"use client";

/**
 * @file CollectiveAdaptiveDashboard.tsx
 * OS Adaptive Dashboard – Phase 006.9
 * Features:
 *  - Real-time Evolution History
 *  - Insight selection + Neural Summary Panel
 *  - Neural Voice HUD (Speech + Wave Animation)
 *  - Timeline, Confidence HUD, Meta Forecast
 *  - Global layered HUD system (via HUDLayerManager + React Portal)
 */

import React, { useEffect, useState } from "react";
import styles from "./OSDashboardWindow.module.css";
import { HUDGlitch } from "./components/HUDGlitch";
import {
  startAutoSnapshot,
  stopAutoSnapshot,
  getEvolutionLogs,
  EvolutionLog,
} from "@/lib/evolution/history.collector";

// === Modules ===
import { EvolutionHistoryChart } from "./components/charts/EvolutionHistoryChart";
import { AdaptiveTimeline } from "./components/AdaptiveTimeline";
import { MetaForecastCard } from "./components/MetaForecastCard";
import { ConfidenceHUD } from "./components/ConfidenceHUD";
import { EvolutionLogsTable } from "./components/EvolutionLogsTable";
import { ExportCenter } from "./components/ExportCenter";
import { InsightPanel } from "./components/charts/InsightPanel";
import type { Insight } from "./analysis/insight";
import { HUDLayerManager } from "./components/HUDLayerManager";

export const CollectiveAdaptiveDashboard: React.FC = () => {
  /** === Auto Logging === */
  useEffect(() => {
    startAutoSnapshot({ intervalSec: 120, confidenceDelta: 0.06 });
    return () => stopAutoSnapshot();
  }, []);

  /** === Evolution Logs Stream === */
  const [evoLogs, setEvoLogs] = useState<EvolutionLog[]>([]);
  useEffect(() => {
    setEvoLogs(getEvolutionLogs());
    const t = setInterval(() => setEvoLogs(getEvolutionLogs()), 30000);
    return () => clearInterval(t);
  }, []);

  /** === States === */
  const [insight, setInsight] = useState<Insight | null>(null);
  const [showAI, setShowAI] = useState(false);
  const [showVoiceHUD, setShowVoiceHUD] = useState(false);

  return (
    <div className={styles.windowContainer}>
      {/* === Global HUD Manager (Portaled) === */}
      <HUDLayerManager
        showAI={showAI}
        showVoice={showVoiceHUD}
        onCloseAI={() => setShowAI(false)}
        onCloseVoice={() => setShowVoiceHUD(false)}
        initialInsight={insight}
        debugDefaultOpen={false}
      />

      {/* === Header === */}
      <header className={styles.windowHeader}>
        <h1>
          <HUDGlitch accent="orange">OS Adaptive Dashboard</HUDGlitch>
        </h1>
        <span>
          <HUDGlitch accent="teal">
            Collective Awareness • Predictive Phase 006.9
          </HUDGlitch>
        </span>
      </header>

      {/* === Main Body === */}
      <main className={styles.windowBody}>
        {/* === Left Column === */}
        <section className={styles.section} style={{ gridColumn: "1 / 2" }}>
          <h2>System Timeline</h2>
          <AdaptiveTimeline />
        </section>

        <section className={styles.section} style={{ gridColumn: "1 / 2" }}>
          <h2>Evolution History</h2>
          <EvolutionHistoryChart
            data={evoLogs}
            onSelect={(i) => {
              setInsight(i);
              setShowAI(true);
            }}
          />
        </section>

        {/* === Right Column === */}
        <section className={styles.section} style={{ gridColumn: "2 / 3" }}>
          <h2>Insight</h2>
          <InsightPanel insight={insight} onClose={() => setInsight(null)} />
        </section>

        <section className={styles.section} style={{ gridColumn: "2 / 3" }}>
          <h2>Meta-Forecast</h2>
          <MetaForecastCard />
        </section>

        <section className={styles.section} style={{ gridColumn: "2 / 3" }}>
          <h2>System Confidence</h2>
          <ConfidenceHUD />
        </section>

        {/* === Full-width Sections === */}
        <section className={styles.section} style={{ gridColumn: "1 / span 2" }}>
          <h2>Evolution Logs</h2>
          <EvolutionLogsTable />
        </section>

        <section className={styles.section} style={{ gridColumn: "1 / span 2" }}>
          <h2>Export Center</h2>
          <ExportCenter />
          <div className="flex justify-center mt-4">
            <button
              onClick={() => setShowVoiceHUD(true)}
              className="px-4 py-2 rounded-md border border-[hsl(var(--border))/60]
                         bg-[hsl(var(--background))/60] hover:bg-[hsl(var(--muted))/30]
                         text-sm text-cyan-300 font-semibold shadow-[0_0_12px_rgba(0,255,255,0.25)]
                         transition-all duration-300 hover:scale-[1.03]"
            >
              🎙️ Activate Neural Voice HUD
            </button>
          </div>
        </section>
      </main>

      {/* === Footer === */}
      <footer className={styles.windowFooter}>
        © {new Date().getFullYear()} Jemy-dev OS — Phase 006.9 • Neural Voice HUD Layer
      </footer>
    </div>
  );
};
