ifixkart-admin/app/(admin)/social-media/page.tsx

1046 lines
46 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef } from 'react';
import {
Share2,
Send,
Sparkles,
Image as ImageIcon,
Video,
CheckCircle2,
AlertCircle,
RefreshCw,
Layers,
Smartphone,
Eye,
Sliders,
Heart,
MessageCircle,
Bookmark,
Radio,
Clock,
ArrowLeft,
Upload,
X,
FileText,
Trash2,
ExternalLink,
Plus
} from 'lucide-react';
import { apiFetch } from '@/services/api/client';
import { API_ENDPOINTS } from '@/services/api/config';
import { toast } from 'sonner';
function InstagramIcon({ className = "w-4 h-4" }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect width="20" height="20" x="2" y="2" rx="5" ry="5" />
<path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
<line x1="17.5" x2="17.51" y1="6.5" y2="6.5" />
</svg>
);
}
function FacebookIcon({ className = "w-4 h-4" }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
</svg>
);
}
function WhatsAppIcon({ className = "w-4 h-4" }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
</svg>
);
}
interface WhatsAppStatus {
connected: boolean;
status: string;
session_id?: string;
session_name?: string;
phone?: string;
pushName?: string;
error?: string;
}
interface SocialStatusResponse {
enabled: boolean;
api_version: string;
app_id: string;
page_id: string;
instagram_id: string;
token_health: {
healthy: boolean;
status_code?: number;
error?: unknown;
};
whatsapp?: WhatsAppStatus;
}
interface PostItem {
id: string;
caption?: string;
message?: string;
media_type?: string;
media_url?: string;
timestamp?: string;
created_time?: string;
permalink?: string;
like_count?: number;
comments_count?: number;
}
// 17 Instagram filters with CSS transform presets
const INSTAGRAM_FILTERS = [
{ name: 'Normal', css: 'none' },
{ name: 'Clarendon', css: 'contrast(120%) saturate(125%)' },
{ name: 'Gingham', css: 'brightness(105%) hue-rotate(-10deg)' },
{ name: 'Moon', css: 'grayscale(100%) contrast(110%) brightness(110%)' },
{ name: 'Lark', css: 'contrast(90%) brightness(115%) saturate(110%)' },
{ name: 'Reyes', css: 'sepia(22%) brightness(110%) contrast(85%) saturate(75%)' },
{ name: 'Juno', css: 'contrast(115%) brightness(115%) saturate(130%)' },
{ name: 'Slumber', css: 'saturate(66%) brightness(105%) sepia(35%)' },
{ name: 'Crema', css: 'sepia(50%) contrast(90%) brightness(110%) saturate(90%)' },
{ name: 'Ludwig', css: 'contrast(105%) brightness(105%) saturate(95%)' },
{ name: 'Aden', css: 'sepia(20%) brightness(115%) saturate(140%) hue-rotate(20deg)' },
{ name: 'Perpetua', css: 'contrast(105%) brightness(110%) saturate(110%)' },
{ name: 'Amaro', css: 'hue-rotate(-10deg) contrast(90%) brightness(110%) saturate(130%)' },
{ name: 'Mayfair', css: 'contrast(110%) saturate(110%)' },
{ name: 'Rise', css: 'brightness(105%) sepia(20%) contrast(90%)' },
{ name: 'Valencia', css: 'contrast(108%) brightness(108%) sepia(8%)' },
{ name: 'X-Pro II', css: 'contrast(130%) saturate(125%) sepia(30%)' },
];
export default function SocialMediaPublisherPage() {
const [socialStatus, setSocialStatus] = useState<SocialStatusResponse | null>(null);
const [loadingStatus, setLoadingStatus] = useState<boolean>(true);
// Composer Form - Clean initial state (Zero static mock data)
const [caption, setCaption] = useState<string>('');
const [mediaUrl, setMediaUrl] = useState<string>('');
const [mediaType, setMediaType] = useState<'IMAGE' | 'VIDEO'>('IMAGE');
const [publishTarget, setPublishTarget] = useState<'all' | 'both' | 'instagram' | 'facebook' | 'whatsapp'>('all');
const [selectedFilter, setSelectedFilter] = useState<string>('Normal');
const [previewPlatform, setPreviewPlatform] = useState<'instagram' | 'whatsapp' | 'facebook'>('instagram');
const [publishing, setPublishing] = useState<boolean>(false);
const [isUploading, setIsUploading] = useState<boolean>(false);
const [uploadedFileName, setUploadedFileName] = useState<string>('');
// Live posts from connected accounts
const [postsTab, setPostsTab] = useState<'instagram' | 'facebook'>('instagram');
const [recentPosts, setRecentPosts] = useState<PostItem[]>([]);
const [loadingPosts, setLoadingPosts] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const fetchStatus = async () => {
try {
setLoadingStatus(true);
const res = await apiFetch<SocialStatusResponse>(API_ENDPOINTS.SOCIAL_META_STATUS);
if (res) setSocialStatus(res);
} catch (err: unknown) {
console.error('Failed to load social status:', err);
} finally {
setLoadingStatus(false);
}
};
const fetchRecentPosts = async (platform: 'instagram' | 'facebook') => {
try {
setLoadingPosts(true);
const endpoint = platform === 'instagram'
? API_ENDPOINTS.SOCIAL_INSTAGRAM_POSTS
: API_ENDPOINTS.SOCIAL_FACEBOOK_POSTS;
const res = await apiFetch<{ status: string; count: number; data: PostItem[] }>(endpoint);
setRecentPosts(res?.data || []);
} catch (err: unknown) {
console.error(`Failed to load ${platform} posts:`, err);
setRecentPosts([]);
} finally {
setLoadingPosts(false);
}
};
useEffect(() => {
fetchStatus();
fetchRecentPosts(postsTab);
}, [postsTab]);
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Validate size (max 50MB)
if (file.size > 50 * 1024 * 1024) {
toast.error('File exceeds maximum upload limit of 50MB');
return;
}
try {
setIsUploading(true);
const formData = new FormData();
formData.append('file', file);
const res = await apiFetch<{
status: string;
url: string;
remote_url?: string;
filename?: string
}>(
API_ENDPOINTS.SOCIAL_META_UPLOAD,
{
method: 'POST',
body: formData
}
);
if (res && res.url) {
const isVideo = file.type.startsWith('video/');
setMediaType(isVideo ? 'VIDEO' : 'IMAGE');
setMediaUrl(res.url);
setUploadedFileName(file.name);
toast.success(`Uploaded successfully: ${file.name}`);
} else {
toast.error('Failed to retrieve uploaded media URL');
}
} catch (err: unknown) {
console.error('Media upload error:', err);
toast.error('Upload failed. Ensure server connection is active.');
} finally {
setIsUploading(false);
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
const handleClearMedia = () => {
setMediaUrl('');
setUploadedFileName('');
};
const handlePublish = async () => {
const trimmedCaption = caption.trim();
if (!trimmedCaption) {
toast.error('Please enter a caption for your post or status');
return;
}
if (!mediaUrl.trim() && publishTarget !== 'whatsapp') {
toast.error('Please upload an image or video for Instagram/Facebook posts');
return;
}
try {
setPublishing(true);
const res = await apiFetch<{
status: string;
message: string;
results?: Record<string, { success: boolean; error?: string; status_code?: number; session_state?: string; data?: unknown }>
}>(
API_ENDPOINTS.SOCIAL_META_PUBLISH,
{
method: 'POST',
body: JSON.stringify({
caption: trimmedCaption,
media_url: mediaUrl,
media_type: mediaType,
target: publishTarget,
filter: selectedFilter
})
}
);
const results = res?.results;
if (results) {
if (results.whatsapp) {
if (results.whatsapp.success) {
toast.success('WhatsApp: Status posted successfully!');
} else if (results.whatsapp.session_state === 'QR_READY') {
toast.warning('WhatsApp: OpenWA session requires QR pairing on :8088 before posting.');
} else {
toast.error(`WhatsApp: ${results.whatsapp.error || 'Failed to update status'}`);
}
}
if (results.instagram) {
if (results.instagram.success) {
toast.success('Instagram: Post published to feed!');
} else {
toast.error('Instagram: Meta token requires refresh or approval.');
}
}
if (results.facebook) {
if (results.facebook.success) {
toast.success('Facebook: Post published to Page feed!');
} else {
toast.error('Facebook: Meta token requires refresh.');
}
}
} else {
toast.success(res?.message || 'Social media post submitted to publishing queue!');
}
// Refresh recent posts
fetchRecentPosts(postsTab);
} catch (err: unknown) {
console.error('Publishing failed:', err);
toast.error('Publication request failed. Please verify API access.');
} finally {
setPublishing(false);
}
};
const activeFilterCss = INSTAGRAM_FILTERS.find(f => f.name === selectedFilter)?.css || 'none';
return (
<div className="space-y-6 pb-12">
{/* Hidden File Input for Real Device Media Upload */}
<input
ref={fileInputRef}
type="file"
accept="image/*,video/*"
onChange={handleFileUpload}
className="hidden"
/>
{/* Top Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-border/60 pb-5">
<div>
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-primary mb-1">
<Share2 className="w-4 h-4 text-primary" />
<span>Omnichannel Social Media & Status Platform</span>
</div>
<h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-foreground">
Social Media Hub
</h1>
<p className="text-sm text-muted-foreground mt-1">
Compose, apply visual filters, and publish simultaneously to Instagram, Facebook, and WhatsApp Status.
</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={fetchStatus}
disabled={loadingStatus}
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-xl bg-card border border-border shadow-xs hover:bg-muted/60 transition disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loadingStatus ? 'animate-spin text-primary' : 'text-muted-foreground'}`} />
<span>Refresh Gateway Status</span>
</button>
</div>
</div>
{/* Multi-Channel Status Banner - Fully Dynamic Real Data */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-3 p-4 rounded-2xl bg-card border border-border/80 text-xs">
{/* Instagram Status */}
<div className="flex items-center justify-between p-2.5 rounded-xl bg-muted/40">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-pink-500/10 text-pink-500">
<InstagramIcon className="w-4 h-4" />
</div>
<div>
<span className="text-muted-foreground block text-[10px]">Instagram Business</span>
<span className="font-mono font-bold text-foreground text-[11px]">
{socialStatus?.instagram_id ? socialStatus.instagram_id : 'Not Configured'}
</span>
</div>
</div>
<span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase ${
socialStatus?.token_health?.healthy
? 'bg-emerald-500/15 text-emerald-600'
: socialStatus?.instagram_id
? 'bg-amber-500/15 text-amber-600'
: 'bg-muted text-muted-foreground'
}`}>
{socialStatus?.token_health?.healthy
? 'Active'
: socialStatus?.instagram_id
? 'Token Expired'
: 'Not Set'}
</span>
</div>
{/* Facebook Status */}
<div className="flex items-center justify-between p-2.5 rounded-xl bg-muted/40">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-blue-500/10 text-blue-500">
<FacebookIcon className="w-4 h-4" />
</div>
<div>
<span className="text-muted-foreground block text-[10px]">Facebook Page ID</span>
<span className="font-mono font-bold text-foreground text-[11px]">
{socialStatus?.page_id ? socialStatus.page_id : 'Not Configured'}
</span>
</div>
</div>
<span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase ${
socialStatus?.token_health?.healthy
? 'bg-emerald-500/15 text-emerald-600'
: socialStatus?.page_id
? 'bg-blue-500/15 text-blue-600'
: 'bg-muted text-muted-foreground'
}`}>
{socialStatus?.token_health?.healthy
? 'Active'
: socialStatus?.page_id
? 'Sandbox Ready'
: 'Not Set'}
</span>
</div>
{/* WhatsApp OpenWA Status */}
<div className="flex items-center justify-between p-2.5 rounded-xl bg-muted/40">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-emerald-500/10 text-emerald-500">
<WhatsAppIcon className="w-4 h-4" />
</div>
<div>
<span className="text-muted-foreground block text-[10px]">WhatsApp Gateway (:8088)</span>
<span className="font-mono font-bold text-foreground text-[11px]">
{socialStatus?.whatsapp?.phone
? `+${socialStatus.whatsapp.phone}`
: (socialStatus?.whatsapp?.session_name || 'OpenWA Gateway')}
</span>
</div>
</div>
<span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase ${
socialStatus?.whatsapp?.connected
? 'bg-emerald-500/15 text-emerald-600'
: socialStatus?.whatsapp?.status === 'QR_READY'
? 'bg-amber-500/15 text-amber-600'
: 'bg-blue-500/15 text-blue-600'
}`}>
{socialStatus?.whatsapp?.connected
? 'Connected'
: socialStatus?.whatsapp?.status === 'QR_READY'
? 'QR Ready'
: (socialStatus?.whatsapp?.status || 'Offline')}
</span>
</div>
</div>
{/* Main Composer & Live Mobile Mockup Grid */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Left: Composer Form (7 cols) */}
<div className="lg:col-span-7 space-y-5">
<div className="rounded-2xl border border-border/80 bg-card p-6 shadow-xs space-y-5">
<h2 className="text-base font-bold text-foreground flex items-center gap-2">
<Sparkles className="w-5 h-5 text-primary" />
<span>Compose Omnichannel Social Post / Status</span>
</h2>
{/* Target Selector */}
<div>
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-2">
Publishing Channels
</label>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5">
<button
type="button"
onClick={() => { setPublishTarget('all'); setPreviewPlatform('instagram'); }}
className={`flex flex-col items-center justify-center p-3 rounded-xl border text-xs font-semibold transition gap-1.5 ${
publishTarget === 'all'
? 'bg-primary/10 border-primary text-primary shadow-xs ring-1 ring-primary/40'
: 'border-border/80 text-muted-foreground hover:bg-muted/50'
}`}
>
<div className="flex items-center gap-1">
<InstagramIcon className="w-3.5 h-3.5 text-pink-500" />
<FacebookIcon className="w-3.5 h-3.5 text-blue-500" />
<WhatsAppIcon className="w-3.5 h-3.5 text-emerald-500" />
</div>
<span className="text-[11px] font-bold">All 3 Channels</span>
</button>
<button
type="button"
onClick={() => { setPublishTarget('whatsapp'); setPreviewPlatform('whatsapp'); }}
className={`flex flex-col items-center justify-center p-3 rounded-xl border text-xs font-semibold transition gap-1.5 ${
publishTarget === 'whatsapp'
? 'bg-emerald-500/15 border-emerald-500 text-emerald-600 dark:text-emerald-400 shadow-xs ring-1 ring-emerald-500/40'
: 'border-border/80 text-muted-foreground hover:bg-muted/50'
}`}
>
<WhatsAppIcon className="w-4 h-4 text-emerald-500" />
<span className="text-[11px] font-bold">WhatsApp Status</span>
</button>
<button
type="button"
onClick={() => { setPublishTarget('instagram'); setPreviewPlatform('instagram'); }}
className={`flex flex-col items-center justify-center p-3 rounded-xl border text-xs font-semibold transition gap-1.5 ${
publishTarget === 'instagram'
? 'bg-pink-500/15 border-pink-500 text-pink-600 dark:text-pink-400 shadow-xs ring-1 ring-pink-500/40'
: 'border-border/80 text-muted-foreground hover:bg-muted/50'
}`}
>
<InstagramIcon className="w-4 h-4 text-pink-500" />
<span className="text-[11px] font-bold">Instagram Only</span>
</button>
<button
type="button"
onClick={() => { setPublishTarget('facebook'); setPreviewPlatform('facebook'); }}
className={`flex flex-col items-center justify-center p-3 rounded-xl border text-xs font-semibold transition gap-1.5 ${
publishTarget === 'facebook'
? 'bg-blue-500/15 border-blue-500 text-blue-600 dark:text-blue-400 shadow-xs ring-1 ring-blue-500/40'
: 'border-border/80 text-muted-foreground hover:bg-muted/50'
}`}
>
<FacebookIcon className="w-4 h-4 text-blue-500" />
<span className="text-[11px] font-bold">Facebook Only</span>
</button>
</div>
</div>
{/* Real Media Upload & Source */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
Media Attachment (Image / Video)
</label>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setMediaType('IMAGE')}
className={`px-2 py-0.5 text-[11px] font-semibold rounded-md transition ${
mediaType === 'IMAGE' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground'
}`}
>
Image
</button>
<button
type="button"
onClick={() => setMediaType('VIDEO')}
className={`px-2 py-0.5 text-[11px] font-semibold rounded-md transition ${
mediaType === 'VIDEO' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground'
}`}
>
Video / Reel
</button>
</div>
</div>
{/* Upload Dropzone / Action Bar */}
{mediaUrl ? (
<div className="flex items-center justify-between p-3 rounded-xl bg-muted/60 border border-border">
<div className="flex items-center gap-3 overflow-hidden">
<div className="w-12 h-12 rounded-lg bg-card border border-border overflow-hidden flex-shrink-0 flex items-center justify-center">
{mediaType === 'VIDEO' ? (
<Video className="w-5 h-5 text-primary" />
) : (
<img
src={mediaUrl}
alt="Uploaded media"
className="w-full h-full object-cover"
style={{ filter: activeFilterCss }}
/>
)}
</div>
<div className="overflow-hidden">
<p className="text-xs font-bold text-foreground truncate max-w-[240px]">
{uploadedFileName || mediaUrl.split('/').pop() || 'Attached Media'}
</p>
<span className="text-[10px] text-muted-foreground uppercase font-mono block">
{mediaType} &bull; Ready to publish
</span>
</div>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="px-2.5 py-1 text-xs font-medium rounded-lg bg-card border border-border hover:bg-muted text-foreground transition"
>
Replace
</button>
<button
type="button"
onClick={handleClearMedia}
className="p-1.5 text-muted-foreground hover:text-red-500 rounded-lg hover:bg-red-500/10 transition"
title="Remove media"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
) : (
<div
onClick={() => fileInputRef.current?.click()}
className="cursor-pointer border-2 border-dashed border-border/80 hover:border-primary/60 rounded-xl p-5 flex flex-col items-center justify-center text-center transition group bg-muted/20 hover:bg-muted/40"
>
<div className="w-10 h-10 rounded-full bg-primary/10 group-hover:bg-primary/20 text-primary flex items-center justify-center mb-2 transition">
{isUploading ? (
<RefreshCw className="w-5 h-5 animate-spin" />
) : (
<Upload className="w-5 h-5" />
)}
</div>
<p className="text-xs font-bold text-foreground">
{isUploading ? 'Uploading Media...' : 'Click to upload image or video'}
</p>
<p className="text-[11px] text-muted-foreground mt-0.5">
Supports JPG, PNG, WEBP, MP4, MOV (up to 50MB)
</p>
</div>
)}
{/* Direct URL input fallback */}
<div className="pt-1">
<input
type="text"
value={mediaUrl}
onChange={(e) => {
setMediaUrl(e.target.value);
setUploadedFileName('');
}}
placeholder="Or paste external media URL (https://... or /uploads/...)"
className="w-full px-3 py-1.5 text-xs rounded-xl bg-muted/40 border border-border/70 focus:outline-none focus:ring-1 focus:ring-primary text-foreground font-mono"
/>
</div>
</div>
{/* Caption Textarea - Clean, No Static Text */}
<div>
<div className="flex items-center justify-between mb-2">
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
Post Caption & WhatsApp Status Text
</label>
<span className="text-[11px] text-muted-foreground font-mono">
{caption.length} / 2200 chars
</span>
</div>
<textarea
rows={4}
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="Enter post caption or WhatsApp status text..."
className="w-full p-3 text-xs rounded-xl bg-muted/50 border border-border focus:outline-none focus:ring-1 focus:ring-primary text-foreground resize-none leading-relaxed"
/>
<div className="flex flex-wrap items-center gap-1.5 mt-2">
<span className="text-[10px] text-muted-foreground uppercase font-semibold mr-1">Quick Tags:</span>
{['#iFixKart', '#iPhoneRepair', '#LaptopService', '#OriginalParts', '#FastDelivery'].map((tag) => (
<button
key={tag}
type="button"
onClick={() => {
if (!caption.includes(tag)) {
setCaption((prev) => (prev ? `${prev} ${tag}` : tag));
}
}}
className="px-2 py-0.5 rounded-md bg-muted/80 text-[10px] font-semibold text-muted-foreground hover:text-foreground hover:bg-muted transition"
>
{tag}
</button>
))}
</div>
</div>
{/* 17 Instagram Filters Carousel - Dynamic Swatches */}
<div>
<div className="flex items-center justify-between mb-2.5">
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
<Sliders className="w-3.5 h-3.5" />
<span>17 Visual Filter Presets</span>
</label>
{selectedFilter !== 'Normal' && (
<button
type="button"
onClick={() => setSelectedFilter('Normal')}
className="text-[10px] font-semibold text-primary hover:underline"
>
Reset Filter
</button>
)}
</div>
<div className="flex gap-2.5 overflow-x-auto pb-2 scrollbar-none">
{INSTAGRAM_FILTERS.map((f) => (
<button
key={f.name}
type="button"
onClick={() => setSelectedFilter(f.name)}
className={`flex-shrink-0 flex flex-col items-center gap-1.5 p-2 rounded-xl border text-center transition ${
selectedFilter === f.name
? 'border-primary bg-primary/10 shadow-xs'
: 'border-border/80 bg-card hover:bg-muted/50'
}`}
>
<div
className="w-14 h-14 rounded-lg overflow-hidden border border-border/60 flex items-center justify-center transition"
style={{
filter: f.css,
backgroundImage: mediaUrl && mediaType === 'IMAGE'
? `url(${mediaUrl})`
: 'linear-gradient(135deg, #6366f1 0%, #ec4899 50%, #f59e0b 100%)',
backgroundSize: 'cover',
backgroundPosition: 'center'
}}
>
{(!mediaUrl || mediaType === 'VIDEO') && (
<Sparkles className="w-4 h-4 text-white/90 drop-shadow-sm" />
)}
</div>
<span className="text-[10px] font-bold text-foreground">{f.name}</span>
</button>
))}
</div>
</div>
{/* Publish CTA Button */}
<div className="pt-2">
<button
type="button"
onClick={handlePublish}
disabled={publishing}
className="w-full flex items-center justify-center gap-2 py-3 px-6 rounded-xl bg-gradient-to-r from-emerald-600 via-pink-600 to-indigo-600 hover:from-emerald-700 hover:to-indigo-700 text-white font-bold text-sm shadow-md transition disabled:opacity-50"
>
{publishing ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : (
<Send className="w-4 h-4" />
)}
<span>
{publishing
? 'Publishing Across Channels...'
: publishTarget === 'all'
? 'Publish to All 3 Channels (IG + FB + WA)'
: publishTarget === 'whatsapp'
? 'Publish to WhatsApp Status'
: `Publish to ${publishTarget.toUpperCase()}`
}
</span>
</button>
</div>
</div>
</div>
{/* Right: Live Interactive Mobile Mockup (5 cols) */}
<div className="lg:col-span-5 flex flex-col items-center">
{/* Mockup Preview Channel Selector */}
<div className="flex items-center gap-2 mb-3 bg-card border border-border/80 p-1 rounded-xl text-xs">
<button
type="button"
onClick={() => setPreviewPlatform('instagram')}
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg font-semibold transition ${
previewPlatform === 'instagram' ? 'bg-pink-500/15 text-pink-600 dark:text-pink-400' : 'text-muted-foreground'
}`}
>
<InstagramIcon className="w-3.5 h-3.5" />
<span>Instagram</span>
</button>
<button
type="button"
onClick={() => setPreviewPlatform('whatsapp')}
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg font-semibold transition ${
previewPlatform === 'whatsapp' ? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400' : 'text-muted-foreground'
}`}
>
<WhatsAppIcon className="w-3.5 h-3.5" />
<span>WhatsApp Status</span>
</button>
<button
type="button"
onClick={() => setPreviewPlatform('facebook')}
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg font-semibold transition ${
previewPlatform === 'facebook' ? 'bg-blue-500/15 text-blue-600 dark:text-blue-400' : 'text-muted-foreground'
}`}
>
<FacebookIcon className="w-3.5 h-3.5" />
<span>Facebook</span>
</button>
</div>
<div className="w-full max-w-[340px] rounded-[32px] border-[6px] border-border bg-card shadow-2xl overflow-hidden text-card-foreground">
{previewPlatform === 'whatsapp' ? (
/* WhatsApp Status Preview */
<div className="bg-[#111b21] text-white min-h-[460px] flex flex-col justify-between p-3 select-none">
{/* Status Bar & Header */}
<div>
{/* WhatsApp Stories Progress Bar */}
<div className="w-full flex gap-1 mb-3 pt-1">
<div className="h-1 flex-1 bg-white/90 rounded-full" />
<div className="h-1 flex-1 bg-white/30 rounded-full" />
</div>
{/* WhatsApp Profile Status Header */}
<div className="flex items-center justify-between text-white">
<div className="flex items-center gap-2">
<ArrowLeft className="w-4 h-4 text-white/80" />
<div className="w-8 h-8 rounded-full border-2 border-emerald-400 p-[1px]">
<div className="w-full h-full rounded-full bg-emerald-600 flex items-center justify-center font-bold text-[10px] text-white">
iK
</div>
</div>
<div>
<span className="text-xs font-bold block leading-none">iFixKart Official</span>
<span className="text-[10px] text-white/60">Just now</span>
</div>
</div>
<span className="text-white/70 text-xs font-bold">&bull;&bull;&bull;</span>
</div>
</div>
{/* Status Media / Text Center */}
<div className="my-auto w-full aspect-square rounded-2xl overflow-hidden border border-white/10 relative flex items-center justify-center bg-black/40">
{mediaUrl ? (
mediaType === 'VIDEO' ? (
<video
src={mediaUrl}
controls
autoPlay
loop
muted
className="w-full h-full object-cover"
/>
) : (
<img
src={mediaUrl}
alt="WhatsApp Status"
className="w-full h-full object-cover transition-all duration-300"
style={{ filter: activeFilterCss }}
/>
)
) : caption.trim() ? (
<div className="w-full h-full bg-gradient-to-br from-[#075E54] to-[#128C7E] flex items-center justify-center p-6 text-center">
<p className="text-sm font-semibold text-white leading-relaxed line-clamp-6">
{caption}
</p>
</div>
) : (
<div
onClick={() => fileInputRef.current?.click()}
className="cursor-pointer flex flex-col items-center justify-center text-center p-6 text-white/60 hover:text-white transition"
>
<ImageIcon className="w-8 h-8 mb-2 opacity-50" />
<span className="text-xs font-medium">No Status Media</span>
<span className="text-[10px] opacity-70 mt-1">Upload an image/video or type text</span>
</div>
)}
<div className="absolute top-2 right-2 px-2 py-0.5 rounded-full bg-black/60 text-[9px] font-mono text-emerald-400 border border-emerald-500/30">
WA Status &bull; 24h
</div>
</div>
{/* Status Bottom Overlay & Caption */}
<div className="space-y-2 pt-2">
{caption.trim() && mediaUrl ? (
<p className="text-xs text-white/95 text-center px-2 line-clamp-3 leading-relaxed">
{caption}
</p>
) : !caption.trim() && !mediaUrl ? (
<p className="text-[11px] text-white/40 text-center italic">
Status caption or text preview
</p>
) : null}
<div className="w-full py-2 rounded-xl bg-white/10 text-center text-[11px] font-semibold text-white/80 flex items-center justify-center gap-1.5">
<span>Reply</span>
<span className="text-[9px]">&and;</span>
</div>
</div>
</div>
) : (
/* Instagram / Facebook Feed Post Preview */
<div>
{/* Mockup Header */}
<div className="p-3 border-b border-border/60 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-full bg-gradient-to-tr from-amber-500 to-pink-500 p-[1.5px]">
<div className="w-full h-full rounded-full bg-card flex items-center justify-center font-bold text-[10px] text-primary">
iK
</div>
</div>
<div>
<span className="text-xs font-bold block leading-none">ifixkart_official</span>
<span className="text-[9px] text-muted-foreground">
{previewPlatform === 'facebook' ? 'Official Page' : 'Official Channel'}
</span>
</div>
</div>
<span className="text-xs text-muted-foreground">&bull;&bull;&bull;</span>
</div>
{/* Media Area */}
<div className="relative aspect-square w-full bg-muted overflow-hidden flex items-center justify-center">
{mediaUrl ? (
mediaType === 'VIDEO' ? (
<video
src={mediaUrl}
controls
autoPlay
loop
muted
className="w-full h-full object-cover"
/>
) : (
<img
src={mediaUrl}
alt="Feed Post"
className="w-full h-full object-cover transition-all duration-300"
style={{ filter: activeFilterCss }}
/>
)
) : (
<div
onClick={() => fileInputRef.current?.click()}
className="cursor-pointer flex flex-col items-center justify-center text-center p-6 text-muted-foreground hover:text-foreground transition"
>
<ImageIcon className="w-10 h-10 mb-2 opacity-40" />
<span className="text-xs font-bold">No Media Attached</span>
<span className="text-[10px] opacity-70 mt-1">Click to attach photo or video</span>
</div>
)}
{mediaUrl && (
<span className="absolute bottom-2 right-2 px-2 py-0.5 rounded-full bg-black/60 text-white text-[9px] font-mono backdrop-blur-xs">
{selectedFilter}
</span>
)}
</div>
{/* Engagement Action Bar */}
<div className="p-3 space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Heart className="w-5 h-5 text-muted-foreground hover:text-red-500 transition cursor-pointer" />
<MessageCircle className="w-5 h-5 text-muted-foreground cursor-pointer" />
<Send className="w-5 h-5 text-muted-foreground cursor-pointer" />
</div>
<Bookmark className="w-5 h-5 text-muted-foreground cursor-pointer" />
</div>
{/* Real-time preview indicator (Zero fake mock likes) */}
<div className="text-[11px] text-muted-foreground font-medium flex items-center gap-1.5">
<Radio className="w-3 h-3 text-emerald-500 animate-pulse" />
<span>Live Preview &bull; Metrics sync after posting</span>
</div>
{/* Caption Text */}
<div className="text-xs text-foreground leading-relaxed line-clamp-3">
<span className="font-bold mr-1.5">ifixkart_official</span>
{caption.trim() ? (
<span>{caption}</span>
) : (
<span className="italic text-muted-foreground">Post caption will appear here as you type...</span>
)}
</div>
<div className="text-[10px] text-muted-foreground uppercase pt-1">
Just now &bull; Multi-channel broadcast
</div>
</div>
</div>
)}
</div>
</div>
</div>
{/* Published Posts & Activity Stream (Live Data Feed) */}
<div className="rounded-2xl border border-border/80 bg-card p-6 shadow-xs space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-border/60 pb-3">
<div>
<h3 className="text-sm font-bold text-foreground flex items-center gap-2">
<Layers className="w-4 h-4 text-primary" />
<span>Published Feed & Activity Stream</span>
</h3>
<p className="text-xs text-muted-foreground">
Live posts retrieved directly from connected Meta accounts.
</p>
</div>
<div className="flex items-center gap-2 bg-muted/50 p-1 rounded-xl text-xs">
<button
type="button"
onClick={() => setPostsTab('instagram')}
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg font-semibold transition ${
postsTab === 'instagram' ? 'bg-card text-foreground shadow-xs' : 'text-muted-foreground'
}`}
>
<InstagramIcon className="w-3.5 h-3.5 text-pink-500" />
<span>Instagram Feed</span>
</button>
<button
type="button"
onClick={() => setPostsTab('facebook')}
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg font-semibold transition ${
postsTab === 'facebook' ? 'bg-card text-foreground shadow-xs' : 'text-muted-foreground'
}`}
>
<FacebookIcon className="w-3.5 h-3.5 text-blue-500" />
<span>Facebook Posts</span>
</button>
</div>
</div>
{loadingPosts ? (
<div className="py-12 flex flex-col items-center justify-center text-center">
<RefreshCw className="w-6 h-6 animate-spin text-primary mb-2" />
<p className="text-xs text-muted-foreground">Fetching posts from {postsTab}...</p>
</div>
) : recentPosts.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{recentPosts.map((post) => (
<div
key={post.id}
className="rounded-xl border border-border bg-card overflow-hidden hover:border-primary/50 transition group flex flex-col"
>
{post.media_url ? (
<div className="aspect-square bg-muted overflow-hidden relative">
<img
src={post.media_url}
alt="Post thumbnail"
className="w-full h-full object-cover group-hover:scale-105 transition duration-300"
/>
{post.permalink && (
<a
href={post.permalink}
target="_blank"
rel="noopener noreferrer"
className="absolute top-2 right-2 p-1.5 rounded-full bg-black/60 text-white hover:bg-black/80 transition"
>
<ExternalLink className="w-3.5 h-3.5" />
</a>
)}
</div>
) : (
<div className="aspect-square bg-muted/40 flex items-center justify-center p-4 text-center">
<FileText className="w-8 h-8 text-muted-foreground/50 mb-1" />
</div>
)}
<div className="p-3 flex-1 flex flex-col justify-between space-y-2">
<p className="text-xs text-foreground line-clamp-2">
{post.caption || post.message || 'No caption'}
</p>
<div className="flex items-center justify-between text-[10px] text-muted-foreground pt-1 border-t border-border/40 font-mono">
<span>
{post.timestamp || post.created_time
? new Date(post.timestamp || post.created_time || '').toLocaleDateString()
: 'Recent'}
</span>
{(post.like_count !== undefined) && (
<span className="flex items-center gap-1">
<Heart className="w-3 h-3 text-red-500" />
{post.like_count}
</span>
)}
</div>
</div>
</div>
))}
</div>
) : (
<div className="py-10 flex flex-col items-center justify-center text-center rounded-xl bg-muted/20 border border-dashed border-border/80">
<Share2 className="w-8 h-8 text-muted-foreground/40 mb-2" />
<p className="text-xs font-bold text-foreground">No Published Posts Found</p>
<p className="text-[11px] text-muted-foreground max-w-sm mt-0.5">
Posts published via the composer above or through your Meta Business Suite will appear here in real time.
</p>
</div>
)}
</div>
</div>
);
}