"use client";

import React, { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import {
  getEvolutionLogs,
  startAutoSnapshot,
  stopAutoSnapshot,
  EvolutionLog,
} from "@/lib/evolution/history.collector";
import type { Insight } from "../analysis/insight";
import { generateAISummary } from "@/lib/awareness/collective/analysis/ai-summary";
import { HUDContainer } from "./hud/glass-effects";
import { DepthReactiveGlass } from "@/lib/awareness/collective/components/hud/hud.depth-sync";

/**
 * AISummaryPanel — Phase 007.2 (Depth Sync + Ambient Glow)
 */
export const AISummaryPanel: React.FC<{
  onClose: () => void;
  initialInsight?: Insight | null;
}> = ({ onClose, initialInsight }) => {
  const [logs, setLogs] = useState<EvolutionLog[]>(() =>
    getEvolutionLogs().slice(-15)
  );
  const [display, setDisplay] = useState("");
  const [phase, setPhase] = useState<"typing" | "done">("typing");

  useEffect(() => {
    startAutoSnapshot({ intervalSec: 60, confidenceDelta: 0.05 });
    const t = setInterval(() => setLogs(getEvolutionLogs().slice(-15)), 20000);
    return () => {
      stopAutoSnapshot();
      clearInterval(t);
    };
  }, []);

  const summary = useMemo(() => {
    const intro = initialInsight
      ? `🧩 Insight: ${initialInsight.point.originalTrend}\nConfidence: ${(initialInsight.point.confidence * 100).toFixed(
          1
        )}%\n───────────────────────────────\n`
      : "";
    return intro + generateAISummary();
  }, [initialInsight, logs]);

  useEffect(() => {
    setDisplay("");
    setPhase("typing");
    let i = 0;
    const timer = setInterval(() => {
      setDisplay(summary.slice(0, i++));
      if (i >= summary.length) {
        clearInterval(timer);
        setPhase("done");
      }
    }, 14);
    return () => clearInterval(timer);
  }, [summary]);

  const confidences = logs.map((l) => l.confidence);
  const avg = confidences.length
    ? confidences.reduce((s, c) => s + c, 0) / confidences.length
    : 0;
  const status =
    avg >= 0.7 ? "Stable" : avg >= 0.4 ? "Fluctuating" : "Critical";
  const statusColor =
    status === "Stable"
      ? "#22c55e"
      : status === "Fluctuating"
      ? "#facc15"
      : "#ef4444";

  const max = Math.max(...confidences, 1);
  const min = Math.min(...confidences, 0);
  const points = confidences
    .map((c, i) => {
      const x = (i / Math.max(1, confidences.length - 1)) * 100;
      const y = 100 - ((c - min) / Math.max(0.001, max - min)) * 100;
      return `${x},${y}`;
    })
    .join(" ");

  return (
    <DepthReactiveGlass strength={12}>
      <HUDContainer status={status}>
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center gap-3">
            <motion.div
              className="w-3 h-3 rounded-full"
              style={{ background: statusColor }}
              animate={{
                boxShadow: [
                  `0 0 0px ${statusColor}`,
                  `0 0 12px ${statusColor}`,
                  `0 0 0px ${statusColor}`,
                ],
              }}
              transition={{ duration: 2, repeat: Infinity }}
            />
            <span className="text-xs font-semibold" style={{ color: statusColor }}>
              {status}
            </span>
            <h2 className="text-[22px] font-bold text-cyan-300 tracking-wide drop-shadow-sm">
              Neural Summary Generator
            </h2>
          </div>
          <motion.button
            onClick={onClose}
            whileHover={{ scale: 1.08 }}
            whileTap={{ scale: 0.9 }}
            className="px-4 py-1.5 text-sm border border-cyan-400/40 text-cyan-200 rounded-md hover:bg-cyan-500/10 transition font-semibold"
          >
            Close
          </motion.button>
        </div>

        {/* Summary Text */}
        <div className="relative font-mono text-[14px] border border-cyan-400/20 rounded-lg p-5 bg-[#031524]/70 leading-relaxed shadow-inner min-h-[220px] overflow-y-auto max-h-[380px]">
          <pre className="whitespace-pre-wrap text-cyan-100">{display}</pre>
          {phase === "typing" && (
            <motion.span
              animate={{ opacity: [0, 1, 0] }}
              transition={{ duration: 0.7, repeat: Infinity }}
              className="inline-block w-[8px] h-[18px] bg-cyan-400 ml-1 rounded-sm"
            />
          )}
        </div>

        {/* Graph */}
        <div className="mt-8">
          <svg viewBox="0 0 100 40" className="w-full h-10">
            <polyline fill="none" stroke="url(#grad)" strokeWidth="2" points={points} />
            <defs>
              <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#f47b46" />
                <stop offset="60%" stopColor="#0ea5e9" />
                <stop offset="100%" stopColor="#06b6d4" />
              </linearGradient>
            </defs>
          </svg>
          <div className="flex justify-between mt-1">
            <span className="text-[11px] text-cyan-300/70">Stability Index</span>
            <span className="text-[11px] text-cyan-200">{(avg * 100).toFixed(1)}%</span>
          </div>
          <motion.div className="h-2 rounded-full bg-gradient-to-r from-cyan-900/40 to-blue-800/40 mt-1 overflow-hidden">
            <motion.div
              className="h-full bg-gradient-to-r from-cyan-400 to-emerald-400"
              style={{ width: `${avg * 100}%` }}
              initial={{ width: 0 }}
              animate={{ width: `${avg * 100}%` }}
              transition={{ duration: 1, ease: "easeOut" }}
            />
          </motion.div>
        </div>
      </HUDContainer>
    </DepthReactiveGlass>
  );
};
