import { useState } from 'react';
import { Header } from './components/Header';
import { useAnalytics } from './hooks/useAnalytics';
import { AIDiscoveryTrafficCard } from './components/cards/AIDiscoveryTrafficCard';
import { AIReferredVisitsCard } from './components/cards/AIReferredVisitsCard';
import { TopPagesCard } from './components/cards/TopPagesCard';
import { NonAIUsersCard } from './components/cards/NonAIUsersCard';
import { CrawlerLogsCard } from './components/cards/CrawlerLogsCard';
import { HumanLogsCard } from './components/cards/HumanLogsCard';
import { RecommendedActionsCard } from './components/cards/RecommendedActionsCard';
import { WinsCard } from './components/cards/WinsCard';
import { api, type Period } from './lib/api';

function extractDomain(url: string): string {
    try {
        return new URL(url).hostname.replace(/^www\./, '');
    } catch {
        return url;
    }
}

export default function App() {
    const [period, setPeriod] = useState<Period>('7d');
    const [enabling, setEnabling] = useState(false);
    const [enableError, setEnableError] = useState<string | null>(null);
    const { data, loading, error, refresh } = useAnalytics(period);
    const domain = window.ezyAiBoot?.siteUrl ? extractDomain(window.ezyAiBoot.siteUrl) : undefined;

    if (error) {
        return (
            <div className="rounded-lg border border-white/[0.1] bg-white/[0.03] backdrop-blur-[45px] p-8 text-center">
                <p className="text-rose-400 font-medium mb-2 tracking-[-0.28px]">Couldn't load analytics</p>
                <p className="text-white/55 text-sm mb-4">{error}</p>
                <button
                    onClick={refresh}
                    className="px-4 py-2 rounded-xl bg-white/10 border border-white/20 text-white text-sm hover:bg-white/15 transition-colors"
                >
                    Try again
                </button>
            </div>
        );
    }

    if (loading && !data) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-10 w-10 border-4 border-white/20 border-t-[#f16001]" />
            </div>
        );
    }

    if (!data) return null;

    const trackingOff = data.tracking_enabled === false;

    // Enable analytics without leaving the page. The /settings route is
    // manage_options-gated server-side, so this is the same authority the
    // Settings screen uses — it just saves the user a round trip.
    async function enableAnalytics() {
        setEnabling(true);
        setEnableError(null);
        try {
            await api.updateSettings({ enable_analytics: true });
            await refresh();
        } catch (e) {
            setEnableError(e instanceof Error ? e.message : 'Could not enable analytics.');
        } finally {
            setEnabling(false);
        }
    }

    return (
        <div className="font-body max-w-[1920px] mx-auto relative">
            <Header period={period} onPeriodChange={setPeriod} onRefresh={refresh} mode={data.mode} refreshing={loading} domain={domain} />

            {trackingOff && (
                <div className="mb-4 lg:mb-5 flex flex-wrap items-center justify-between gap-4 lg:gap-8 rounded-lg border border-[#ff5300]/40 bg-[#ff5300]/10 px-[18px] py-[18px] lg:px-7 lg:py-6">
                    <div className="min-w-0 flex-[1_1_320px]">
                        <span className="inline-block rounded-full bg-[#ff5300]/20 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.6px] text-[#ff8a4d]">
                            Analytics
                        </span>
                        <h2 className="mt-2 mb-1.5 text-[17px] lg:text-xl font-bold leading-[1.25] tracking-[-0.4px] text-white">
                            Turn on analytics to start tracking AI visits.
                        </h2>
                        <p className="max-w-[640px] text-[13px] lg:text-[15px] leading-[1.5] tracking-[-0.2px] text-white/60">
                            Visitor analytics is off, so nothing is being recorded yet. Enable it to see
                            which AI crawlers reach your site, which pages they read, and which visitors
                            arrive from ChatGPT, Claude and Perplexity.
                        </p>
                    </div>
                    <button
                        type="button"
                        onClick={enableAnalytics}
                        disabled={enabling}
                        className="inline-flex shrink-0 items-center gap-2 rounded-xl bg-[#ff5300] px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-[#e04a00] disabled:cursor-not-allowed disabled:opacity-70"
                    >
                        {enabling ? (
                            <>
                                <span className="size-4 animate-spin rounded-full border-2 border-white/40 border-t-white" />
                                <span>Enabling...</span>
                            </>
                        ) : (
                            <>
                                <span>Enable Analytics</span>
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                                    <line x1="5" y1="12" x2="19" y2="12" />
                                    <polyline points="12 5 19 12 12 19" />
                                </svg>
                            </>
                        )}
                    </button>
                    {enableError && (
                        <p className="w-full text-sm text-rose-300">
                            {enableError} You can also enable it from the Settings page.
                        </p>
                    )}
                </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-5 mb-4 lg:mb-5">
                <AIDiscoveryTrafficCard
                    totalVisits={data.aiDiscovery.totalMeasured}
                    totalWithEstimate={data.aiDiscovery.totalWithEstimate}
                    trend={data.aiDiscovery.trend}
                    previousTotal={data.aiDiscovery.previousTotal}
                    trendLabel={data.aiDiscovery.trendLabel}
                    chartData={data.aiDiscovery.chartData}
                    engineBreakdown={data.aiDiscovery.engineBreakdown}
                    statusText={data.aiDiscovery.statusText}
                    windowLabel={data.aiDiscovery.windowLabel}
                    estimatedHumanReach={data.aiDiscovery.estimatedHumanReach}
                    claudeCrawler={data.aiDiscovery.claudeCrawler}
                    claudeUserLike={data.aiDiscovery.claudeUserLike}
                    gptCrawler={data.aiDiscovery.gptCrawler}
                    gptUserLike={data.aiDiscovery.gptUserLike}
                    extrapolationMethodology={data.aiDiscovery.extrapolationMethodology}
                    extrapolationMultiplier={data.aiDiscovery.extrapolationMultiplier}
                    extrapolationHumanReachRatio={data.aiDiscovery.extrapolationHumanReachRatio}
                    delay={0.1}
                />
                <AIReferredVisitsCard groups={data.aiReferredGroups} delay={0.2} />
                <TopPagesCard pages={data.topPages.pages} statusText={data.topPages.statusText} delay={0.3} />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-5 mb-4 lg:mb-5">
                <NonAIUsersCard pages={data.nonAiUsers.pages} statusText={data.nonAiUsers.statusText} delay={0.4} />
                <CrawlerLogsCard
                    logs={data.crawlerLogs.logs}
                    isActive={data.crawlerLogs.isActive}
                    totalCrawlerCount={data.crawlerLogs.totalCrawlerCount}
                    delay={0.5}
                />
                <HumanLogsCard logs={data.humanLogs} delay={0.6} />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 lg:gap-5">
                <div className="lg:col-span-7">
                    <RecommendedActionsCard delay={0.7} />
                </div>
                <div className="lg:col-span-5 lg:self-start">
                    <WinsCard
                        totalVisits={data.aiDiscovery.totalMeasured}
                        trend={data.aiDiscovery.trend}
                        estimatedHumanReach={data.aiDiscovery.estimatedHumanReach}
                        delay={0.8}
                    />
                </div>
            </div>
        </div>
    );
}
