"use client"

import { useState } from "react"
import Header from "@/components/header"
import Footer from "@/components/footer"
import { 
  ArrowUpRight, 
  Terminal, 
  Globe, 
  FileCode, 
  Cpu, 
  RefreshCw, 
  Check, 
  ExternalLink,
  ChevronRight
} from "lucide-react"

// Types
type Tool = {
  id: string
  name: string
  isNew?: boolean
  description: string
  categories: string[]
  details?: string
  placeholderInput?: string
  mockResult?: (domain: string) => string
}

export default function ToolsPage() {
  const [selectedTool, setSelectedTool] = useState<Tool | null>(null)
  const [inputDomain, setInputDomain] = useState("")
  const [isSimulating, setIsSimulating] = useState(false)
  const [simulationLog, setSimulationLog] = useState<string[]>([])
  const [simulationResult, setSimulationResult] = useState("")
  const [activeCategory, setActiveCategory] = useState("all")

  // Waitlist State
  const [waitlistEmail, setWaitlistEmail] = useState("")
  const [waitlistSubmitted, setWaitlistSubmitted] = useState(false)
  const [waitlistLoading, setWaitlistLoading] = useState(false)

  const categoryLabels: Record<string, string> = {
    ai: "AI AGENTS",
    seo: "SEO",
    marketing: "MARKETING",
    social: "SOCIAL",
    dev: "DEVELOPER",
    design: "DESIGN",
    careers: "CAREERS",
  }

  const freeTools: Tool[] = [
    {
      id: "ad-maker",
      name: "Ad Maker",
      isNew: true,
      categories: ["marketing", "ai"],
      description: "Generate three on-brand ad creatives from any domain. AI picks 3 of 12 creative directions for your brand, then a different image model paints each — OpenAI and xAI via the Vercel AI Gateway. Downloadable PNGs.",
      placeholderInput: "e.g. apple.com",
      mockResult: (domain) => `[
  {
    "creativeDirection": "Minimalist Feature Highlight",
    "headline": "Less is everything. Meet the new standard for ${domain.split('.')[0]}.",
    "subheading": "Precision engineered. Beautifully simple.",
    "model": "DALL-E 3 (Vercel AI Gateway)",
    "imageMock": "[Minimalist product rendering with warm orange highlights on dark slate canvas]"
  },
  {
    "creativeDirection": "Bold Typography",
    "headline": "RETHINK WHAT IS POSSIBLE.",
    "subheading": "Accelerate your workflows with ${domain} today.",
    "model": "Flux.1 Dev (Vercel AI Gateway)",
    "imageMock": "[High contrast typographic art showcasing key brand features]"
  },
  {
    "creativeDirection": "Lifestyle & Human Connection",
    "headline": "Designed for the way you work.",
    "subheading": "Join thousands who trust ${domain.split('.')[0]} to power their day.",
    "model": "xAI Grok-Image-1",
    "imageMock": "[A professional interacting with sleek interfaces reflecting the ${domain} color palette]"
  }
]`
    },
    {
      id: "llms-txt",
      name: "llms.txt Generator",
      isNew: true,
      categories: ["ai", "dev"],
      description: "Generate a spec-compliant llms.txt and llms-full.txt for any domain. Crawls the sitemap, classifies pages, scrapes clean Markdown, and outputs both files ready to host at the root of your site for ChatGPT, Claude, Perplexity, and Cursor.",
      placeholderInput: "e.g. stripe.com",
      mockResult: (domain) => `# llms.txt for ${domain}

> Spec-compliant documentation map for LLMs and AI Agents.

## Main Resources
- [Home Page](https://${domain}/) - Core services, features, and platform overview.
- [Documentation](https://${domain}/docs) - Complete API references, developer quickstarts, and integration guidelines.
- [Pricing](https://${domain}/pricing) - Pricing plans, tiers, usage billing detail.

## Detailed Specs (llms-full.txt)
- [API Reference](https://${domain}/docs/api) - Full endpoint specifications.
- [SDKs & Libraries](https://${domain}/docs/sdks) - Official TypeScript, Python, and Go libraries.
- [Security & Trust](https://${domain}/trust) - SOC2 compliance, security architecture.`
    },
    {
      id: "ai-seo",
      name: "AI-SEO / GEO Checker",
      isNew: true,
      categories: ["seo", "ai"],
      description: "Score any page for how well it ranks in ChatGPT, Perplexity, Google AI Overviews, and Copilot. Research-backed checks for schema, structure, freshness, and llms.txt, plus a one-click fix list you can paste into Cursor or Claude Code.",
      placeholderInput: "e.g. github.com/features",
      mockResult: (domain) => `================================================
AI-SEO / GEO CHECKER SCORECARD FOR: ${domain}
================================================

Overall AI Optimization Index: 78/100

Detailed Scores:
- JSON-LD Structured Data Schema: 92/100 (Excellent tags, breadcrumbs)
- llms.txt Spec Availability: 0/100 (Missing at root level /llms.txt)
- Content Readability for LLM Parsers: 85/100 (High semantic density, low layout noise)
- Freshness & Metadata Accuracy: 75/100 (Update dates are not programmatically visible)

Recommended fixes for Cursor / Claude Code:
1. "Create an llms.txt at public/llms.txt containing links to all docs."
2. "Inject a <meta name=\"last-modified\" content=\"2026-06-15\"> to boost freshness scoring."
3. "Add semantic landmarks (<main>, <article>) inside root page components."`
    },
    {
      id: "design-md",
      name: "Design.md Generator",
      isNew: true,
      categories: ["dev", "design"],
      description: "Generate a plain-text design system from any website: colors, typography, components, and visual identity. Readable by humans and AI agents.",
      placeholderInput: "e.g. vercel.com",
      mockResult: (domain) => `# Design System for ${domain}

## Core Palette
- Primary: #000000 (Black)
- Secondary: #ffffff (White)
- Accent: #0070f3 (Vercel Blue)
- Muted: #888888 (Gray)

## Typography
- Main Sans Font: Geist Sans, Inter, sans-serif
- Monospace Font: Geist Mono, SFMono-Regular, monospace

## Components & Styles
- Button Style: Pill-shaped, border border-border, transition hover:bg-opacity-90.
- Card Style: Border border-border, background #ffffff, subtle box-shadow on hover.`
    },
    {
      id: "sitemap",
      name: "Sitemap Generator",
      categories: ["seo", "dev"],
      description: "Crawl any domain and get a valid XML sitemap. Download as a ready-to-submit .xml file for Google Search Console.",
      placeholderInput: "e.g. rethinksoft.com",
      mockResult: (domain) => `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://${domain}/</loc>
    <lastmod>2026-06-15T12:00:00+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://${domain}/about</loc>
    <lastmod>2026-06-15T12:00:00+00:00</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>https://${domain}/services</loc>
    <lastmod>2026-06-15T12:00:00+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
  </url>
</urlset>`
    },
    {
      id: "url-markdown",
      name: "URL to Markdown Converter",
      categories: ["dev", "ai"],
      description: "Convert any webpage to clean GitHub Flavored Markdown. Good for docs, AI context, or content migration.",
      placeholderInput: "e.g. react.dev/reference/react",
      mockResult: (domain) => `# React Reference Overview

Explore the core React APIs for creating components, managing state, and interacting with the DOM.

## Hooks
- \`useState\`: Declare a state variable that you can update directly.
- \`useEffect\`: Synchronize a component with an external system.

## Components
- \`<Suspense>\`: Lets you display a fallback until its children have finished loading.`
    },
    {
      id: "og-checker",
      name: "Open Graph Checker & Structured Data Extractor",
      categories: ["seo", "dev"],
      description: "Check Open Graph tags and extract JSON-LD schemas, Twitter Cards, and meta tags from any URL. Formatted and ready to copy.",
      placeholderInput: "e.g. producthunt.com",
      mockResult: (domain) => `{
  "meta": {
    "title": "Product Hunt - The best new products in tech.",
    "description": "Discover your next favorite website, mobile app, or tech gadget.",
    "robots": "index, follow"
  },
  "openGraph": {
    "og:title": "Product Hunt",
    "og:description": "The best new products in tech.",
    "og:type": "website",
    "og:url": "https://${domain}",
    "og:image": "https://${domain}/og-image.png"
  },
  "twitter": {
    "twitter:card": "summary_large_image",
    "twitter:site": "@ProductHunt",
    "twitter:title": "Product Hunt"
  }
}`
    },
    {
      id: "email-signature",
      name: "Email Signature Generator",
      categories: ["marketing"],
      description: "Create a professional HTML email signature with your brand colors, logo, and social links. Browse examples and auto-populate from any domain.",
      placeholderInput: "e.g. apple.com",
      mockResult: (domain) => `<table cellpadding="0" cellspacing="0" style="font-family: Arial, sans-serif; color: #333333; line-height: 1.5;">
  <tr>
    <td style="padding-right: 15px; border-right: 2px solid #e35706; vertical-align: middle;">
      <img src="https://logo.clearbit.com/${domain}" width="60" alt="Logo" style="border-radius: 4px; display: block;" />
    </td>
    <td style="padding-left: 15px; vertical-align: middle;">
      <div style="font-weight: bold; font-size: 16px; color: #111111;">John Doe</div>
      <div style="font-size: 13px; color: #666666; margin-bottom: 4px;">Director of Product | ${domain.split('.')[0]}</div>
      <div style="font-size: 12px;">
        <span style="color: #e35706;">W:</span> <a href="https://${domain}" style="color: #333333; text-decoration: none;">https://${domain}</a>
        <br />
        <span style="color: #e35706;">E:</span> john@${domain}
      </div>
    </td>
  </tr>
</table>`
    },
    {
      id: "dns-lookup",
      name: "DNS Lookup Tool",
      categories: ["dev"],
      description: "Free DNS lookup with MX record lookup, SSL certificate checker, WHOIS data, reverse DNS, redirect chains, and hosting provider detection.",
      placeholderInput: "e.g. google.com",
      mockResult: (domain) => `; ${domain} DNS Lookup
; A Records
${domain}.      300     IN      A       142.250.190.46

; MX Records
${domain}.      3600    IN      MX      10 aspmx.l.google.com.
${domain}.      3600    IN      MX      20 alt1.aspmx.l.google.com.

; SSL Certificate: Valid (Expires in 89 days)
; Hosting Provider: Google LLC
; Reverse DNS: lga34s36-in-f14.1e100.net`
    },
    {
      id: "twitter-validator",
      name: "Twitter Card Validator",
      categories: ["marketing", "seo"],
      description: "Preview how your page looks when shared on X. Validates Twitter Card meta tags and suggests fixes.",
      placeholderInput: "e.g. rethinksoft.com/blog",
      mockResult: (domain) => `=========================================
TWITTER CARD VALIDATION FOR: ${domain}
=========================================
Card Type: summary_large_image [Valid]
Site Account: @Rethinksoft1 [Valid]
Title: Rethinksoft Blog - AI Insights & Tech Trends [Valid]
Description: Read our latest updates on AI, ML implementations, and business solutions [Valid]
Image URL: https://${domain}/blog-hero.jpg [Found, 1200x630px]

Fix suggestions: None. Your meta tags are fully optimized for sharing on X.`
    },
    {
      id: "brand-font",
      name: "Brand Font Finder",
      isNew: true,
      description: "Find what font any website uses. See font families, usage percentages, fallback stacks, and live type specimens for any domain.",
      categories: ["design", "dev"],
      placeholderInput: "e.g. airbnb.com",
      mockResult: (domain) => `Found Font Families on ${domain}:

1. "Circular", -apple-system, sans-serif
   - Usage: 88% of body content
2. "SF Pro Text", -apple-system, sans-serif
   - Usage: 12%`
    },
    {
      id: "seo-aeo-report",
      name: "SEO / AEO Optimizer Report",
      isNew: true,
      description: "Score and optimize your website for AI search engines like Perplexity, ChatGPT Search, Gemini, and Claude. Get structured recommendations.",
      categories: ["seo", "ai"]
    },
    {
      id: "clone-website",
      name: "Clone Website Layout",
      isNew: true,
      description: "Instantly clone any landing page layout by URL. Converts UI elements and CSS tailwind classes to React components.",
      categories: ["dev", "design"]
    },
    {
      id: "product-demo",
      name: "AI Product Demo Generator",
      isNew: true,
      description: "Create interactive walk-through demos and step-by-step guides from any landing page URL or upload document.",
      categories: ["marketing", "ai"]
    },
    {
      id: "viral-x-trends",
      name: "Viral X (Twitter) Trends Finder",
      isNew: true,
      description: "Scan top-performing social templates and threads in real-time to identify high-engagement content strategies.",
      categories: ["marketing", "social"]
    },
    {
      id: "viral-instagram",
      name: "Instagram Viral Reels Finder",
      isNew: true,
      description: "Analyze trending Reels, audio structures, and video Hooks on Instagram to optimize marketing performance.",
      categories: ["marketing", "social"]
    },
    {
      id: "resume-review",
      name: "AI Resume Review",
      isNew: true,
      description: "Upload resume to check structural metrics, ATS compatibility, bullet point strengths, and industry recommendations.",
      categories: ["careers", "ai"]
    },
    {
      id: "linkedin-makeover",
      name: "LinkedIn Profile Makeover",
      isNew: true,
      description: "Analyze profile sections and rewrite headlines, about paragraphs, and skills summary to optimize recruitment SEO.",
      categories: ["careers", "ai"]
    },
    {
      id: "customgpt-gen",
      name: "CustomGPT Prompt Generator",
      isNew: true,
      description: "Input goals to instantly export tailored CustomGPT system instructions, context schemas, and configuration settings.",
      categories: ["dev", "ai"]
    },
    {
      id: "portfolio-gen",
      name: "Portfolio Site Creator",
      isNew: true,
      description: "Turn LinkedIn URL or resume profile into a modern portfolio website ready to host, with developer themes.",
      categories: ["careers", "dev", "ai"]
    }
  ]

  const startSimulation = (tool: Tool) => {
    if (!inputDomain.trim()) return
    setIsSimulating(true)
    setSimulationLog([])
    setSimulationResult("")

    const steps = [
      `[info] Initializing ${tool.name} request...`,
      `[info] Resolving domain details for "${inputDomain}"...`,
      `[info] Initiating Context.dev crawl protocols...`,
      `[info] Extracting semantic content elements...`,
      `[info] Structuring result payloads...`,
      `[success] Complete. Output ready.`
    ]

    steps.forEach((step, index) => {
      setTimeout(() => {
        setSimulationLog(prev => [...prev, step])
        if (index === steps.length - 1) {
          setIsSimulating(false)
          if (tool.mockResult) {
            setSimulationResult(tool.mockResult(inputDomain))
          }
        }
      }, (index + 1) * 600)
    })
  }

  return (
    <main className="min-h-screen bg-background text-foreground font-sans antialiased selection:bg-accent/30 selection:text-foreground">
      <Header />

      {/* Free Tools Section */}
      <section id="free-tools" className="pt-32 md:pt-36 pb-20 px-6 max-w-7xl mx-auto">
        <div className="text-center max-w-3xl mx-auto mb-10">
          <h1 className="text-4xl lg:text-5xl font-bold text-accent font-sans mb-3">
            Rethinksoft Tools
          </h1>
          <div className="inline-flex items-center gap-1.5 text-sm text-[#FF8C00] font-semibold mb-2">
            <span>Free Tools, zero friction</span>
          </div>
          <p className="text-sm text-foreground/75 leading-relaxed">
            Powered by the <span className="font-semibold text-foreground underline decoration-accent">Rethinksoft</span> API. No signup, No account, no rate limits, no strings attached. Its completely Free.
          </p>
        </div>

        {/* Category Filters */}
        <div className="flex flex-wrap gap-2 justify-center mb-10">
          {[
            { id: "all", label: "All Tools" },
            { id: "ai", label: "AI & Agents" },
            { id: "seo", label: "SEO & Web" },
            { id: "marketing", label: "Marketing & Social" },
            { id: "dev", label: "Dev & Design" },
            { id: "careers", label: "Careers" }
          ].map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveCategory(cat.id)}
              className={`px-5 py-2 rounded-full text-xs md:text-sm font-semibold transition-all duration-300 cursor-pointer ${
                activeCategory === cat.id
                  ? "bg-accent text-accent-foreground shadow-md shadow-accent/15"
                  : "bg-card border border-border/60 text-foreground/60 hover:text-foreground hover:bg-card/85"
              }`}
            >
              {cat.label}
            </button>
          ))}
        </div>

        {/* Grid of Free Tools */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-16">
          {freeTools
            .filter((tool) => {
              if (activeCategory === "all") return true
              if (activeCategory === "dev") return tool.categories.includes("dev") || tool.categories.includes("design")
              if (activeCategory === "marketing") return tool.categories.includes("marketing") || tool.categories.includes("social")
              return tool.categories.includes(activeCategory)
            })
            .map((tool, idx) => {
              const bgImages = [
                "/images/tech_dashboard.png",
                "/images/network_nodes.png",
                "/images/ai_workflow.png",
                "/images/seo_audit.png",
                "/images/coding_concept.png"
              ]
              const bgImage = bgImages[idx % bgImages.length]
              const displayCategory = categoryLabels[tool.categories[0]] || "DEVELOPER"

              return (
                <div 
                  key={tool.id} 
                  onClick={() => {
                    setSelectedTool(tool)
                    setInputDomain("")
                    setSimulationResult("")
                    setSimulationLog([])
                    setWaitlistSubmitted(false)
                    setWaitlistEmail("")
                  }}
                  className="relative overflow-hidden rounded-[1.25rem] aspect-[4/3] flex flex-col justify-between p-6 md:p-8 border border-white/10 group hover:border-[#FF8C00]/30 transition-all duration-300 shadow-xl cursor-pointer"
                >
                  {/* Background Image with Zoom on Hover */}
                  <div 
                    className="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-[1.04] pointer-events-none"
                    style={{ backgroundImage: `url(${bgImage})` }}
                  />
                  {/* Dark Tint Overlay */}
                  <div className="absolute inset-0 bg-gradient-to-t from-black/95 via-black/80 to-black/45 group-hover:from-black/100 group-hover:via-black/85 group-hover:to-black/50 transition-all duration-300 pointer-events-none" />
                  
                  {/* Card Header (Category Tag & New Tag) */}
                  <div className="relative z-10 flex justify-between items-start pointer-events-none">
                    <span className="text-[11px] font-bold tracking-widest text-white/60 uppercase transition-colors duration-300 group-hover:text-[#FF8C00]">
                      {displayCategory}
                    </span>
                    {tool.isNew && (
                      <span className="text-[9px] font-bold tracking-wider uppercase bg-[#FF8C00] text-white px-2 py-0.5 rounded-full shadow">
                        New
                      </span>
                    )}
                  </div>
                  
                  {/* Card Content (Title & Description) */}
                  <div className="relative z-10 mt-auto pointer-events-none">
                    <h3 className="text-xl md:text-2xl font-bold text-white mb-2 leading-tight transition-colors duration-300 group-hover:text-white">
                      {tool.name}
                    </h3>
                    <p className="text-xs md:text-sm text-white/70 leading-relaxed line-clamp-3 group-hover:text-white/95 transition-colors duration-300">
                      {tool.description}
                    </p>
                  </div>
                </div>
              )
            })}
        </div>

        {/* API CTA / Need at scale Section */}
        <div className="p-8 md:p-12 rounded-3xl border border-border bg-[linear-gradient(135deg,rgba(227,87,6,0.03)_0%,rgba(17,17,17,0.05)_100%)] relative overflow-hidden">
          <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_bottom_right,rgba(255,140,0,0.05),transparent_50%)] pointer-events-none" />
          <div className="grid lg:grid-cols-12 gap-8 items-center relative z-10">
            <div className="lg:col-span-8">
              <h3 className="text-2xl font-extrabold mb-4 font-sans">Need these at scale?</h3>
              <p className="text-foreground/70 leading-relaxed mb-2">
                Every tool above is powered by a Context.dev API endpoint. Get programmatic access with higher limits and batch processing.
              </p>
              <p className="text-sm font-medium text-[#FF8C00]">
                Ship an agent that actually knows things. Free tier, 10-minute integration, and the same API powering agents at Mintlify, daily.dev, and Propane. No credit card to start.
              </p>
            </div>
            <div className="lg:col-span-4 flex flex-col sm:flex-row lg:flex-col gap-3 justify-end">
              <a
                href="https://context.dev"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 rounded-full bg-accent text-accent-foreground px-6 py-3.5 text-sm font-bold hover:opacity-90 transition-opacity w-full text-center"
              >
                Get API Access
                <ExternalLink className="h-4 w-4" />
              </a>
              <a
                href="#contact"
                className="inline-flex items-center justify-center gap-2 rounded-full border border-border bg-card/60 text-foreground px-6 py-3.5 text-sm font-bold hover:bg-card transition-colors w-full text-center"
              >
                Book a call
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* OVERLAY DIALOGS */}
      {selectedTool && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          {selectedTool.mockResult ? (
            /* SIMULATOR MODAL */
            <div className="w-full max-w-3xl rounded-2xl border border-white/10 bg-[#0d0d0d] shadow-2xl overflow-hidden flex flex-col max-h-[85vh] animate-in fade-in zoom-in-95 duration-200">
              {/* Modal Header */}
              <div className="p-6 border-b border-white/10 flex items-center justify-between">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-[10px] font-bold px-2 py-0.5 rounded bg-[#FF8C00]/10 text-[#FF8C00]">Free Tool Simulator</span>
                    <span className="text-white/20">•</span>
                    <span className="text-xs text-white/50">{selectedTool.name}</span>
                  </div>
                  <h3 className="text-xl font-bold font-sans text-white">{selectedTool.name}</h3>
                </div>
                <button 
                  onClick={() => setSelectedTool(null)}
                  className="p-2 rounded-full border border-white/10 text-white/60 hover:bg-white/10 hover:text-white transition-colors cursor-pointer"
                >
                  ✕
                </button>
              </div>

              {/* Modal Body */}
              <div className="p-6 overflow-y-auto flex-1 space-y-6">
                <p className="text-sm text-white/70 leading-relaxed">
                  {selectedTool.description}
                </p>

                {/* URL/Domain input form */}
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Globe className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4.5 w-4.5 text-white/40" />
                    <input
                      type="text"
                      value={inputDomain}
                      onChange={(e) => setInputDomain(e.target.value)}
                      placeholder={selectedTool.placeholderInput || "e.g. example.com"}
                      className="w-full pl-11 pr-4 py-3 rounded-xl border border-white/10 bg-[#151515] text-sm text-white focus:outline-none focus:ring-1 focus:ring-[#FF8C00] placeholder:text-white/30"
                      onKeyDown={(e) => {
                        if (e.key === "Enter") startSimulation(selectedTool)
                      }}
                    />
                  </div>
                  <button
                    onClick={() => startSimulation(selectedTool)}
                    disabled={isSimulating || !inputDomain.trim()}
                    className="px-6 rounded-xl bg-accent text-accent-foreground text-sm font-semibold hover:opacity-95 disabled:opacity-50 transition-opacity flex items-center gap-2 whitespace-nowrap cursor-pointer"
                  >
                    {isSimulating ? (
                      <>
                        <RefreshCw className="h-4 w-4 animate-spin" />
                        Running...
                      </>
                    ) : (
                      <>
                        Run Tool
                        <ChevronRight className="h-4 w-4" />
                      </>
                    )}
                  </button>
                </div>

                {/* Terminal Logs & Outputs */}
                {(simulationLog.length > 0 || simulationResult) && (
                  <div className="rounded-xl border border-white/10 bg-[#050505] text-white p-4 font-mono text-xs md:text-sm shadow-inner overflow-hidden flex flex-col space-y-4">
                    {/* Console Header */}
                    <div className="flex items-center justify-between pb-2 border-b border-white/10 text-white/40 text-[10px] uppercase tracking-wider">
                      <span className="flex items-center gap-1.5">
                        <Terminal className="h-3.5 w-3.5" />
                        terminal console
                      </span>
                      <span>active session</span>
                    </div>

                    {/* Logs output */}
                    <div className="space-y-1 text-white/80">
                      {simulationLog.map((log, index) => (
                        <div key={index} className={log.includes("[success]") ? "text-emerald-400 font-semibold" : ""}>
                          {log}
                        </div>
                      ))}
                    </div>

                    {/* Final Result Container */}
                    {simulationResult && (
                      <div className="pt-4 border-t border-white/10 flex flex-col space-y-2">
                        <div className="flex justify-between items-center text-[10px] text-white/40 uppercase">
                          <span>Output Payload</span>
                          <span className="text-emerald-400 flex items-center gap-1">
                            <Check className="h-3 w-3" />
                            Validated
                          </span>
                        </div>
                        <pre className="p-3 bg-white/5 rounded border border-white/5 overflow-x-auto text-[11px] leading-relaxed max-h-[300px] text-white/90">
                          <code>{simulationResult}</code>
                        </pre>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Modal Footer */}
              <div className="p-6 border-t border-white/10 bg-black/40 flex items-center justify-between text-xs text-white/50">
                <span className="flex items-center gap-1">
                  <FileCode className="h-4 w-4" />
                  Raw payload output formats: Markdown & JSON
                </span>
                <button 
                  onClick={() => setSelectedTool(null)}
                  className="px-4 py-2 rounded-lg border border-white/10 text-white hover:bg-white/5 transition-colors cursor-pointer"
                >
                  Close
                </button>
              </div>
            </div>
          ) : (
            /* WAITLIST MODAL */
            <div className="w-full max-w-md rounded-2xl border border-white/10 bg-[#0d0d0d] shadow-2xl p-8 overflow-hidden flex flex-col relative animate-in fade-in zoom-in-95 duration-200">
              {/* Close Button */}
              <button 
                onClick={() => setSelectedTool(null)}
                className="absolute right-4 top-4 p-2 rounded-full border border-white/10 text-white/60 hover:bg-white/10 hover:text-white transition-colors cursor-pointer"
              >
                ✕
              </button>

              {!waitlistSubmitted ? (
                <div className="space-y-6">
                  <div className="space-y-2">
                    <span className="text-[10px] font-bold tracking-widest text-[#FF8C00] uppercase">COMING SOON</span>
                    <h3 className="text-2xl font-bold text-white leading-tight">{selectedTool.name}</h3>
                    <p className="text-sm text-neutral-400 leading-relaxed">
                      {selectedTool.description}
                    </p>
                  </div>

                  <div className="space-y-4 pt-2">
                    <p className="text-xs text-neutral-400">
                      This developer utility is running in private beta. Enter your email below to join the waitlist and get notified when it goes public.
                    </p>
                    
                    <form onSubmit={(e) => {
                      e.preventDefault()
                      if (!waitlistEmail.trim()) return
                      setWaitlistLoading(true)
                      setTimeout(() => {
                        setWaitlistLoading(false)
                        setWaitlistSubmitted(true)
                      }, 800)
                    }} className="flex flex-col gap-2">
                      <input
                        type="email"
                        required
                        value={waitlistEmail}
                        onChange={(e) => setWaitlistEmail(e.target.value)}
                        placeholder="name@company.com"
                        className="w-full px-4 py-3 rounded-xl border border-white/10 bg-[#151515] text-sm text-white focus:outline-none focus:ring-1 focus:ring-[#FF8C00] placeholder:text-neutral-500"
                      />
                      <button
                        type="submit"
                        disabled={waitlistLoading}
                        className="w-full py-3 rounded-xl bg-accent text-accent-foreground text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
                      >
                        {waitlistLoading ? "Joining..." : "Join Waitlist"}
                        <ArrowUpRight className="h-4 w-4" />
                      </button>
                    </form>
                  </div>
                </div>
              ) : (
                <div className="py-8 text-center space-y-4">
                  <div className="h-12 w-12 rounded-full bg-emerald-500/10 text-emerald-400 flex items-center justify-center mx-auto border border-emerald-500/20">
                    <Check className="h-6 w-6" />
                  </div>
                  <div className="space-y-2">
                    <h3 className="text-xl font-bold text-white">You're on the list!</h3>
                    <p className="text-sm text-neutral-400 max-w-xs mx-auto">
                      Thanks for your interest. We'll email you at <span className="text-white font-medium">{waitlistEmail}</span> as soon as access opens up.
                    </p>
                  </div>
                  <button 
                    onClick={() => {
                      setSelectedTool(null)
                      setWaitlistSubmitted(false)
                      setWaitlistEmail("")
                    }}
                    className="mt-6 px-6 py-2 rounded-xl border border-white/10 text-xs text-neutral-400 hover:text-white hover:bg-white/5 transition-colors cursor-pointer"
                  >
                    Close Window
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      <Footer />
    </main>
  )
}
