"use client";

import { useState } from "react";
import Link from "next/link";

function Icon({ name, className = "" }: { name: string; className?: string }) {
  return <span className={`material-symbols-outlined ${className}`}>{name}</span>;
}

// ─── Sidebar nav data ─────────────────────────────────────────────────────────
const NAV = [
  {
    group: "Introduction",
    items: [
      { icon: "rocket_launch", label: "Getting Started", id: "getting-started", active: true },
      { icon: "description",   label: "Architecture",    id: "architecture" },
    ],
  },
  {
    group: "Core Concepts",
    items: [
      { icon: "person_search", label: "Agent Personas",  id: "personas" },
      { icon: "account_tree",  label: "Mesh Topology",   id: "topology" },
      { icon: "memory",        label: "Memory Systems",  id: "memory" },
    ],
  },
  {
    group: "Development",
    items: [
      { icon: "code",        label: "API Reference", id: "api" },
      { icon: "inventory_2", label: "SDKs & Tools",  id: "sdks" },
      { icon: "terminal",    label: "CLI Tool",      id: "cli" },
    ],
  },
];

// ─── Code block ───────────────────────────────────────────────────────────────
function CodeBlock({ filename, children }: { filename: string; children: React.ReactNode }) {
  const [copied, setCopied] = useState(false);
  return (
    <div className="relative rounded-xl border overflow-hidden shadow-2xl" style={{ background:"#0a0716", borderColor:"#1f1a30", boxShadow:"0 0 20px rgba(183,166,251,0.06)" }}>
      <div className="flex items-center justify-between px-4 py-2.5 border-b" style={{ borderColor:"#1f1a30" }}>
        <div className="flex gap-1.5">
          <div className="size-2.5 rounded-full bg-red-500/40" />
          <div className="size-2.5 rounded-full bg-amber-500/40" />
          <div className="size-2.5 rounded-full bg-emerald-500/40" />
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[11px] font-mono text-slate-500">{filename}</span>
          <button
            onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1800); }}
            className="p-1 rounded hover:bg-white/5 text-slate-600 hover:text-[#B7A6FB] transition-colors"
          >
            <Icon name={copied ? "check" : "content_copy"} className="text-sm" />
          </button>
        </div>
      </div>
      <div className="p-5 text-sm leading-7 font-mono overflow-x-auto">{children}</div>
    </div>
  );
}

// ─── Section wrapper ──────────────────────────────────────────────────────────
function Section({ id, children }: { id: string; children: React.ReactNode }) {
  return <section id={id} className="mb-20 scroll-mt-24">{children}</section>;
}

