import React, { useState } from 'react'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { DashboardAnalytics } from './dashboard-analytics'; import { TopPagesProducts } from './top-pages-products'; import { __, sprintf, _n } from '../lib/i18n'; interface DashboardData { rootPath: string; lastGenerated: string | null; llmsTxtExists: boolean; llmsTxtUrl: string; llmsTxtSize?: string; postsCount: number; markdownCount: number; itemsInLlms: number; totalAllPostTypes: number; botVisits30Days: number; botClicks30Days: number; imageCount: number; imagesWithoutAlt: Array<{ id: number; url: string; type: string; post_id: number; post_title: string; preview_url: string; }>; postTypeBreakdown?: Array<{ name: string; label: string; total: number; selected: number; in_llms?: number; }>; settings: { post_types: string[]; full_content: boolean; days_to_include: number; delete_on_uninstall: boolean; include_images?: boolean; llm_response_images?: Array<{ id: number; position: 'before' | 'after'; }>; // Keep old fields for backward compatibility llm_response_image_id?: number; llm_response_image_position?: 'before' | 'after'; }; postTypes: Array<{ name: string; label: string; }>; imageData?: { id: number; url: string; preview_url: string; width?: number; height?: number; } | null; pluginVersion: string; wordpressVersion: string; woocommerce?: { active: boolean; version: string | null; product_count: number; currency: string; currency_symbol: string; }; llmsFullInfo?: { exists: boolean; size: number; size_formatted: string; post_count: number; warning: number | null; }; } interface DashboardProps { data: DashboardData; onGenerateNow: () => Promise<{ success: boolean; message: string; timestamp?: string }>; } export function Dashboard({ data, onGenerateNow }: DashboardProps) { // Log all dashboard data to console for debugging console.log('Dashboard Data:', { rootPath: data.rootPath, lastGenerated: data.lastGenerated, llmsTxtExists: data.llmsTxtExists, llmsTxtUrl: data.llmsTxtUrl, llmsTxtSize: data.llmsTxtSize, postsCount: data.postsCount, markdownCount: data.markdownCount, settings: data.settings, postTypes: data.postTypes, imageData: data.imageData, pluginVersion: data.pluginVersion, wordpressVersion: data.wordpressVersion }); const [isGenerating, setIsGenerating] = useState(false); const [generateMessage, setGenerateMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null); const [dropdownOpen, setDropdownOpen] = useState(false); const dropdownRef = React.useRef(null); // Alt text modal state const [isAltTextModalOpen, setIsAltTextModalOpen] = useState(false); const [imagesWithoutAlt, setImagesWithoutAlt] = useState(data.imagesWithoutAlt || []); const [imageAltTexts, setImageAltTexts] = useState>({}); const [isUpdatingAltText, setIsUpdatingAltText] = useState(false); // Calculate AI availability score (percentage of site covered in llms.txt) const calculateAIAvailabilityScore = () => { if (data.totalAllPostTypes === 0) return 0; // Calculate: (items actually in llms.txt / total of all post types) * 100 return Math.round((data.itemsInLlms / Math.max(data.totalAllPostTypes, 1)) * 100); }; // Initialize alt text fields when modal opens or images change React.useEffect(() => { if (isAltTextModalOpen && imagesWithoutAlt.length > 0) { console.log('Initializing alt text fields for', imagesWithoutAlt.length, 'images'); const initialAltTexts: Record = {}; imagesWithoutAlt.forEach(image => { if (image.id > 0) { // Generate a default alt text based on post title initialAltTexts[image.id] = `Image from ${image.post_title}`; } }); // Only set if we have values to avoid overwriting user input if (Object.keys(initialAltTexts).length > 0) { console.log('Setting initial alt texts:', initialAltTexts); setImageAltTexts(initialAltTexts); } } }, [isAltTextModalOpen, imagesWithoutAlt]); // Close dropdown when clicking outside React.useEffect(() => { function handleClickOutside(event: MouseEvent) { if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { setDropdownOpen(false); } } document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); const handleGenerateNow = async () => { setIsGenerating(true); setGenerateMessage(null); try { const result = await onGenerateNow(); setGenerateMessage({ type: result.success ? 'success' : 'error', text: result.message }); // Clear message after 5 seconds setTimeout(() => setGenerateMessage(null), 5000); } catch (error) { setGenerateMessage({ type: 'error', text: __('An error occurred while generating files.', 'llmagnet-llm-txt-generator') }); } finally { setIsGenerating(false); } }; // State for global success message const [globalSuccessMessage, setGlobalSuccessMessage] = useState(''); const aiAvailabilityScore = calculateAIAvailabilityScore(); return (
{/* Global success message */} {globalSuccessMessage && (
{globalSuccessMessage}
)} {/* Header */}

{__('LLMagnet Dashboard', 'llmagnet-llm-txt-generator')}

{/* Generate Button with Dropdown */}
{/* Dropdown Menu */} {dropdownOpen && ( )}

{__('Manage your LLMS.txt file and LLM response settings', 'llmagnet-llm-txt-generator')}

{/* Status Overview - New AI Metrics */}

{__('Overview Statistics', 'llmagnet-llm-txt-generator')}

{/* AI Availability Score Card */}
{__('AI Availability Score', 'llmagnet-llm-txt-generator')}
{/* Tooltip */}

{__('Coverage Calculation', 'llmagnet-llm-txt-generator')}

{__('Formula: (Items in LLMS.txt ÷ Total Items) × 100', 'llmagnet-llm-txt-generator')}

{data.postTypeBreakdown && data.postTypeBreakdown.length > 0 ? ( <>

{__('Breakdown by Post Type:', 'llmagnet-llm-txt-generator')}

{data.postTypeBreakdown.map((pt) => (
{pt.label}: {pt.in_llms || 0} / {pt.total} {pt.total > (pt.in_llms || 0) && ( ({sprintf(__('%d missing', 'llmagnet-llm-txt-generator'), pt.total - (pt.in_llms || 0))}) )}
))}
{__('Total:', 'llmagnet-llm-txt-generator')} {data.itemsInLlms} / {data.totalAllPostTypes} {data.totalAllPostTypes > data.itemsInLlms && ( ({sprintf(__('%d missing', 'llmagnet-llm-txt-generator'), data.totalAllPostTypes - data.itemsInLlms)}) )}
) : (

{sprintf(__('%1$d items included out of %2$d total items', 'llmagnet-llm-txt-generator'), data.itemsInLlms, data.totalAllPostTypes)}

)}
{__('Site coverage in llms.txt', 'llmagnet-llm-txt-generator')}
= 75 ? '#16a34a' : aiAvailabilityScore >= 50 ? '#eab308' : '#ea580c'} strokeWidth="8" strokeDasharray={`${(aiAvailabilityScore / 100) * 282.7} 282.7`} strokeLinecap="round" style={{ transform: 'rotate(-90deg)', transformOrigin: '50% 50%' }} /> = 75 ? '#16a34a' : aiAvailabilityScore >= 50 ? '#eab308' : '#ea580c'} > {aiAvailabilityScore}%
{/* Bot Visits Last 30 Days Card */}
{__('Bot Visits (30 Days)', 'llmagnet-llm-txt-generator')}
{data.botVisits30Days.toLocaleString()}
{__('Crawler activity', 'llmagnet-llm-txt-generator')}
{/* Clicks Card - Not Ready Yet */}
{__('Clicks (30 Days)', 'llmagnet-llm-txt-generator')}
{data.botClicks30Days.toLocaleString()}
{__('Bot UTM clicks', 'llmagnet-llm-txt-generator')}
{/* Generate Message Section */} {generateMessage && (
{generateMessage.text}
)} {/* Analytics Summary */}
{/* Bot Analytics */}
{/* Pages Analytics Overview */}
{/* Content Settings & System Information moved to separate pages */} {/* Alt Text Modal */} {isAltTextModalOpen && (

{__('Fix Missing Alt Text', 'llmagnet-llm-txt-generator')}

{sprintf( _n( '%d image is missing alt text. Adding descriptive alt text improves accessibility and can help LLMs better understand your images.', '%d images are missing alt text. Adding descriptive alt text improves accessibility and can help LLMs better understand your images.', imagesWithoutAlt.length, 'llmagnet-llm-txt-generator' ), imagesWithoutAlt.length )}

{/* Direct HTML form submission as a last resort */}
{ e.preventDefault(); console.log('Form submitted'); // We'll handle the submission manually return false; }} >
{imagesWithoutAlt.map((image) => (
{ // Fallback if thumbnail doesn't load const target = e.target as HTMLImageElement; target.onerror = null; target.src = image.url; }} />

{image.post_title}

{sprintf(__('Type: %s image', 'llmagnet-llm-txt-generator'), image.type.charAt(0).toUpperCase() + image.type.slice(1))}
setImageAltTexts({...imageAltTexts, [image.id]: e.target.value})} placeholder={__('Describe this image...', 'llmagnet-llm-txt-generator')} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" /> {/* Make sure we have a valid numeric ID */} {image && image.id && Number(image.id) > 0 && ( )}
))}
({ id: parseInt(id), alt_text: imageAltTexts[parseInt(id)] })) )} />
{/* Direct link as an absolute last resort */} {/*

Important: If the Save button doesn't work, please use this direct link instead:

Click to Update All Images with Alt Text

This will open a new window, add placeholder alt text to all images without alt text, regenerate the llms.txt file, and then close automatically.

Note: This will use "Image from [Post Title]" as the alt text for all images.

Debug Info:

Images without alt: {imagesWithoutAlt.length}

Image alt texts entries: {Object.keys(imageAltTexts).length}

First few images without alt:

                        {JSON.stringify(imagesWithoutAlt.slice(0, 2), null, 2)}
                      
*/}
)}
); }