import { PhotoWithFallback } from '../elements';
import { isVideoUrl } from '../../utils/photo-helpers';
import type { SocialPost } from '../../types/api/social-post';

/** Get display image URLs from post (excludes video URLs so img/PhotoWithFallback don't break) */
function getPostImageUrls(post: SocialPost): string[] {
  const videoSet = post.video_urls?.length ? new Set(post.video_urls) : null;
  const isVideo = (url: string) => isVideoUrl(url) || (videoSet !== null && videoSet.has(url));
  if (post.image_urls?.length) {
    return post.image_urls.filter((url) => !isVideo(url));
  }
  const attachments = post.photo_attachments || [];
  const sorted = [...attachments].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
  return sorted
    .map((pa) => pa.photo?.large_url || pa.photo?.original_url || pa.photo?.medium_url || pa.photo?.thumbnail_url)
    .filter((url): url is string => Boolean(url))
    .filter((url) => !isVideo(url));
}

interface SocialMediaGridProps {
  socialPosts?: SocialPost[] | null;
  title?: string;
  subtitle?: string;
  recentLabel?: string;
  viewOnLabel?: string;
  emptyMessage?: string;
}

const formatDate = (dateString?: string, recentLabel: string = "Recent") => {
  if (!dateString) return recentLabel;
  try {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  } catch {
    return recentLabel;
  }
};

const getPlatformColor = (platform?: string) => {
  const platformLower = platform?.toLowerCase() || '';
  const colors: Record<string, string> = {
    facebook: '#1877F2',
    instagram: '#E4405F',
    twitter: '#1DA1F2',
    linkedin: '#0A66C2',
    youtube: '#FF0000',
  };
  return colors[platformLower] || '#6B625E';
};

export const SocialMediaGrid = ({
  socialPosts: postsData,
  title = "",
  subtitle = "",
  recentLabel = "Recent",
  viewOnLabel = "View on",
  emptyMessage = "No posts available",
}: SocialMediaGridProps) => {
  const posts = Array.isArray(postsData) ? postsData : [];

  return (
    <section className="py-16 md:py-20 lg:py-24 bg-primary">
      <div className="mx-auto max-w-7xl px-4 md:px-8">
        {/* Section Header - Centered */}
        <div className="mx-auto max-w-3xl text-center mb-12 md:mb-16">
          <h2 className="font-display text-4xl font-medium text-fg-primary md:text-5xl mb-4">
            {title}
          </h2>
          {subtitle && (
            <p className="font-body text-lg text-secondary leading-normal">
              {subtitle}
            </p>
          )}
        </div>

        {posts.length > 0 ? (
          <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {posts.map((post) => {
              const images = getPostImageUrls(post);
              const firstImage = images[0] || '';
              const content = post.content_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
              const platform = post.platform || 'social';
              const platformColor = getPlatformColor(platform);
              
              return (
                <div key={post.id} className="flex flex-col bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-shadow duration-300">
                  <div className="w-full h-64 overflow-hidden">
                    <PhotoWithFallback
                      item={post}
                      photoUrl={firstImage}
                      photoAlt={content.substring(0, 50) || ''}
                      fallbackId={post.id}
                      className="w-full h-full object-cover transition-transform duration-300 hover:scale-105"
                    />
                  </div>
                  
                  <div className="p-6 flex flex-col flex-grow">
                    <div className="flex items-center justify-between mb-4">
                      <span 
                        className="text-xs font-body font-semibold uppercase tracking-wide px-3 py-1.5 rounded-full text-white"
                        style={{ backgroundColor: platformColor }}
                      >
                        {platform}
                      </span>
                      <span className="text-xs font-body" style={{ color: 'var(--color-text-brand-secondary)' }}>
                        {formatDate(post.posted_at, recentLabel)}
                      </span>
                    </div>

                    {content && (
                      <p className="font-body text-sm text-tertiary mb-4 flex-grow line-clamp-4">
                        {content}
                      </p>
                    )}

                    {post.platform && (
                      <a
                        href={post.external_post_url || `https://${platform.toLowerCase()}.com`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-body text-sm underline underline-offset-4 hover:no-underline mt-auto transition-colors"
                        style={{ color: 'var(--color-text-brand-accent)' }}
                      >
                        {viewOnLabel} {platform.charAt(0).toUpperCase() + platform.slice(1)}
                      </a>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="font-body text-base text-tertiary">{emptyMessage}</p>
          </div>
        )}
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('social-media-grid', 'barelux', SocialMediaGrid);