function SectionHeading({ title, badge }: { title: string; badge?: string }) {
  return (
    <div className="flex items-center gap-4 mb-6">
      <h2 className="text-3xl font-bold text-white">{title}</h2>
      {badge && (
        <span className="rounded-full px-3 py-1 text-[10px] font-bold uppercase tracking-widest" style={{ background:"rgba(183,166,251,0.1)", color:"#B7A6FB" }}>
          {badge}
        </span>
      )}
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────
export default function DocsPage() {
  return (
    <div className="relative flex min-h-screen flex-col overflow-x-hidden bg-[#070312] text-slate-100">

      {/* ── Topbar ── */}
      <header className="sticky top-0 z-50 flex h-16 w-full items-center justify-between border-b border-white/[0.07] bg-[#070312]/85 px-6 backdrop-blur-md lg:px-10">
        <div className="flex items-center gap-8">
          <Link href="/" className="flex items-center gap-3">
            <div className="size-8 rounded-lg bg-[#B7A6FB] flex items-center justify-center text-[#070312]">
              <Icon name="hub" className="text-xl font-bold" />
            </div>
            <h2 className="text-xl font-bold tracking-tight text-white">negoT8</h2>
          </Link>
          <div className="relative hidden md:block">
            <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-slate-500">
              <Icon name="search" className="text-sm" />
            </div>
            <input
              className="h-9 w-64 rounded-lg border-none pl-10 text-sm text-white placeholder-slate-600 focus:ring-1 focus:ring-[#B7A6FB]/50 outline-none"
              style={{ background:"#0f0a1f" }}
              placeholder="Search documentation..."
              type="text"
            />
          </div>
        </div>
        <div className="flex items-center gap-6">
          <nav className="hidden lg:flex items-center gap-6">
            {["Docs", "API", "Showcase"].map((l) => (
              <a key={l} href="#" className="text-sm font-medium text-slate-300 hover:text-[#B7A6FB] transition-colors">{l}</a>
            ))}
          </nav>
          <div className="h-4 w-px bg-white/10" />
          <Link href="/dashboard" className="flex items-center gap-2 rounded-lg bg-[#B7A6FB] px-4 py-2 text-sm font-bold text-[#070312] hover:opacity-90 active:scale-95 transition-all">
            Console
            <Icon name="arrow_outward" className="text-sm" />
          </Link>
        </div>
      </header>

      <div className="flex flex-1">

        {/* ── Left sidebar ── */}
        <aside className="sticky top-16 hidden h-[calc(100vh-64px)] w-64 flex-col border-r border-white/[0.07] bg-[#070312] p-6 overflow-y-auto lg:flex" style={{ scrollbarWidth:"thin", scrollbarColor:"#1f1a30 transparent" }}>
          {NAV.map(({ group, items }) => (
            <div key={group} className="mb-8">
              <h3 className="mb-4 text-[10px] font-bold uppercase tracking-widest text-slate-600">{group}</h3>
              <ul className="space-y-1">
                {items.map((item) => (
                  <li key={item.id}>
                    <a
                      href={`#${item.id}`}
                      className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                        item.active
                          ? "bg-[#B7A6FB]/10 text-[#B7A6FB]"
                          : "text-slate-400 hover:bg-white/5 hover:text-slate-200"
                      }`}
                    >
                      <Icon name={item.icon} className="text-lg" />
                      {item.label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          <div className="mt-auto pt-6">
            <div className="rounded-xl border p-4" style={{ background:"#0f0a1f", borderColor:"#1f1a30" }}>
              <p className="text-xs font-medium text-slate-500">Version</p>
              <p className="text-sm font-bold text-[#B7A6FB]">v2.0.0-stable</p>
            </div>
          </div>
        </aside>

        {/* ── Main content ── */}
        <main className="flex-1 px-6 py-12 lg:px-20">
          <div className="mx-auto max-w-3xl">

            {/* Breadcrumb */}
            <nav className="mb-8 flex items-center gap-2 text-sm text-slate-600">
              <a href="#" className="hover:text-slate-300 transition-colors">Docs</a>
              <Icon name="chevron_right" className="text-xs" />
              <span className="text-[#B7A6FB]">Getting Started</span>
            </nav>

            {/* ── Quick Start ── */}
            <Section id="getting-started">
              <h1 className="mb-4 text-5xl font-bold tracking-tight text-white">Quick Start Guide</h1>
              <p className="text-xl leading-relaxed text-slate-400 mb-10">
                Deploy your first negoT8 negotiation in under five minutes. Two autonomous agents, one on-chain settlement.
              </p>

              <div className="space-y-8">
                {/* Step 1 */}
                <div>
                  <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-white">
                    <span className="flex size-6 items-center justify-center rounded-full text-xs font-bold text-[#B7A6FB]" style={{ background:"rgba(183,166,251,0.15)" }}>1</span>
                    Install the SDK
                  </h3>
                  <CodeBlock filename="terminal">
                    <span className="text-[#B7A6FB]">$</span>{" "}
                    <span className="text-slate-200">pip install</span>{" "}
                    <span className="text-emerald-400">negot8</span>
                  </CodeBlock>
                </div>

                {/* Step 2 */}
                <div>
                  <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-white">
                    <span className="flex size-6 items-center justify-center rounded-full text-xs font-bold text-[#B7A6FB]" style={{ background:"rgba(183,166,251,0.15)" }}>2</span>
                    Configure Your Instance
                  </h3>
                  <CodeBlock filename="config.py">
                    <div><span className="text-slate-500"># Initialize negoT8</span></div>
                    <div><span className="text-[#B7A6FB]">from</span> <span className="text-emerald-400">negot8</span> <span className="text-[#B7A6FB]">import</span> negoT8</div>
                    <br />
                    <div>mesh = <span className="text-emerald-400">negoT8</span>{"({"}</div>
                    <div className="pl-4"><span className="text-slate-400">api_key</span>=<span className="text-emerald-300">os.environ["AM_KEY"]</span>,</div>
                    <div className="pl-4"><span className="text-slate-400">region</span>=<span className="text-emerald-300">"us-east-mesh"</span>,</div>
                    <div className="pl-4"><span className="text-slate-400">strategy</span>=<span className="text-emerald-300">"tit-for-tat"</span></div>
                    <div>{"}"}</div>
                    <br />
                    <div><span className="text-slate-500"># Connect to the protocol</span></div>
                    <div><span className="text-[#B7A6FB]">await</span> mesh.<span className="text-emerald-400">connect</span>()</div>
                  </CodeBlock>
                </div>

                {/* Step 3 */}
                <div>
                  <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-white">
                    <span className="flex size-6 items-center justify-center rounded-full text-xs font-bold text-[#B7A6FB]" style={{ background:"rgba(183,166,251,0.15)" }}>3</span>
                    Start a Negotiation
                  </h3>
                  <CodeBlock filename="negotiate.py">
                    <div>session = <span className="text-[#B7A6FB]">await</span> mesh.<span className="text-emerald-400">negotiate</span>{"({"}</div>
                    <div className="pl-4"><span className="text-slate-400">feature</span>=<span className="text-emerald-300">"expenses"</span>,</div>
                    <div className="pl-4"><span className="text-slate-400">agent_a</span>=<span className="text-emerald-300">"@alice"</span>,</div>
                    <div className="pl-4"><span className="text-slate-400">agent_b</span>=<span className="text-emerald-300">"@bob"</span>,</div>
                    <div className="pl-4"><span className="text-slate-400">limit</span>=<span className="text-[#B7A6FB]">5000</span></div>
                    <div>{"}"}</div>
                    <br />
                    <div><span className="text-slate-500"># Settlement happens automatically</span></div>
                    <div><span className="text-[#B7A6FB]">print</span>(session.<span className="text-emerald-400">outcome</span>)  <span className="text-slate-500"># AGREED: ...</span></div>
                  </CodeBlock>
                </div>
              </div>
            </Section>

            {/* ── Architecture ── */}
            <Section id="architecture">
              <SectionHeading title="Architecture" />
              <p className="text-slate-400 leading-relaxed mb-6">
                negoT8 runs a bilateral negotiation protocol over a persistent WebSocket mesh. Each agent maintains a preference vector and personality profile. Rounds are logged immutably, and final settlement is recorded on Polygon POS.
              </p>
              <div className="grid grid-cols-3 gap-4 text-center">
                {[
                  { icon: "person", label: "Personal Agents", desc: "Telegram-native, personality-driven" },
                  { icon: "sync_alt", label: "Negotiation Engine", desc: "Game-theoretic, multi-round" },
                  { icon: "link", label: "Blockchain Layer", desc: "Polygon POS — immutable record" },
                ].map(({ icon, label, desc }) => (
                  <div key={label} className="rounded-xl p-5 border border-white/[0.06]" style={{ background:"#0f0a1f" }}>
                    <div className="size-10 rounded-lg flex items-center justify-center mx-auto mb-3" style={{ background:"rgba(183,166,251,0.1)" }}>
                      <Icon name={icon} className="text-[#B7A6FB]" />
                    </div>
                    <p className="text-white text-sm font-bold mb-1">{label}</p>
                    <p className="text-slate-500 text-xs">{desc}</p>
                  </div>
                ))}
              </div>
            </Section>

            {/* ── Agent Personas ── */}
            <Section id="personas">
              <SectionHeading title="Agent Personas" badge="Core Concept" />
              <p className="mb-8 text-slate-400 leading-relaxed">
                Personas define the negotiation behaviour and cognitive boundaries of each agent. Assigning a persona controls how aggressively the agent bids, how empathetically it responds, and how analytically it evaluates proposals.
              </p>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                {[
                  { icon: "psychology",  name: "Analytical",     desc: "Pattern recognition, data-first decisions. Minimal emotional drift — best for financial negotiations." },
                  { icon: "terminal",    name: "Aggressive",     desc: "Opens high, concedes slow. Optimised for maximising individual outcome in competitive scenarios." },
                  { icon: "chat",        name: "Empathetic",     desc: "Human-centric, sentiment-aligned. Prioritises mutual satisfaction over raw gain." },
                  { icon: "balance",     name: "Balanced",       desc: "Default profile. Adapts strategy dynamically based on opponent behaviour and round history." },
                  { icon: "favorite",    name: "People Pleaser", desc: "High concession rate, fast convergence. Ideal when relationship preservation matters most." },
                  { icon: "security",    name: "Sentinel",       desc: "Enforces fair-play policy. Flags anomalous proposals and prevents runaway concession spirals." },
                ].map(({ icon, name, desc }) => (
                  <div key={name} className="group rounded-xl border border-white/[0.06] p-6 transition-all hover:border-[#B7A6FB]/40" style={{ background:"#0f0a1f" }}>
                    <div className="mb-4 size-10 rounded-lg flex items-center justify-center text-[#B7A6FB] transition-transform group-hover:scale-110" style={{ background:"rgba(183,166,251,0.1)" }}>
                      <Icon name={icon} />
                    </div>
                    <h4 className="mb-2 font-bold text-white">{name}</h4>
                    <p className="text-sm leading-relaxed text-slate-500">{desc}</p>
                  </div>
                ))}
              </div>
            </Section>

            {/* ── Mesh Topology ── */}
            <Section id="topology">
              <SectionHeading title="Mesh Topology" />
              <p className="text-slate-400 leading-relaxed mb-6">
                The negoT8 protocol supports 1:1 bilateral negotiations today, with n-party consensus rolling out in v2.1. Agents communicate over an encrypted Socket.IO channel. The backend orchestrator assigns feature handlers (expenses, scheduling, freelance, etc.) and routes messages to the correct agent pair.
              </p>
              <div className="p-5 rounded-xl border border-white/[0.06] font-mono text-xs leading-6 text-slate-400" style={{ background:"#08051a" }}>
                <div><span className="text-[#B7A6FB]">Agent A</span> → PROPOSE → <span className="text-[#22d3ee]">Orchestrator</span> → RELAY → <span className="text-[#B7A6FB]">Agent B</span></div>
                <div><span className="text-[#B7A6FB]">Agent B</span> → COUNTER → <span className="text-[#22d3ee]">Orchestrator</span> → RELAY → <span className="text-[#B7A6FB]">Agent A</span></div>
                <div className="text-slate-600">{'─'.repeat(52)}</div>
                <div><span className="text-emerald-400">CONSENSUS</span> → <span className="text-[#22d3ee]">Orchestrator</span> → SETTLE → <span className="text-amber-400">Blockchain</span></div>
              </div>
            </Section>

            {/* ── API Reference ── */}
            <Section id="api">
              <SectionHeading title="Core API Endpoints" />
              <div className="overflow-hidden rounded-xl border border-white/[0.07]" style={{ background:"#0f0a1f" }}>
                <table className="w-full text-left text-sm">
                  <thead className="border-b border-white/[0.07] uppercase tracking-wider text-slate-600 text-[11px]">
                    <tr>
                      <th className="px-6 py-4 font-bold">Endpoint</th>
                      <th className="px-6 py-4 font-bold">Method</th>
                      <th className="px-6 py-4 font-bold">Description</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/[0.04]">
                    {[
                      { path:"/negotiations",        method:"POST", color:"text-emerald-400", desc:"Create a new negotiation session between two agents." },
                      { path:"/negotiations",        method:"GET",  color:"text-blue-400",   desc:"List all negotiations with status and fairness score." },
                      { path:"/negotiations/:id",    method:"GET",  color:"text-blue-400",   desc:"Fetch full detail, rounds, and analytics for a session." },
                      { path:"/negotiations/:id/start", method:"POST", color:"text-emerald-400", desc:"Kick off the negotiation loop between the two agents." },
                      { path:"/users",               method:"POST", color:"text-emerald-400", desc:"Register a new Telegram user with a personality profile." },
                      { path:"/users/:id",           method:"GET",  color:"text-blue-400",   desc:"Retrieve user profile and personality settings." },
                      { path:"/stats",               method:"GET",  color:"text-blue-400",   desc:"Global platform metrics: resolved, active, fairness avg." },
                    ].map(({ path, method, color, desc }) => (
                      <tr key={path+method} className="hover:bg-white/[0.02] transition-colors">
                        <td className="px-6 py-4"><code className="text-[#B7A6FB] text-xs">{path}</code></td>
                        <td className={`px-6 py-4 font-mono text-xs font-bold ${color}`}>{method}</td>
                        <td className="px-6 py-4 text-slate-500 text-xs">{desc}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Section>

            {/* ── SDKs & Tools ── */}
            <Section id="sdks">
              <SectionHeading title="SDKs & Tools" />
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                {[
                  { icon:"smart_toy",  name:"Python SDK",      tag:"Official",  desc:"pip install negot8" },
                  { icon:"send",       name:"Telegram Bot",    tag:"Built-in",  desc:"@negoT8Bot on Telegram" },
                  { icon:"record_voice_over", name:"Voice API", tag:"ElevenLabs", desc:"AI-generated settlement summaries" },
                ].map(({ icon, name, tag, desc }) => (
                  <div key={name} className="rounded-xl border border-white/[0.06] p-5" style={{ background:"#0f0a1f" }}>
                    <div className="size-9 rounded-lg flex items-center justify-center mb-3" style={{ background:"rgba(183,166,251,0.1)" }}>
                      <Icon name={icon} className="text-[#B7A6FB]" />
                    </div>
                    <div className="flex items-center gap-2 mb-1">
                      <p className="text-sm font-bold text-white">{name}</p>
                      <span className="text-[9px] px-1.5 py-0.5 rounded font-mono" style={{ background:"rgba(183,166,251,0.1)", color:"#B7A6FB" }}>{tag}</span>
                    </div>
                    <p className="text-xs text-slate-600 font-mono">{desc}</p>
                  </div>
                ))}
              </div>
            </Section>

            {/* ── CLI ── */}
            <Section id="cli">
              <SectionHeading title="CLI Tool" />
              <p className="text-slate-400 text-sm leading-relaxed mb-6">Run and inspect negotiations directly from your terminal.</p>
              <CodeBlock filename="terminal">
                <div><span className="text-[#B7A6FB]">$</span> <span className="text-slate-200">negot8 negotiate</span> <span className="text-emerald-300">--feature expenses --agent-a @alice --agent-b @bob</span></div>
                <br />
                <div><span className="text-slate-600">▶ Round 1 · Agent A proposes $54.20</span></div>
                <div><span className="text-slate-600">▶ Round 2 · Agent B counters $58.00</span></div>
                <div><span className="text-slate-600">▶ Round 3 · Convergence at 98.4%</span></div>
                <div><span className="text-emerald-400">✓ SETTLED · $56.10 · TX: 0x8fb…442b</span></div>
              </CodeBlock>
            </Section>

            {/* Footer */}
            <footer className="mt-16 flex flex-col items-center justify-between gap-6 border-t border-white/[0.07] py-10 md:flex-row">
              <div className="flex items-center gap-4 text-sm text-slate-600">
                <span>© 2026 negoT8 Protocol</span>
                <div className="size-1 rounded-full bg-slate-700" />
                <a href="#" className="hover:text-[#B7A6FB] transition-colors">Privacy</a>
              </div>
              <div className="flex gap-3">
                <Link href="/" className="flex items-center gap-1.5 text-xs text-slate-500 hover:text-[#B7A6FB] transition-colors font-medium">
                  <Icon name="arrow_back" className="text-sm" /> Back to landing
                </Link>
                <Link href="/dashboard" className="flex items-center gap-1.5 text-xs text-[#B7A6FB] hover:text-white transition-colors font-medium">
                  Open Dashboard <Icon name="arrow_forward" className="text-sm" />
                </Link>
              </div>
            </footer>

          </div>
        </main>

        {/* ── Right TOC ── */}
        <aside className="sticky top-16 hidden h-[calc(100vh-64px)] w-64 p-10 xl:block">
          <h4 className="mb-4 text-[10px] font-bold uppercase tracking-widest text-slate-600">On this page</h4>
          <nav className="space-y-4">
            {[
              { label:"Quick Start",    id:"getting-started", active:true },
              { label:"Architecture",   id:"architecture" },
              { label:"Agent Personas", id:"personas" },
              { label:"Mesh Topology",  id:"topology" },
              { label:"API Reference",  id:"api" },
              { label:"SDKs & Tools",   id:"sdks" },
              { label:"CLI Tool",       id:"cli" },
            ].map(({ label, id, active }) => (
              <a key={id} href={`#${id}`}
                className={`block text-sm font-medium transition-colors ${active ? "text-[#B7A6FB]" : "text-slate-600 hover:text-slate-200"}`}>
                {label}
              </a>
            ))}
          </nav>
          <div className="mt-10 rounded-xl p-4 border" style={{ background:"linear-gradient(135deg,rgba(183,166,251,0.08),transparent)", borderColor:"rgba(183,166,251,0.15)" }}>
            <h5 className="mb-2 text-xs font-bold text-white">Need help?</h5>
            <p className="mb-4 text-xs leading-relaxed text-slate-400">Connect with the team on Telegram or file an issue on GitHub.</p>
            <a href="https://t.me/" target="_blank" rel="noopener noreferrer" className="block w-full rounded-lg py-2 text-center text-xs font-bold text-white border border-white/10 hover:border-[#B7A6FB]/40 transition-colors" style={{ background:"#0f0a1f" }}>
              Open Telegram
            </a>
          </div>
        </aside>

      </div>
    </div>
  );
}
