import { useState } from "react";
import { motion } from "framer-motion";
import { Search, Code2, BookOpen, Rocket, Zap, Shield, Globe } from "lucide-react";

const DOCS_SECTIONS = [
  {
    id: "getting-started",
    title: "Getting Started",
    icon: Rocket,
    articles: [
      { id: "intro", title: "Introduction to AeThex", content: `# Introduction to AeThex

**Write once. Build everywhere. Comply by default.**

AeThex is a programming language for cross-platform metaverse development. Write your game logic, authentication, and compliance rules once in AeThex, then compile to JavaScript, Lua (Roblox), Verse (UEFN), and C# (Unity).

## Why AeThex?

### The Problem
Building cross-platform games means writing the same code multiple times:
- **Roblox** → Lua
- **UEFN/Fortnite** → Verse/Blueprint
- **Unity/VRChat** → C#
- **Web** → JavaScript

Plus managing compliance (COPPA, FERPA, PII) separately on each platform.

### The Solution
Write once in AeThex. Compile to all platforms. Compliance built-in.

## Example

\`\`\`aethex
reality MyGame {
    platforms: [roblox, uefn, web]
}

journey AuthenticatePlayer(username) {
    platform: all

    let passport = new Passport(username)

    when passport.verify() {
        sync passport across [roblox, uefn, web]
        notify "Welcome, " + username + "!"
    }
}
\`\`\`

This single AeThex file compiles to:
- **JavaScript** for web browsers
- **Lua** for Roblox
- **Verse** for UEFN (Fortnite)
- **C#** for Unity (coming soon)` },
      { id: "install", title: "Installation", content: `# Installation

## Quick Install

### Via npm (Recommended)

\`\`\`bash
# Install globally
npm install -g @aethex.os/cli

# Verify installation
aethex --version
\`\`\`

### Via the OS Terminal

If you're using AeThex OS, the compiler is built-in:

\`\`\`bash
# In the terminal, type:
aethex --help
\`\`\``  },
      { id: "first-program", title: "Your First Program", content: `# Your First AeThex Program

## Hello World

Create a file called \`hello.aethex\`:

\`\`\`aethex
reality HelloWorld {
    platforms: all
}

journey Greet(name) {
    platform: all
    notify "Hello, " + name + "!"
}
\`\`\`

## Compile It

### In the Terminal
\`\`\`bash
aethex compile journey Greet(name) { notify "Hello, " + name + "!" }
\`\`\`

### In the IDE
1. Open the IDE
2. Create a new \`.aethex\` file
3. Click the **Compile** button
4. Select your target platform (JavaScript, Roblox, etc.)
5. Download the compiled code

## Run It

The compiled JavaScript will look like:

\`\`\`javascript
async function Greet(name) {
  console.log("Hello, " + name + "!");
}
\`\`\`

Run it:
\`\`\`bash
node hello.js
\`\`\`` }
    ]
  },
  {
    id: "language-guide",
    title: "Language Guide",
    icon: Code2,
    articles: [
      { id: "syntax", title: "Syntax Basics", content: `# AeThex Syntax

## Realities (Namespaces)

Realities define the scope and platforms for your code:

\`\`\`aethex
reality GameName {
    platforms: [roblox, uefn, web]
    type: "multiplayer"
}
\`\`\`

## Journeys (Functions)

Journeys are asynchronous functions that can run on any platform:

\`\`\`aethex
journey ProcessScore(player, score) {
    platform: all

    when score > 1000 {
        notify "High score achieved!"
    }
}
\`\`\`

## Variables

Use \`let\` to declare variables:

\`\`\`aethex
let username = "Player1"
let score = 0
let isAdmin = false
\`\`\`

## Control Flow

### when / otherwise

AeThex uses \`when\` for conditionals:

\`\`\`aethex
when player.age < 13 {
    notify "COPPA compliance required"
} otherwise {
    notify "Full features unlocked"
}
\`\`\`` },
      { id: "cross-platform", title: "Cross-Platform Sync", content: `# Cross-Platform Synchronization

## The Power of \`sync across\`

AeThex's killer feature: automatically sync data across all platforms:

\`\`\`aethex
import { Passport } from "@aethex.os/core"

journey SaveProgress(player) {
    let passport = player.passport

    # This ONE LINE syncs to all platforms
    sync passport across [roblox, uefn, web]
}
\`\`\`

## Platform-Specific Code

Sometimes you need platform-specific behavior:

\`\`\`aethex
journey DisplayLeaderboard() {
    platform: roblox {
        # Roblox-specific UI code
        reveal leaderboardGUI
    }

    platform: web {
        # Web-specific HTML
        reveal leaderboardHTML
    }
}
\`\`\`` },
      { id: "compliance", title: "Compliance & Safety", content: `# Compliance & Safety

## Built-in COPPA Compliance

AeThex automatically enforces COPPA:

\`\`\`aethex
import { Compliance } from "@aethex.os/core"

journey RegisterUser(username, age) {
    when !Compliance.isCOPPACompliant(age) {
        notify "Parent permission required"
        return
    }

    # User is 13+, proceed
    let passport = new Passport(username)
}
\`\`\`

## PII Detection

Automatically detect and block PII:

\`\`\`aethex
import { SafeInput } from "@aethex.os/core"

journey SubmitScore(player, scoreName) {
    let validation = SafeInput.validate(scoreName)

    when !validation.valid {
        notify "PII detected: " + validation.message
        return
    }

    # Safe to use
}
\`\`\`

SafeInput detects:
- Phone numbers
- Email addresses
- SSN
- Credit card numbers` }
    ]
  },
  {
    id: "standard-library",
    title: "Standard Library",
    icon: BookOpen,
    articles: [
      { id: "core", title: "@aethex.os/core", content: `# @aethex.os/core

The core AeThex runtime provides cross-platform utilities.

## Passport

Universal identity across platforms:

\`\`\`aethex
import { Passport } from "@aethex.os/core"

let passport = new Passport(userId, username)
passport.verify()
passport.syncAcross([roblox, web])
\`\`\`

## DataSync

Cross-platform data synchronization:

\`\`\`aethex
import { DataSync } from "@aethex.os/core"

DataSync.sync(playerData, [roblox, uefn])
let data = DataSync.pull(userId, "roblox")
\`\`\`

## SafeInput

PII detection and scrubbing:

\`\`\`aethex
import { SafeInput } from "@aethex.os/core"

let result = SafeInput.validate(userInput)
when result.valid {
    # Input is safe
}
\`\`\`

## Compliance

COPPA/FERPA checks:

\`\`\`aethex
import { Compliance } from "@aethex.os/core"

when Compliance.isCOPPACompliant(user.age) {
    # Can collect data
}

Compliance.logCheck(userId, "login", true)
\`\`\`` }
    ]
  },
  {
    id: "examples",
    title: "Examples",
    icon: Zap,
    articles: [
      { id: "hello-world", title: "Hello World", content: `# Hello World Example

\`\`\`aethex
reality HelloWorld {
    platforms: all
}

journey Greet(name) {
    platform: all
    notify "Hello, " + name + "!"
}
\`\`\`

Compiles to JavaScript:

\`\`\`javascript
async function Greet(name) {
  console.log("Hello, " + name + "!");
}
\`\`\`` },
      { id: "auth-example", title: "Cross-Platform Auth", content: `# Cross-Platform Authentication

\`\`\`aethex
import { Passport } from "@aethex.os/core"

reality UniversalAuth {
    platforms: [roblox, uefn, web]
}

journey Login(username) {
    platform: all

    let passport = new Passport(username)

    when passport.verify() {
        sync passport across [roblox, uefn, web]
        notify "Logged in across all platforms!"
        reveal passport
    }
}
\`\`\`` },
      { id: "foundry-exam", title: "Foundry Exam (Leaderboard)", content: `# The Foundry Certification Exam

Build a PII-safe, COPPA-compliant leaderboard:

\`\`\`aethex
import { SafeInput, Compliance } from "@aethex.os/core"

reality SecureLeaderboard {
    platforms: [roblox]
}

journey SubmitScore(player, playerName, score) {
    platform: roblox

    # STEP 1: COPPA check
    when !Compliance.isCOPPACompliant(player.age) {
        notify "Players under 13 cannot submit scores"
        return
    }

    # STEP 2: PII validation
    let nameValidation = SafeInput.validate(playerName)

    when !nameValidation.valid {
        notify "Invalid name: " + nameValidation.message
        Compliance.logCheck(player.userId, "leaderboard_check", false)
        return
    }

    # STEP 3: Success
    Compliance.logCheck(player.userId, "leaderboard_submission", true)
    notify "Score submitted successfully!"

    reveal {
        player: nameValidation.clean,
        score: score
    }
}
\`\`\`

**This is the certification exam!** If you can build this correctly, you're ready to work in metaverse development.` }
    ]
  }
];

