import React, { useEffect, useState } from 'react'; import { Box, Card, CardContent, Typography, Button, Grid, Chip, Dialog, DialogTitle, DialogContent, DialogActions, List, ListItem, ListItemIcon, ListItemText, Alert, Tooltip, CircularProgress, LinearProgress } from '@mui/material'; import { Search as SearchIcon, Analytics as AnalyticsIcon, Check as CheckIcon, Insights as InsightsIcon, CheckCircleOutline as CheckCircleIcon, AutoAwesome as AIIcon } from '@mui/icons-material'; import { apiClient, longRunningApiClient } from '../../../api/client'; import { SitemapBenchmarkResults } from './SitemapBenchmarkResults'; import { StrategicInsightsResults } from './StrategicInsightsResults'; export const ComingSoonSection: React.FC<{ missingData?: boolean }> = ({ missingData = false }) => { const [openModal, setOpenModal] = useState(false); const [selectedFeature, setSelectedFeature] = useState(null); const [scheduledStatus, setScheduledStatus] = useState(null); const [sitemapBenchmarkRunning, setSitemapBenchmarkRunning] = useState(false); const [sitemapBenchmarkError, setSitemapBenchmarkError] = useState(null); const [sitemapBenchmarkData, setSitemapBenchmarkData] = useState(null); const [loadingBenchmarkData, setLoadingBenchmarkData] = useState(false); const [isLongRunning, setIsLongRunning] = useState(false); const [strategicInsightsRunning, setStrategicInsightsRunning] = useState(false); const [strategicInsightsError, setStrategicInsightsError] = useState(null); const [strategicInsightsData, setStrategicInsightsData] = useState(null); // const [loadingStrategicHistory, setLoadingStrategicHistory] = useState(false); useEffect(() => { const loadStatus = async () => { try { const res = await apiClient.get('/api/onboarding/step3/scheduled-tasks-status'); setScheduledStatus(res.data); // If report is available, fetch the full data if (res.data?.competitive_sitemap_benchmarking?.report?.available) { fetchBenchmarkData(); } } catch { setScheduledStatus(null); } }; const loadHistory = async () => { // setLoadingStrategicHistory(true); try { const res = await apiClient.get('/api/seo-dashboard/strategic-insights/history'); if (res.data?.history?.length > 0) { setStrategicInsightsData(res.data.history[0]); // Show latest } } catch (e) { console.error("Failed to fetch strategic insights history", e); } finally { // setLoadingStrategicHistory(false); } }; loadStatus(); loadHistory(); }, []); const fetchBenchmarkData = async () => { setLoadingBenchmarkData(true); try { const res = await apiClient.get('/api/onboarding/step3/sitemap-benchmark-report'); setSitemapBenchmarkData(res.data); } catch (e) { console.error("Failed to fetch benchmark report", e); } finally { setLoadingBenchmarkData(false); } }; const deepStatus = scheduledStatus?.deep_competitor_analysis; const deepBulb = deepStatus?.bulb || 'unknown'; const deepReason = deepStatus?.reason; const deepTask = deepStatus?.task; const sitemapStatus = scheduledStatus?.competitive_sitemap_benchmarking; const sitemapBulb = sitemapStatus?.bulb || 'unknown'; const sitemapReason = sitemapStatus?.reason; const sitemapReport = sitemapStatus?.report; const getBulbColor = (bulb: string) => { if (bulb === 'green') return '#22c55e'; if (bulb === 'red') return '#ef4444'; return '#94a3b8'; }; const getFeatureStatusLabel = (featureId: string, fallback: string) => { if (featureId === 'sitemap-benchmarking') { if (sitemapReport?.available) return 'Report Ready (No AI)'; return 'Available (No AI)'; } return fallback; }; const runSitemapBenchmark = async () => { setSitemapBenchmarkError(null); setSitemapBenchmarkRunning(true); setIsLongRunning(false); try { await longRunningApiClient.post('/api/seo/competitive-sitemap-benchmarking/run', { max_competitors: 5 }); // Poll for completion with adaptive backoff let attempts = 0; const maxAttempts = 60; // Adjusted for ~10-12 mins (matching backend timeout) let currentInterval = 2000; const poll = async () => { try { attempts++; // Mark as long running after ~2 minutes (approx 30 attempts) if (attempts > 30) { setIsLongRunning(true); } const res = await apiClient.get('/api/onboarding/step3/scheduled-tasks-status'); setScheduledStatus(res.data); // Check status flag const reportAvailable = res.data?.competitive_sitemap_benchmarking?.report?.available; const reportStatus = res.data?.competitive_sitemap_benchmarking?.report?.status; const reportError = res.data?.competitive_sitemap_benchmarking?.report?.error; let reportFetched = false; // Check for failure if (reportStatus === 'failed' || reportError) { setSitemapBenchmarkRunning(false); setSitemapBenchmarkError(reportError || "Benchmark failed during execution."); return; // Stop polling } // If available, try to fetch data if (reportAvailable && !sitemapBenchmarkData) { try { const reportRes = await apiClient.get('/api/onboarding/step3/sitemap-benchmark-report'); if (reportRes?.data) { setSitemapBenchmarkData(reportRes.data); reportFetched = true; } } catch { // Report might be saving or transient error } } if (reportAvailable || reportFetched) { if (!reportFetched && !sitemapBenchmarkData) { await fetchBenchmarkData(); } setOpenModal(false); // Close modal on success setSitemapBenchmarkRunning(false); setIsLongRunning(false); // Focus on results setTimeout(() => { const element = document.getElementById('sitemap-benchmark-results'); if (element) { element.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, 500); return; // Stop polling } else if (attempts >= maxAttempts) { setSitemapBenchmarkRunning(false); setIsLongRunning(false); setSitemapBenchmarkError("Benchmark timed out (10 mins limit). It may still be running in the background."); return; } // Adaptive backoff: Slow down polling over time if (attempts > 5) currentInterval = 4000; // After ~10s, slow to 4s if (attempts > 15) currentInterval = 8000; // After ~50s, slow to 8s if (attempts > 25) currentInterval = 15000; // After ~2m, slow to 15s setTimeout(poll, currentInterval); } catch (e) { console.error("Polling error", e); // Continue polling on error, but maybe wait longer setTimeout(poll, currentInterval + 1000); } }; // Start polling setTimeout(poll, currentInterval); } catch (e: any) { setSitemapBenchmarkError(e?.response?.data?.detail || e?.message || 'Failed to run benchmark'); setSitemapBenchmarkRunning(false); } }; const runStrategicInsights = async () => { setStrategicInsightsError(null); setStrategicInsightsRunning(true); try { const res = await apiClient.post('/api/seo-dashboard/strategic-insights/run'); if (res.data?.success) { setStrategicInsightsData(res.data.report); setOpenModal(false); // Focus on results setTimeout(() => { const element = document.getElementById('strategic-insights-results'); if (element) { element.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, 500); } } catch (e: any) { setStrategicInsightsError(e?.response?.data?.detail || e?.message || 'Failed to run strategic insights'); } finally { setStrategicInsightsRunning(false); } }; const features = [ { id: 'deep-competitor-analysis', title: 'Deep Competitor Analysis', description: 'We dig deep into your competitors\' strategies so you don\'t have to.', icon: , status: 'Auto-scheduled', color: '#3b82f6', details: [ 'Uncover their top-performing content and keywords', 'Identify their unique selling propositions (USPs)', 'Spot gaps in their content strategy you can exploit', 'Analyze their publishing frequency and patterns', 'Get a clear roadmap to outperform them' ] }, { id: 'sitemap-benchmarking', title: 'Competitive Sitemap Benchmarking', description: 'See exactly how your website stacks up against the market leaders.', icon: , status: 'Available (No AI)', color: '#10b981', details: [ 'Visualize your content volume vs. competitors', 'Compare site structure and ease of navigation', 'Check if you are publishing enough content', 'Find missing categories your competitors have', 'Get instant, data-backed improvement ideas' ] }, { id: 'ai-competitive-insights', title: 'AI-Powered Competitive Insights', description: 'Turn raw data into a winning game plan with AI.', icon: , status: 'Planned', color: '#8b5cf6', details: [ 'Receive a personalized "Winning Moves" report', 'Understand the business impact of your strategy', 'Get specific content ideas to steal market share', 'Identify your true competitive advantages', 'Build a roadmap for long-term growth' ] } ]; const handleFeatureClick = (featureId: string) => { setSelectedFeature(featureId); setOpenModal(true); }; const selectedFeatureData = features.find(f => f.id === selectedFeature); return ( <> 🔍 Scheduled Tasks Long-running analyses that run automatically after onboarding {features.map((feature) => ( handleFeatureClick(feature.id)} > {feature.icon} {feature.title} {feature.id === 'deep-competitor-analysis' && ( )} {feature.id === 'sitemap-benchmarking' && ( )} : undefined} sx={{ backgroundColor: feature.status === 'Auto-scheduled' ? '#ecfdf5' : `${feature.color}20`, color: feature.status === 'Auto-scheduled' ? '#059669' : feature.color, fontWeight: 700, fontSize: '0.75rem', height: 24, border: feature.status === 'Auto-scheduled' ? '1px solid #a7f3d0' : 'none', '& .MuiChip-label': { px: 1.5 } }} /> {feature.description} ))} What's Next: These advanced competitor analysis features will be available in upcoming releases. Your current competitor research provides valuable insights to get started! {sitemapReport?.available && sitemapBenchmarkData && ( )} {strategicInsightsData && ( )} {/* Feature Details Modal */} { if (reason !== 'backdropClick' && reason !== 'escapeKeyDown') { setOpenModal(false); } else if (!sitemapBenchmarkRunning) { setOpenModal(false); } }} disableEscapeKeyDown={sitemapBenchmarkRunning} maxWidth="md" fullWidth PaperProps={{ sx: { backgroundColor: '#ffffff', borderRadius: 3, boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)' } }} > {selectedFeatureData && ( <> {selectedFeatureData.icon} {selectedFeatureData.title} )} {selectedFeatureData && ( <> {selectedFeatureData.description} Key Features: {selectedFeatureData.details.map((detail, index) => ( ))} {selectedFeatureData.id === 'deep-competitor-analysis' && ( How It Works: Once you finish onboarding, Alwrity automatically starts analyzing the competitors we found. We compare your website's performance against theirs to find hidden opportunities. You'll see the results in your SEO Dashboard, including a breakdown of what makes them successful and how you can do better. Status: {deepBulb === 'red' ? (deepReason || "Not eligible yet. No competitors found.") : "Eligible. This will run automatically after onboarding."} {deepTask?.exists && ( {deepTask.last_status ? `Last run: ${deepTask.last_status}${deepTask.last_run ? ` at ${deepTask.last_run}` : ''}` : (deepTask.next_execution ? `Next scheduled: ${deepTask.next_execution}` : `Task status: ${deepTask.status || 'unknown'}`)} )} )} {selectedFeatureData.id === 'sitemap-benchmarking' && ( Why This Matters: We scan competitor websites to understand how they organize their content and how often they publish. This shows you exactly where you need to improve to match or beat the market leaders. {sitemapBenchmarkRunning && ( {isLongRunning ? "This is taking longer than usual. Large websites can take a few minutes..." : "Analyzing competitor websites... please wait."} )} {loadingBenchmarkData ? ( ) : sitemapReport?.available ? ( Benchmark Report is ready! Close this window to view the detailed analysis below. ) : ( Status: {sitemapReport?.available ? 'Report is ready.' : sitemapReport?.status === 'failed' ? `Failed: ${sitemapReport?.error || 'Unknown error'}` : sitemapReport?.status === 'processing' ? 'Analysis in progress...' : 'No report yet. You can run it now (No AI).'} {sitemapReport?.last_run && ( Last run: {sitemapReport.last_run} )} )} {sitemapBenchmarkError && ( {sitemapBenchmarkError} )} )} {selectedFeatureData.id === 'ai-competitive-insights' && ( The "Winning Moves" Advantage: We turn millions of data points into a clear "Winning Moves" report. See exactly which content will drive the most traffic and revenue, and get a step-by-step plan to steal market share from your competitors. {strategicInsightsRunning && ( Our AI is analyzing market shifts and competitor moves... this takes about 30-45 seconds. )} {strategicInsightsError && ( {strategicInsightsError} )} )} )} {selectedFeatureData?.id === 'sitemap-benchmarking' && ( )} {selectedFeatureData?.id === 'ai-competitive-insights' && ( )} ); }; export default ComingSoonSection;