import { useRef } from 'react';
import { motion, useInView } from 'framer-motion';
import { Link } from 'react-router-dom';

function SectionHeading({ children }: { children: React.ReactNode }) {
  return (
    <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4">{children}</h2>
  );
}

function CodeSnippet({ code }: { code: string }) {
  return (
    <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 overflow-x-auto text-sm font-mono text-green-400">
      {code}
    </pre>
  );
}

function FeatureCard({ title, description, icon, delay = 0 }: {
  title: string;
  description: string;
  icon: string;
  delay?: number;
}) {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: '-80px' });

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 40 }}
      animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
      transition={{ duration: 0.6, delay, ease: 'easeOut' }}
      className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8 hover:border-sky-400/30 transition-colors duration-300"
    >
      <div className="text-3xl mb-4">{icon}</div>
      <h3 className="text-lg font-bold text-sky-400 mb-2">{title}</h3>
      <p className="text-slate-300 leading-relaxed text-sm">{description}</p>
    </motion.div>
  );
}

function StepNumber({ n }: { n: number }) {
  return (
    <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
      {n}
    </div>
  );
}

function FlowStep({ step, label, description, delay = 0 }: {
  step: number;
  label: string;
  description: string;
  delay?: number;
}) {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: '-60px' });

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, x: -20 }}
      animate={inView ? { opacity: 1, x: 0 } : { opacity: 0, x: -20 }}
      transition={{ duration: 0.5, delay, ease: 'easeOut' }}
      className="flex items-start gap-4"
    >
      <div className="flex flex-col items-center">
        <div className="w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold text-sm">
          {step}
        </div>
        {step < 4 && <div className="w-px h-12 bg-sky-400/20 mt-2" />}
      </div>
      <div className="pb-8">
        <h4 className="text-slate-100 font-semibold mb-1">{label}</h4>
        <p className="text-slate-400 text-sm">{description}</p>
      </div>
    </motion.div>
  );
}

