import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { BarChart3, Users, Lightbulb, Wrench, AlertTriangle, DollarSign, Clock, Table2, Brain, CalendarDays, Workflow, Repeat, GitCompare, TrendingUp, Sparkles } from 'lucide-react';
import { useData } from './hooks/useData';
import { useTimezone } from './hooks/useTimezone';
import Hero from './components/Hero';
import Insights from './components/Insights';
import ToolBreakdown from './components/ToolBreakdown';
import DeveloperProfiles from './components/DeveloperProfiles';
import SessionDistribution from './components/SessionDistribution';
import WastedReads from './components/WastedReads';
import StruggleSignals from './components/StruggleSignals';
import SessionTimeline from './components/SessionTimeline';
import SessionTable from './components/SessionTable';
import CostBreakdown from './components/CostBreakdown';
import ToolFrequency from './components/ToolFrequency';
import IntentDistribution from './components/IntentDistribution';
import DailyHeatmap from './components/DailyHeatmap';
import WorkflowPatterns from './components/WorkflowPatterns';
import SessionArcs from './components/SessionArcs';
import HourlyProductivity from './components/HourlyProductivity';
import CostConcentration from './components/CostConcentration';
import Recommendations from './components/Recommendations';
import RepoCosts from './components/RepoCosts';
import SessionDeepDives from './components/SessionDeepDives';
import CLIComparison from './components/CLIComparison';
import LearningCurves from './components/LearningCurves';
import TokenGrowth from './components/TokenGrowth';
import ActiveTimeBreakdown from './components/ActiveTimeBreakdown';
import QualitativeInsights from './components/QualitativeInsights';
import Methodology from './components/Methodology';
import ZeroEditByHour from './components/ZeroEditByHour';
import DeveloperEfficiency from './components/DeveloperEfficiency';
import MonthlyTrends from './components/MonthlyTrends';

const NAV_ITEMS = [
  { id: 'overview', label: 'Overview', icon: BarChart3 },
  { id: 'insights', label: 'Insights', icon: Lightbulb },
  { id: 'tools', label: 'Tools', icon: Wrench },
  { id: 'patterns', label: 'Patterns', icon: Repeat },
  { id: 'workflows', label: 'Workflows', icon: Workflow },
  { id: 'intent', label: 'Intent', icon: Brain },
  { id: 'cost', label: 'Cost', icon: DollarSign },
  { id: 'cli', label: 'CLI', icon: GitCompare },
  { id: 'trends', label: 'Trends', icon: TrendingUp },
  { id: 'activity', label: 'Activity', icon: CalendarDays },
  { id: 'timeline', label: 'Timeline', icon: Clock },
  { id: 'developers', label: 'Developers', icon: Users },
  { id: 'qualitative', label: 'Qualitative', icon: Sparkles },
  { id: 'waste', label: 'Waste', icon: AlertTriangle },
  { id: 'sessions', label: 'Sessions', icon: Table2 },
];

interface Overview {
  total_sessions: number;
  unique_users: number;
  date_range: { start: string; end: string };
}

