/**
* SEO Analysis Controller Component
* Main component that orchestrates enterprise audit and GSC analysis
* with LLM insights generation and traffic improvement strategies
*/
import React, { useState, useEffect } from 'react';
import {
Box,
Container,
Typography,
Button,
TextField,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
CircularProgress,
Alert,
Stepper,
Step,
StepLabel,
Card,
CardContent,
Grid,
Tab,
Tabs,
Paper,
Chip,
Stack,
LinearProgress,
} from '@mui/material';
import {
PlayArrow as PlayArrowIcon,
Refresh as RefreshIcon,
Settings as SettingsIcon,
Assessment as AssessmentIcon,
AutoAwesome as AutoAwesomeIcon,
TrendingUp as TrendingUpIcon,
Download as DownloadIcon,
} from '@mui/icons-material';
import { motion, AnimatePresence } from 'framer-motion';
import { enterpriseSeoAPI, EnterpriseAuditResult, GSCAnalysisResult } from '../../api/enterpriseSeoApi';
import { llmInsightsGenerator } from '../../api/llmInsightsGenerator';
import { EnterpriseAuditResults } from './components/EnterpriseAuditResults';
import { GSCAnalysisResults } from './components/GSCAnalysisResults';
import { ActionableInsightsDisplay } from './components/ActionableInsightsDisplay';
import { AIVisibilitySection } from './components/AIVisibilitySection';
interface AnalysisStep {
label: string;
description: string;
}
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index } = props;
return (
{value === index && {children}}
);
}
const analysisSteps: AnalysisStep[] = [
{ label: 'Website Input', description: 'Enter your website URL' },
{ label: 'Enterprise Audit', description: 'Comprehensive SEO audit' },
{ label: 'GSC Analysis', description: 'Search performance analysis' },
{ label: 'Insights', description: 'AI-powered recommendations' },
{ label: 'Review', description: 'Review results and strategy' },
];
export const SEOAnalysisController: React.FC = () => {
// UI State
const [activeStep, setActiveStep] = useState(0);
const [tabValue, setTabValue] = useState(0);
const [websiteUrl, setWebsiteUrl] = useState('');
const [competitors, setCompetitors] = useState([]);
const [targetKeywords, setTargetKeywords] = useState([]);
// Analysis State
const [auditResult, setAuditResult] = useState(null);
const [gscResult, setGscResult] = useState(null);
const [insights, setInsights] = useState([]);
// Loading & Error State
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [progress, setProgress] = useState(0);
// Dialog State
const [openOptionsDialog, setOpenOptionsDialog] = useState(false);
const [options, setOptions] = useState({
includeContentAnalysis: true,
includeCompetitiveAnalysis: true,
generateExecutiveReport: true,
dateRangeDays: 90,
});
// Validation
const isUrlValid = websiteUrl && websiteUrl.startsWith('http');
const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
setTabValue(newValue);
};
/**
* Execute enterprise audit
*/
const handleStartAudit = async () => {
if (!isUrlValid) {
setError('Please enter a valid website URL starting with http:// or https://');
return;
}
setLoading(true);
setError(null);
setProgress(20);
setActiveStep(1);
try {
// Execute enterprise audit
console.log('Starting enterprise audit for', websiteUrl);
const auditResponse = await enterpriseSeoAPI.executeEnterpriseAudit(websiteUrl, {
competitors: competitors.filter(c => c.trim()),
targetKeywords: targetKeywords.filter(k => k.trim()),
includeContentAnalysis: options.includeContentAnalysis,
includeCompetitiveAnalysis: options.includeCompetitiveAnalysis,
generateExecutiveReport: options.generateExecutiveReport,
});
if (!auditResponse.success) {
throw new Error(auditResponse.message || 'Audit failed');
}
setAuditResult(auditResponse.data);
setProgress(50);
setActiveStep(2);
// Execute GSC analysis
console.log('Starting GSC analysis for', websiteUrl);
const gscResponse = await enterpriseSeoAPI.analyzeGSCSearchPerformance(websiteUrl, {
dateRangeDays: options.dateRangeDays,
includeOpportunities: true,
includeCompetitive: true,
});
if (!gscResponse.success) {
throw new Error(gscResponse.message || 'GSC analysis failed');
}
setGscResult(gscResponse.data);
setProgress(75);
setActiveStep(3);
// Skip insights generation for now - user can generate manually
setProgress(100);
setActiveStep(4);
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'An error occurred';
console.error('Analysis error:', err);
setError(errorMsg);
setActiveStep(activeStep);
} finally {
setLoading(false);
}
};
/**
* Generate AI-powered insights
*/
const handleGenerateInsights = async () => {
if (!auditResult && !gscResult) {
setError('No analysis results available');
return;
}
setLoading(true);
setError(null);
try {
let insightResults = [];
if (auditResult) {
const auditInsights = await llmInsightsGenerator.generateEnterpriseAuditInsights(
auditResult,
{ currentMonthlyTraffic: 1000 } // TODO: Get from user
);
insightResults.push(...auditInsights.insights);
}
if (gscResult) {
const gscInsights = await llmInsightsGenerator.generateGSCAnalysisInsights(
gscResult,
{ currentMonthlyTraffic: 1000 } // TODO: Get from user
);
insightResults.push(...gscInsights.insights);
}
setInsights(insightResults);
setActiveStep(4);
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to generate insights';
console.error('Insights generation error:', err);
setError(errorMsg);
} finally {
setLoading(false);
}
};
/**
* Download report
*/
const handleDownloadReport = () => {
const reportData = {
website: websiteUrl,
timestamp: new Date().toISOString(),
audit: auditResult,
gscAnalysis: gscResult,
insights: insights,
};
const dataStr = JSON.stringify(reportData, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = `seo-analysis-${new Date().getTime()}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
/**
* Reset analysis
*/
const handleReset = () => {
setWebsiteUrl('');
setCompetitors([]);
setTargetKeywords([]);
setAuditResult(null);
setGscResult(null);
setInsights([]);
setError(null);
setProgress(0);
setActiveStep(0);
setTabValue(0);
};
return (
{/* Header */}
Enterprise SEO Analysis
Comprehensive audit with AI-powered insights to improve organic traffic and rankings
{/* Progress Indicator */}
{loading && (
{activeStep === 1 && 'Running enterprise audit...'}
{activeStep === 2 && 'Analyzing search performance...'}
{activeStep === 3 && 'Generating insights...'}
)}
{/* Error Display */}
{error && (
setError(null)}
sx={{ mb: 3 }}
action={
}
>
{error}
)}
{/* Stepper */}
{analysisSteps.map((step, index) => (
{step.label}
))}
{/* Main Content */}
{/* Left Panel: Input & Controls */}
Analysis Configuration
{/* URL Input */}
setWebsiteUrl(e.target.value)}
size="small"
sx={{ mb: 2 }}
disabled={loading}
helperText="Include http:// or https://"
/>
{/* Competitors Input */}
setCompetitors(e.target.value.split(',').map(c => c.trim()))}
size="small"
sx={{ mb: 2 }}
disabled={loading}
/>
{/* Keywords Input */}
setTargetKeywords(e.target.value.split(',').map(k => k.trim()))}
size="small"
sx={{ mb: 3 }}
disabled={loading}
/>
{/* Control Buttons */}
}
onClick={handleStartAudit}
disabled={!isUrlValid || loading}
>
{loading ? 'Running...' : 'Start Analysis'}
}
onClick={() => setOpenOptionsDialog(true)}
disabled={loading}
>
Analysis Options
{(auditResult || gscResult) && (
<>
}
onClick={handleGenerateInsights}
disabled={loading}
>
Generate Insights
}
onClick={handleDownloadReport}
disabled={loading}
>
Download Report
}
onClick={handleReset}
disabled={loading}
>
New Analysis
>
)}
{/* Quick Stats */}
{(auditResult || gscResult) && (
Quick Stats
{auditResult && (
}
label={`Audit Score: ${auditResult.executive_summary.overall_score}`}
variant="outlined"
size="small"
/>
)}
{gscResult && (
}
label={`Clicks: ${gscResult.performance_overview.clicks.toLocaleString()}`}
variant="outlined"
size="small"
/>
)}
{insights.length > 0 && (
}
label={`${insights.length} Insights Generated`}
variant="outlined"
size="small"
color="success"
/>
)}
)}
{/* Right Panel: Results */}
{!auditResult && !gscResult ? (
No analysis yet
Enter a website URL and click "Start Analysis" to begin
) : (
{/* Tabs */}
{auditResult && }
{gscResult && }
{insights.length > 0 && }
{/* Tab Content */}
{auditResult && (
)}
{auditResult && gscResult && (
{gscResult && (
)}
)}
{!auditResult && gscResult && (
{gscResult && (
)}
)}
{/* AI Overview Insights — always last tab */}
{(() => {
const aioIndex = (auditResult ? 1 : 0) + (gscResult ? 1 : 0) + (insights.length > 0 ? 1 : 0);
return (
setActiveStep(0)}
/>
);
})()}
)}
{/* Options Dialog */}
);
};
export default SEOAnalysisController;