export default function OpenClaw() {
  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      {/* Hero */}
      <section className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-b from-sky-500/5 via-transparent to-transparent pointer-events-none" />
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 pt-24 pb-16 text-center relative z-10">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.7 }}
          >
            <p className="text-sky-400/70 text-sm font-medium tracking-widest uppercase mb-4">Plugin Integration</p>
            <h1 className="text-5xl sm:text-6xl font-black text-sky-400 tracking-tight mb-6">
              PULSE for OpenClaw
            </h1>
            <p className="text-lg sm:text-xl text-slate-300 max-w-2xl mx-auto leading-relaxed">
              Give your OpenClaw agent persistent memory. Every session learns. No session forgotten.
            </p>
          </motion.div>
        </div>
      </section>

      {/* How It Works */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.5 }}
          className="mb-10"
        >
          <SectionHeading>How It Works</SectionHeading>
          <p className="text-slate-400 max-w-2xl">
            The plugin hooks into OpenClaw's lifecycle. Your agent gets memory for free.
          </p>
        </motion.div>

        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8 sm:p-10">
          <FlowStep
            step={1}
            label="Session starts"
            description="Plugin checks the PULSE brain and loads relevant context — lessons, failures, patterns, and predictions from past sessions."
            delay={0}
          />
          <FlowStep
            step={2}
            label="Before each turn"
            description="Brain context is injected into the agent's system prompt. Anti-patterns and domain knowledge surface automatically."
            delay={0.1}
          />
          <FlowStep
            step={3}
            label="Agent responds"
            description="Your agent has access to memory_search, memory_store, and memory_get tools to query and write to the brain mid-conversation."
            delay={0.2}
          />
          <FlowStep
            step={4}
            label="After each turn"
            description="Conversation is captured and knowledge is extracted — lessons, failures, and causal patterns are stored permanently."
            delay={0.3}
          />
        </div>
      </section>

      {/* Install */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.5 }}
          className="mb-10"
        >
          <SectionHeading>Setup Guide</SectionHeading>
          <p className="text-slate-400 max-w-2xl">Everything you need to get PULSE memory running inside OpenClaw.</p>
          <div className="mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-sky-500/10 border border-sky-400/30 text-sky-300 text-sm">
            <span>Requires a PULSE license.</span>
            <Link to="/pricing" className="underline underline-offset-2 hover:text-sky-200 font-medium">
              View plans
            </Link>
          </div>
        </motion.div>

        <div className="space-y-6">
          {/* Step 1: Prerequisites */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5 }}
            className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8"
          >
            <div className="flex items-start gap-4">
              <StepNumber n={1} />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-slate-200 mb-3">Prerequisites</h3>
                <p className="text-slate-400 text-sm mb-4">Make sure you have these installed before starting.</p>
                <div className="space-y-2">
                  <CodeSnippet code={`# Python 3.10+ and Node.js 18+ required
pip install pulse-os
npm install -g openclaw`} />
                </div>
              </div>
            </div>
          </motion.div>

          {/* Step 2: Configure OpenClaw */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, delay: 0.1 }}
            className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8"
          >
            <div className="flex items-start gap-4">
              <StepNumber n={2} />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-slate-200 mb-3">Configure OpenClaw</h3>
                <p className="text-slate-400 text-sm mb-4">
                  Set up your LLM provider. OpenClaw supports Anthropic, MiniMax, Ollama, Google, OpenAI, and any OpenAI-compatible endpoint.
                </p>
                <CodeSnippet code={`# Interactive setup — pick your provider and auth method
openclaw configure`} />
                <p className="text-slate-500 text-xs mt-3">
                  This creates <code className="text-sky-300/70">~/.openclaw/openclaw.json</code> with your provider settings.
                </p>
              </div>
            </div>
          </motion.div>

          {/* Step 3: Start the gateway */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, delay: 0.15 }}
            className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8"
          >
            <div className="flex items-start gap-4">
              <StepNumber n={3} />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-slate-200 mb-3">Start the OpenClaw gateway</h3>
                <p className="text-slate-400 text-sm mb-4">
                  The gateway routes requests between the TUI and your LLM provider.
                </p>
                <CodeSnippet code={`# Start in a separate terminal — keep it running
openclaw gateway run`} />
              </div>
            </div>
          </motion.div>

          {/* Step 4: Install the plugin */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, delay: 0.2 }}
            className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8"
          >
            <div className="flex items-start gap-4">
              <StepNumber n={4} />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-slate-200 mb-3">Install the PULSE memory plugin</h3>
                <CodeSnippet code="openclaw plugins install @pulse-os/memory-pulse" />
                <p className="text-slate-500 text-xs mt-3">
                  This registers the plugin and disables any built-in memory plugins. PULSE takes over the memory slot.
                </p>
              </div>
            </div>
          </motion.div>

          {/* Step 5: Launch */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, delay: 0.25 }}
            className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8"
          >
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0 w-10 h-10 rounded-full bg-green-500/20 border border-green-400/50 flex items-center justify-center text-green-400 font-bold">
                5
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-slate-200 mb-3">Launch OpenClaw</h3>
                <CodeSnippet code="openclaw tui" />
                <p className="text-slate-400 text-sm mt-4 leading-relaxed">
                  The PULSE sidecar API auto-starts on first session. Brain context is injected before every turn, and knowledge is captured after every response. Your agent now has permanent memory.
                </p>
              </div>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Features Grid */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.5 }}
          className="text-center mb-12"
        >
          <SectionHeading>What You Get</SectionHeading>
        </motion.div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <FeatureCard
            icon="~"
            title="Auto-Recall"
            description="Brain context is injected before every turn. Your agent starts each conversation with everything it learned from previous sessions."
            delay={0}
          />
          <FeatureCard
            icon="+"
            title="Auto-Capture"
            description="Knowledge is extracted after every turn. Lessons, failures, and causal patterns are saved to persistent memory without any manual effort."
            delay={0.1}
          />
          <FeatureCard
            icon="#"
            title="12-Source Search"
            description="Lessons, failures, patterns, predictions, anti-patterns, evidence, domains, schemas, procedures, graph, private, and index — all queried in parallel."
            delay={0.2}
          />
          <FeatureCard
            icon="*"
            title="Cross-Agent Memory"
            description="Claude, Gemini, Codex, Grok, and OpenClaw share the same brain. A fix discovered by one agent is available to all others instantly."
            delay={0}
          />
          <FeatureCard
            icon=">"
            title="Zero Config"
            description="The sidecar auto-starts the PULSE API on first use. No manual setup, no YAML files, no daemon management. Install and go."
            delay={0.1}
          />
          <FeatureCard
            icon="@"
            title="Any Provider"
            description="Works with Anthropic, MiniMax, Ollama, Google, OpenAI, and any OpenAI-compatible endpoint. Provider-agnostic by design."
            delay={0.2}
          />
        </div>
      </section>

      {/* Memory Tools */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.5 }}
          className="mb-10"
        >
          <SectionHeading>Memory Tools</SectionHeading>
          <p className="text-slate-400 max-w-2xl">
            Three tools are registered with your OpenClaw agent. The agent can call them mid-conversation.
          </p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
          className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl overflow-hidden"
        >
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-slate-700/50">
                <th className="px-8 py-4 text-sky-400 font-semibold text-sm">Tool</th>
                <th className="px-8 py-4 text-sky-400 font-semibold text-sm">Description</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/30">
              <tr>
                <td className="px-8 py-4">
                  <code className="text-green-400 font-mono text-sm">memory_search</code>
                </td>
                <td className="px-8 py-4 text-slate-300 text-sm">
                  Search the brain for relevant memories. Queries all 12 sources in parallel, ranked by salience, recency, and relevance.
                </td>
              </tr>
              <tr>
                <td className="px-8 py-4">
                  <code className="text-green-400 font-mono text-sm">memory_store</code>
                </td>
                <td className="px-8 py-4 text-slate-300 text-sm">
                  Save a lesson, failure, or pattern to persistent memory. Stored with metadata (agent, timestamp, salience) and available to all agents.
                </td>
              </tr>
              <tr>
                <td className="px-8 py-4">
                  <code className="text-green-400 font-mono text-sm">memory_get</code>
                </td>
                <td className="px-8 py-4 text-slate-300 text-sm">
                  Read a specific brain region directly — lessons, failures, patterns, anti-patterns, predictions, or any other Hippocampus file.
                </td>
              </tr>
            </tbody>
          </table>
        </motion.div>
      </section>

      {/* Config */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.5 }}
          className="mb-10"
        >
          <SectionHeading>Configuration</SectionHeading>
          <p className="text-slate-400 max-w-2xl">
            Optional. Defaults work out of the box. Drop this into your <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">openclaw.json</code> to customize.
          </p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
        >
          <CodeSnippet code={`{
  "plugins": {
    "@pulse-os/memory-pulse": {
      "baseUrl": "http://localhost:3100",
      "autoRecall": true,
      "autoCapture": true,
      "maxResults": 20,
      "maxContextTokens": 4096
    }
  }
}`} />
          <div className="mt-6 grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
            <div className="flex items-start gap-3">
              <code className="text-green-400 font-mono text-xs whitespace-nowrap mt-0.5">baseUrl</code>
              <p className="text-slate-400">PULSE sidecar API address. Auto-starts if not running.</p>
            </div>
            <div className="flex items-start gap-3">
              <code className="text-green-400 font-mono text-xs whitespace-nowrap mt-0.5">autoRecall</code>
              <p className="text-slate-400">Inject brain context before each turn. Default: true.</p>
            </div>
            <div className="flex items-start gap-3">
              <code className="text-green-400 font-mono text-xs whitespace-nowrap mt-0.5">autoCapture</code>
              <p className="text-slate-400">Extract knowledge after each turn. Default: true.</p>
            </div>
            <div className="flex items-start gap-3">
              <code className="text-green-400 font-mono text-xs whitespace-nowrap mt-0.5">maxResults</code>
              <p className="text-slate-400">Max memories returned per search. Default: 20.</p>
            </div>
            <div className="flex items-start gap-3">
              <code className="text-green-400 font-mono text-xs whitespace-nowrap mt-0.5">maxContextTokens</code>
              <p className="text-slate-400">Token budget for injected brain context. Default: 4096.</p>
            </div>
          </div>
        </motion.div>
      </section>

      {/* CTA */}
      <section className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 pt-16 pb-24">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
          className="bg-gradient-to-br from-sky-500/10 to-cyan-500/10 backdrop-blur-sm border border-sky-400/30 rounded-2xl p-10 text-center"
        >
          <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4">
            Ready to give your agent a brain?
          </h2>
          <p className="text-slate-400 mb-8 max-w-lg mx-auto">
            Five steps to set up. Zero config after that. Every session makes your agent smarter.
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
            <Link
              to="/pricing"
              className="px-8 py-3 rounded-xl bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 font-semibold text-lg shadow-lg shadow-sky-500/50 hover:shadow-sky-400/75 hover:-translate-y-1 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950"
            >
              Get Started
            </Link>
            <Link
              to="/docs"
              className="px-8 py-3 rounded-xl border-2 border-sky-400/50 text-sky-400 font-semibold text-lg hover:bg-sky-400/10 hover:border-sky-400 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950"
            >
              Read the Docs
            </Link>
          </div>
        </motion.div>
      </section>
    </div>
  );
}
