import { useState } from 'react';
import { motion } from 'framer-motion';

interface FAQItem {
  question: string;
  answer: string;
}

const FAQ_ITEMS: FAQItem[] = [
  {
    question: 'What is PULSE?',
    answer:
      'PULSE is a Neural Operating System for AI swarms. It provides constitutional governance, collective memory, and autonomous task coordination across multiple AI agents (Claude, Gemini, Codex, Grok) — all unified under immutable laws enforced by cryptographic signing.',
  },
  {
    question: 'Which AI providers does PULSE support?',
    answer:
      'PULSE supports Anthropic (Claude), Google (Gemini), OpenAI (Codex/GPT), xAI (Grok), and Ollama for local models. Agents can run via API keys, CLI subscriptions, or local Ollama instances. The system is agent-agnostic by design — every solution must work for any agent, any provider, any mode.',
  },
  {
    question: 'How does the Brain pipeline work?',
    answer:
      'Every agent interaction is captured into signed logs. The Bridge daemon processes these through 62+ regex patterns and semantic extraction, scoring each by salience. Extracted knowledge flows into Hippocampus regions (Lessons, Failures, Patterns, Evidence, Knowledge). A consolidation daemon deduplicates, mines patterns, and promotes schemas every 6 hours. At boot, agents receive a compressed briefing so no insight is ever lost.',
  },
  {
    question: 'What are the Constitutional Laws?',
    answer:
      'PULSE has 4 immutable Tier 0 laws (Ahimsa, Sovereignty, Veracity, Consensus) and 10 Tier 1 Sacred Laws including Immutable Constitution, Brain First, No Repeat Mistakes, Maximum Separation of Concerns, and Cryptographic Integrity. All are enforced by code — HMAC-SHA256 signing, compliance validators, and pre-commit hooks — not ceremony.',
  },
  {
    question: 'What is the ASOP protocol?',
    answer:
      'The Agent Self-Organization Protocol enables multiple agents to coordinate around a shared task board. One agent decomposes user prompts into tasks, others claim and execute in parallel. It uses optimistic claiming (no locks), file declaration to prevent edit collisions, heartbeat monitoring, and dependency ordering.',
  },
  {
    question: 'Can I run PULSE locally without API keys?',
    answer:
      'Yes. PULSE supports Ollama for fully local, offline operation. Install Ollama, pull a model (e.g., llama3, mistral), and PULSE auto-detects it. The brain pipeline, task board, and governance work entirely locally. API keys are only needed for cloud-hosted models.',
  },
  {
    question: 'How does the Swarm work?',
    answer:
      'Run `pulse swarm` to start background workers. Workers are headless daemons that poll the task board every 5 seconds, atomically claim tasks matching their tier, and execute them with up to 15 tool iterations. Tasks are auto-tiered: cheap models handle docs and formatting, standard models handle features, premium models handle architecture and security.',
  },
{
    question: 'How does PULSE process my conversations?',
    answer:
      'PULSE uses LLMs (via API keys, CLI subscriptions like Claude Code/Gemini CLI, or local Ollama models) to synthesize and extract knowledge. The regex pipeline runs locally with zero cost — 62+ patterns match lessons, failures, causal relationships, and decisions directly from conversation text. LLM-powered synthesis (consolidation, prediction, workspace integration) requires an LLM provider. Ollama is fully supported for free, offline synthesis — no cloud calls needed.',
  },
  {
    question: 'What data does PULSE store?',
    answer:
      'PULSE stores extracted knowledge (lessons, failures, patterns, decisions) in local JSONL/JSON files in your project\'s Hippocampus directory or ~/.pulse/brain/. Raw conversation logs stay in state/. Nothing is sent to external servers — all processing happens locally or through your own LLM provider.',
  },
  {
    question: 'Can I use PULSE without paying for API keys?',
    answer:
      'Yes! Install Ollama (free, open source) and PULSE auto-detects it. The brain pipeline, task board, governance, and all 47 CLI commands work locally. Regex-based extraction (62+ patterns) runs with zero cost. LLM synthesis uses your local Ollama models instead of cloud APIs.',
  },
  {
    question: 'How do I migrate from one AI tool to another?',
    answer:
      'You don\'t need to migrate — that\'s the point. PULSE is the shared memory layer across all your tools. Switch from Claude to Gemini mid-project and Gemini inherits everything Claude learned. Add Cursor or Copilot later and they plug into the same brain. Knowledge is tool-agnostic.',
  },
];

function FAQAccordion({ items }: { items: FAQItem[] }) {
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  return (
    <div className="space-y-3">
      {items.map((item, index) => (
        <div
          key={index}
          className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl overflow-hidden"
        >
          <button
            onClick={() => setOpenIndex(openIndex === index ? null : index)}
            className="w-full text-left px-6 py-4 flex items-center justify-between gap-4 hover:bg-slate-700/30 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-inset"
            aria-expanded={openIndex === index}
          >
            <span className="font-medium text-slate-200">{item.question}</span>
            <svg
              className={`w-5 h-5 text-sky-400 flex-shrink-0 transition-transform duration-300 ${
                openIndex === index ? 'rotate-180' : ''
              }`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          <motion.div
            initial={false}
            animate={{
              height: openIndex === index ? 'auto' : 0,
              opacity: openIndex === index ? 1 : 0,
            }}
            transition={{ duration: 0.3, ease: 'easeInOut' }}
            className="overflow-hidden"
          >
            <p className="px-6 pb-5 text-slate-400 text-sm leading-relaxed">{item.answer}</p>
          </motion.div>
        </div>
      ))}
    </div>
  );
}

export default function FAQ() {
  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      {/* Header */}
      <div className="border-b border-slate-800/50 bg-slate-900/50 backdrop-blur-sm sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <h1 className="text-3xl sm:text-4xl font-bold text-sky-400">Frequently Asked Questions</h1>
          <p className="text-slate-400 mt-2">Common questions about PULSE</p>
        </div>
      </div>

      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <FAQAccordion items={FAQ_ITEMS} />
        </motion.div>

        {/* Back to Docs link */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
          className="mt-12 text-center"
        >
          <p className="text-slate-400 mb-4">Still have questions?</p>
          <div className="flex justify-center gap-4">
            <a
              href="/docs"
              className="inline-block px-6 py-3 rounded-xl border border-sky-400/50 text-sky-400 font-semibold hover:bg-sky-400/10 hover:border-sky-400 transition-all duration-200"
            >
              Read the Docs
            </a>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