function App() {
  const [activeSection, setActiveSection] = useState('overview');
  const [scrollProgress, setScrollProgress] = useState(0);
  const { tz, toggle: toggleTz } = useTimezone();
  const { data: overview } = useData<Overview>('/data/overview.json', {
    total_sessions: 0, unique_users: 0, date_range: { start: '', end: '' },
  });

  useEffect(() => {
    const handleScroll = () => {
      const sections = NAV_ITEMS.map(n => ({
        id: n.id,
        el: document.getElementById(n.id),
      })).filter(s => s.el);

      const scrollY = window.scrollY + 120;
      for (let i = sections.length - 1; i >= 0; i--) {
        if (sections[i].el!.offsetTop <= scrollY) {
          setActiveSection(sections[i].id);
          break;
        }
      }

      const docHeight = document.documentElement.scrollHeight - window.innerHeight;
      setScrollProgress(docHeight > 0 ? (window.scrollY / docHeight) * 100 : 0);
    };
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const scrollTo = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const genDate = overview.date_range.end
    ? new Date(overview.date_range.end).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
    : 'Feb 14, 2026';

  return (
    <div className="min-h-screen bg-surface-0 text-text-1">
      {/* Fixed top nav */}
      <nav className="fixed top-0 left-0 right-0 z-50 bg-surface-0/80 backdrop-blur-xl border-b border-border-dim">
        <div className="max-w-7xl mx-auto px-8 flex items-center h-14 gap-0.5 overflow-x-auto scrollbar-none">
          <span className="text-sm font-bold text-accent mr-4 tracking-tight shrink-0">qc-trace</span>
          {NAV_ITEMS.map(item => {
            const Icon = item.icon;
            const active = activeSection === item.id;
            return (
              <button
                key={item.id}
                onClick={() => scrollTo(item.id)}
                className={`relative px-2.5 py-1.5 rounded-lg text-[11px] font-medium flex items-center gap-1 transition-colors shrink-0 ${
                  active ? 'text-text-1' : 'text-text-3 hover:text-text-2'
                }`}
              >
                <Icon size={12} />
                {item.label}
                {active && (
                  <motion.div
                    layoutId="nav-pill"
                    className="absolute inset-0 bg-surface-2 rounded-lg -z-10"
                    transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                  />
                )}
              </button>
            );
          })}
          <div className="ml-auto shrink-0">
            <button
              onClick={toggleTz}
              className="px-2.5 py-1 rounded-lg text-[10px] font-mono font-semibold bg-surface-2 border border-border-dim text-text-2 hover:text-text-1 transition-colors"
              title="Toggle timezone"
            >
              {tz}
            </button>
          </div>
        </div>
        {/* Scroll progress bar */}
        <div className="h-[2px] bg-transparent">
          <div
            className="h-full bg-accent/50 transition-[width] duration-100"
            style={{ width: `${scrollProgress}%` }}
          />
        </div>
      </nav>

      {/* Content */}
      <div className="pt-16">
        <div id="overview">
          <Hero />
        </div>

        <div id="insights">
          <Insights />
          <Recommendations />
        </div>

        <div id="tools">
          <ToolBreakdown />
          <ToolFrequency />
          <SessionDistribution />
        </div>

        <div id="patterns">
          <SessionArcs />
        </div>

        <div id="workflows">
          <WorkflowPatterns />
        </div>

        <div id="intent">
          <IntentDistribution />
        </div>

        <div id="cost">
          <CostConcentration />
          <DeveloperEfficiency />
          <RepoCosts />
          <SessionDeepDives />
          <CostBreakdown />
        </div>

        <div id="cli">
          <CLIComparison />
        </div>

        <div id="trends">
          <MonthlyTrends />
          <LearningCurves />
          <TokenGrowth />
          <ActiveTimeBreakdown />
        </div>

        <div id="activity">
          <HourlyProductivity />
          <ZeroEditByHour />
          <DailyHeatmap />
        </div>

        <div id="timeline">
          <SessionTimeline />
        </div>

        <div id="developers">
          <DeveloperProfiles />
        </div>

        <div id="qualitative">
          <QualitativeInsights />
        </div>

        <div id="waste">
          <WastedReads />
          <StruggleSignals />
        </div>

        <div id="sessions">
          <SessionTable />
        </div>

        <Methodology />

        {/* Footer */}
        <footer className="px-8 max-w-7xl mx-auto py-16 border-t border-border-dim">
          <div className="flex items-center justify-between text-xs text-text-3">
            <span>AI Developer Analytics — qc-trace</span>
            <span>
              Generated {genDate} from {overview.total_sessions.toLocaleString()} sessions across {overview.unique_users} developers
            </span>
          </div>
        </footer>
      </div>
    </div>
  );
}

export default App;