export default function AeThexDocs() {
  const [activeSection, setActiveSection] = useState("getting-started");
  const [activeArticle, setActiveArticle] = useState("intro");
  const [search, setSearch] = useState("");

  const currentSection = DOCS_SECTIONS.find(s => s.id === activeSection);
  const currentArticle = currentSection?.articles.find(a => a.id === activeArticle);

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 text-slate-100 font-mono flex">
      {/* Sidebar */}
      <aside className="w-64 border-r border-white/10 bg-slate-950/60 backdrop-blur flex flex-col">
        <div className="p-4 border-b border-white/10">
          <h1 className="text-xl font-bold text-cyan-400">AeThex Docs</h1>
          <p className="text-xs text-slate-400 mt-1">Language Reference</p>
        </div>

        <div className="p-4 border-b border-white/10">
          <div className="relative">
            <Search className="absolute left-2 top-2 w-4 h-4 text-slate-400" />
            <input
              type="text"
              placeholder="Search docs..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full bg-slate-800 border border-white/10 rounded pl-8 pr-3 py-2 text-sm text-slate-200 placeholder-slate-500"
            />
          </div>
        </div>

        <nav className="flex-1 overflow-y-auto p-4">
          {DOCS_SECTIONS.map((section) => {
            const Icon = section.icon;
            return (
              <div key={section.id} className="mb-4">
                <button
                  onClick={() => {
                    setActiveSection(section.id);
                    setActiveArticle(section.articles[0].id);
                  }}
                  className={`w-full flex items-center gap-2 px-3 py-2 rounded text-sm font-semibold transition ${
                    activeSection === section.id
                      ? "bg-cyan-500/20 text-cyan-100"
                      : "text-slate-300 hover:bg-white/5"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {section.title}
                </button>
                {activeSection === section.id && (
                  <div className="mt-2 ml-6 space-y-1">
                    {section.articles.map((article) => (
                      <button
                        key={article.id}
                        onClick={() => setActiveArticle(article.id)}
                        className={`w-full text-left px-3 py-1 rounded text-xs transition ${
                          activeArticle === article.id
                            ? "bg-cyan-500/10 text-cyan-200"
                            : "text-slate-400 hover:text-slate-200"
                        }`}
                      >
                        {article.title}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </nav>

        <div className="p-4 border-t border-white/10 text-xs text-slate-400">
          <div className="flex items-center gap-2 mb-2">
            <Globe className="w-3 h-3" />
            <span>aethex.dev/lang</span>
          </div>
          <div className="flex items-center gap-2">
            <Shield className="w-3 h-3" />
            <span>v1.0.0</span>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <main className="flex-1 overflow-y-auto">
        <div className="max-w-4xl mx-auto p-8">
          <motion.article
            key={activeArticle}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="prose prose-invert prose-cyan max-w-none"
          >
            <div
              className="markdown-content"
              dangerouslySetInnerHTML={{
                __html: currentArticle?.content.replace(/```(\w+)\n([\s\S]*?)```/g,
                  '<pre class="bg-slate-800 p-4 rounded text-sm overflow-x-auto"><code class="language-$1">$2</code></pre>'
                ).replace(/`([^`]+)`/g, '<code class="bg-slate-800 px-2 py-1 rounded text-sm">$1</code>')
                  .replace(/^# (.+)$/gm, '<h1 class="text-3xl font-bold text-cyan-400 mb-4">$1</h1>')
                  .replace(/^## (.+)$/gm, '<h2 class="text-2xl font-semibold text-white mt-8 mb-3">$1</h2>')
                  .replace(/^### (.+)$/gm, '<h3 class="text-xl font-medium text-slate-200 mt-6 mb-2">$1</h3>')
                  .replace(/^\*\*(.+?)\*\*/gm, '<strong class="text-cyan-300">$1</strong>')
                  .replace(/^- (.+)$/gm, '<li class="ml-6 list-disc text-slate-300">$1</li>')
              }}
            />
          </motion.article>
        </div>
      </main>
    </div>
  );
}
