import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { BrowserRouter as Router, Routes, Route, Link, useNavigate } from 'react-router-dom'
import './App.css'
import { Button } from './components/ui/button'
import BlogPage from './blog/BlogPage'
import BlogPost from './blog/BlogPost'
import mushroomImage from './assets/mushroom.png'
import RegistrationTerminal from './components/RegistrationTerminal'

function App() {
  const [showTerminal, setShowTerminal] = useState(false)
  const [networkNodes, setNetworkNodes] = useState([])
  const [showConfirmation, setShowConfirmation] = useState(false)

  // Terminal typing effect
  const [terminalText, setTerminalText] = useState('')

  const terminalCommands = [
    '> connecting to mycelium network...',
    '> establishing secure p2p connection...',
    '> welcome to the digital frontier',
  ]

  useEffect(() => {
    let typingTimer

    if (showTerminal) {
      // Reset terminal text when opening
      setTerminalText('')

      let index = 0
      let charIndex = 0
      let isDeleting = false

      const type = () => {
        if (index < terminalCommands.length) {
          if (!isDeleting && charIndex <= terminalCommands[index].length) {
            setTerminalText(terminalCommands[index].substring(0, charIndex))
            charIndex++
            typingTimer = setTimeout(type, 20)
          } else if (isDeleting && charIndex >= 0) {
            setTerminalText(terminalCommands[index].substring(0, charIndex))
            charIndex--
            typingTimer = setTimeout(type, 10)
          } else {
            isDeleting = !isDeleting
            if (!isDeleting) {
              index++
              typingTimer = setTimeout(type, 500)
            } else {
              typingTimer = setTimeout(type, 300)
            }
          }
        } else {
          // After the last prompt, show the confirmation dialog
          setTerminalText('> mycelial network patterns')
          setTimeout(() => {
            setShowTerminal(false)
            setShowConfirmation(true)
          }, 1000)
        }
      }

      // Start the typing effect
      typingTimer = setTimeout(type, 30)

      // Clean up the timer when component unmounts or showTerminal changes
      return () => clearTimeout(typingTimer)
    } else {
      // Reset terminal state when closing
      setTerminalText('')
    }
  }, [showTerminal])

  // Generate network nodes
  useEffect(() => {
    const generateNodes = () => {
      const nodes = []
      const nodeCount = 15

      for (let i = 0; i < nodeCount; i++) {
        nodes.push({
          id: i,
          x: Math.random() * 100,
          y: Math.random() * 100,
          size: Math.random() * 20 + 10,
          pulseSpeed: Math.random() * 2 + 1
        })
      }

      setNetworkNodes(nodes)
    }

    generateNodes()
  }, [])

  return (
    <Router>
      <div className="app">
        <Routes>
          <Route path="/blog/:id" element={<BlogPost />} />
          <Route path="/blog" element={<BlogPage />} />
          <Route path="/register" element={<RegistrationPage />} />
          <Route path="/" element={<HomePage
            showTerminal={showTerminal}
            setShowTerminal={setShowTerminal}
            terminalText={terminalText}
            networkNodes={networkNodes}
            showConfirmation={showConfirmation}
            setShowConfirmation={setShowConfirmation}
          />} />
        </Routes>
      </div>
    </Router>
  )
}

function HomePage({ showTerminal, setShowTerminal, terminalText, networkNodes, showConfirmation, setShowConfirmation }) {
  const navigate = useNavigate();

  const handleConfirmRegistration = () => {
    setShowConfirmation(false);
    navigate('/register');
  };

  const handleCancelRegistration = () => {
    setShowConfirmation(false);
  };

  return (
    <div className="app">
      {/* Network Nodes Background */}
      <div className="network-nodes">
        {networkNodes.map(node => (
          <motion.div
            key={node.id}
            className="network-node"
            style={{
              left: `${node.x}%`,
              top: `${node.y}%`,
              width: `${node.size}px`,
              height: `${node.size}px`
            }}
            animate={{
              scale: [1, 1.2, 1],
              opacity: [0.3, 0.7, 0.3]
            }}
            transition={{
              duration: node.pulseSpeed,
              repeat: Infinity,
              ease: "easeInOut"
            }}
          />
        ))}
      </div>

      {/* Terminal Overlay */}
      {showTerminal && (
        <div className="terminal-overlay">
          <div className="terminal">
            <div className="terminal-header">
              <div className="terminal-title">MYCELIUM NETWORK TERMINAL</div>
              <button className="terminal-close" onClick={() => setShowTerminal(false)}>
                Close Terminal
              </button>
            </div>
            <div className="terminal-body">
              <div id="terminal-content">{terminalText}<span className="terminal-cursor"></span></div>
            </div>
          </div>
        </div>
      )}

      {/* Registration Confirmation Dialog */}
      {showConfirmation && (
        <div className="terminal-overlay">
          <div className="terminal">
            <div className="terminal-header">
              <div className="terminal-title">MYCELIUM NETWORK CONFIRMATION</div>
              <button className="terminal-close" onClick={handleCancelRegistration}>
                Close Terminal
              </button>
            </div>
            <div className="terminal-body">
              <div className="font-mono text-green-400 mb-6">
                <p>{'>'} Do you want to register for the Mycelium Network?</p>
                <p className="mt-2">{'>'} Registration is required to access the network.</p>
              </div>
              <div className="flex space-x-4 mt-4">
                <Button
                  onClick={handleConfirmRegistration}
                  className="bg-transparent border-2 border-cyan-400 text-cyan-400 hover:bg-cyan-400 hover:text-black font-bold px-4 py-2 transition-all duration-300 hover:shadow-lg hover:shadow-cyan-400/50"
                >
                  {'>'} Yes, Register
                </Button>
                <Button
                  onClick={handleCancelRegistration}
                  className="bg-transparent border-2 border-gray-400 text-gray-400 hover:bg-gray-400 hover:text-black font-bold px-4 py-2 transition-all duration-300 hover:shadow-lg hover:shadow-gray-400/50"
                >
                  {'>'} Cancel
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Hero Section */}
      <section className="hero-section">
        <div className="container mx-auto px-6 py-24 text-center">
          <motion.div
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 1 }}
            className="logo-container mb-8"
          >
            <div className="logo-box"></div>
          </motion.div>

          <div className="relative flex justify-center items-center">
            <img
              src={mushroomImage}
              alt="Mushroom"
              className="absolute top-0 left-1/2 transform -translate-x-1/2 -translate-y-full w-100 h-100 object-contain z-10"
            />
            <motion.h1
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 1, delay: 0.2 }}
              className="text-6xl md:text-7xl font-bold mb-4 relative z-0 mt-2"
              style={{ fontFamily: 'monospace' }}
            >
              MYCELIUM <span className="text-cyan-400">SOCIETY</span>
            </motion.h1>
          </div>

          <motion.p
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 1, delay: 0.4 }}
            className="text-xl md:text-2xl mb-8 text-gray-300 max-w-2xl mx-auto"
          >
            The Digital Frontier. A Virtual Nation for the Digital Age.
          </motion.p>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 1, delay: 0.6 }}
          >
            <Button
              className="bg-transparent border-2 border-cyan-400 text-cyan-400 hover:bg-cyan-400 hover:text-black font-bold px-8 py-4 text-lg transition-all duration-300 hover:shadow-lg hover:shadow-cyan-400/50"
              onClick={() => setShowTerminal(true)}
            >
              <span className="mr-2">{'>'}</span> ENTER THE NETWORK
            </Button>
          </motion.div>

          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 1, delay: 1 }}
            className="scroll-indicator mt-16"
          >
            <div className="scroll-arrow"></div>
          </motion.div>
        </div>
      </section>

      {/* Manifesto Section */}
      <section className="manifesto-section py-24 relative">
        <div className="container mx-auto px-6">
          <motion.div
            initial={{ opacity: 0, y: 50 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 1 }}
            viewport={{ once: true }}
            className="max-w-4xl mx-auto text-center"
          >
            <h2 className="text-5xl font-bold mb-8 text-cyan-400" style={{ fontFamily: 'monospace' }}>
              THE MANIFESTO
            </h2>
            <div className="space-y-8 text-lg leading-relaxed">
              <p className="text-gray-300">
                We are not just a network — we are a <strong className="text-white">virtual nation for the digital age</strong>,
                where each member operates as their own sovereign entity within a recognized legal framework.
              </p>
              <p className="text-gray-300">
                By combining resilient peer-to-peer infrastructure with cooperative governance,
                we enable individuals to thrive as entrepreneurs, creators, and collaborators
                while strengthening the global digital economy.
              </p>
              <p className="text-cyan-400 text-xl font-bold">
                Building the future together, legally and transparently.
              </p>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Core Pillars Section */}
      <section className="core-pillars-section py-24 bg-gray-900">
        <div className="container mx-auto px-6">
          <motion.h2
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
            className="text-5xl font-bold mb-16 text-center text-cyan-400"
            style={{ fontFamily: 'monospace' }}
          >
            CORE PILLARS
          </motion.h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.2 }}
              viewport={{ once: true }}
              className="pillar-card bg-black p-8 rounded-lg"
            >
              <div className="pillar-icon text-cyan-400 text-4xl mb-6">
                <i className="fas fa-network-wired"></i>
              </div>
              <h3 className="text-2xl font-bold mb-4 text-white">TECHNOLOGY</h3>
              <p className="text-gray-300">
                Decentralized P2P cloud infrastructure with end-to-end encryption, AI integration, unbreakable network and distributed trust layer.
              </p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.4 }}
              viewport={{ once: true }}
              className="pillar-card bg-black p-8 rounded-lg"
            >
              <div className="pillar-icon text-cyan-400 text-4xl mb-6">
                <i className="fas fa-balance-scale"></i>
              </div>
              <h3 className="text-2xl font-bold mb-4 text-white">GOVERNANCE</h3>
              <p className="text-gray-300">
                Every member operates as their own legal entity with a flat 5% tax rate in our digital free zone. With integrated legal dispute resolution also for AI agents.
              </p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.6 }}
              viewport={{ once: true }}
              className="pillar-card bg-black p-8 rounded-lg"
            >
              <div className="pillar-icon text-cyan-400 text-4xl mb-6">
                <i className="fas fa-chart-line"></i>
              </div>
              <h3 className="text-2xl font-bold mb-4 text-white">ECONOMY</h3>
              <p className="text-gray-300">
                Sovereign web infrastructure with unbreakable websites, Personal AI Agents, Web3 integration, and marketplace for frictionless global trade.
              </p>
            </motion.div>
          </div>
        </div>
      </section>

      {/* Blog Section Preview */}
      <section className="blog-preview-section py-24">
        <div className="container mx-auto px-6">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
            className="text-center mb-12"
          >
            <h2 className="text-4xl font-bold mb-4 text-cyan-400" style={{ fontFamily: 'monospace' }}>
              THE FRONTIER JOURNAL
            </h2>
            <p className="text-xl text-gray-300">
              Insights and updates from our digital nation
            </p>
          </motion.div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.2 }}
              viewport={{ once: true }}
              className="blog-card bg-gray-900 border border-cyan-400/30 rounded-lg overflow-hidden"
            >
              <div className="p-6">
                <div className="text-sm text-gray-400 mb-2">2025-09-24 • Mycelium Society</div>
                <h3 className="text-2xl font-bold mb-2 text-white">Welcome to the Digital Frontier</h3>
                <p className="text-gray-300 mb-4">
                  An introduction to the Mycelium Society and our vision for a sovereign digital nation.
                </p>
                <Link to="/blog/welcome-to-the-frontier" className="text-cyan-400 hover:underline">
                  Read more →
                </Link>
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.4 }}
              viewport={{ once: true }}
              className="blog-card bg-gray-900 border border-cyan-400/30 rounded-lg overflow-hidden"
            >
              <div className="p-6">
                <div className="text-sm text-gray-400 mb-2">2025-09-23 • Tech Team</div>
                <h3 className="text-2xl font-bold mb-2 text-white">The Technology Behind Mycelium Society</h3>
                <p className="text-gray-300 mb-4">
                  An exploration of the decentralized infrastructure powering our digital nation.
                </p>
                <Link to="/blog/technology-behind-mycelium" className="text-cyan-400 hover:underline">
                  Read more →
                </Link>
              </div>
            </motion.div>
          </div>

          <div className="text-center">
            <Link to="/blog">
              <Button className="bg-transparent border-2 border-cyan-400 text-cyan-400 hover:bg-cyan-400 hover:text-black font-bold px-8 py-3 transition-all duration-300 hover:shadow-lg hover:shadow-cyan-400/50">
                VIEW ALL POSTS
              </Button>
            </Link>
          </div>
        </div>
      </section>

      {/* Call to Action */}
      <section className="cta-section py-24 bg-black">
        <div className="container mx-auto px-6">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 1 }}
            viewport={{ once: true }}
            className="text-center"
          >
            <h2 className="text-4xl font-bold mb-8 text-white" style={{ fontFamily: 'monospace' }}>
              READY TO JOIN THE <span className="text-cyan-400">FRONTIER</span>?
            </h2>
            <p className="text-xl text-gray-300 mb-8 max-w-2xl mx-auto">
              Join visionary entrepreneurs and creators building the next generation of digital infrastructure.
              Become a founding member of our sovereign digital nation.
            </p>
            <Link to="/register">
              <Button
                className="bg-transparent border-2 border-cyan-400 text-cyan-400 hover:bg-cyan-400 hover:text-black font-bold px-12 py-4 text-lg transition-all duration-300 hover:shadow-lg hover:shadow-cyan-400/50"
              >
                <i className="fas fa-bolt mr-2"></i> REQUEST ACCESS
              </Button>
            </Link>
          </motion.div>
        </div>
      </section>

      {/* Footer */}
      <footer className="py-8 px-6 bg-gray-900 border-t border-cyan-400/30">
        <div className="max-w-6xl mx-auto text-center">
          <div className="mb-4">
            <Link to="/" className="text-gray-400 hover:text-cyan-400 mx-3">Home</Link>
            <Link to="/blog" className="text-gray-400 hover:text-cyan-400 mx-3">Blog</Link>
          </div>
          <p className="text-gray-500 font-mono">
            © 2025 Mycelium Society. The Digital Frontier.
          </p>
        </div>
      </footer>
    </div>
  )
}

function RegistrationPage() {
  const [showRegistrationTerminal, setShowRegistrationTerminal] = useState(true)
  const [registrationSuccess, setRegistrationSuccess] = useState(false)
  const navigate = useNavigate()

  const handleRegister = (data) => {
    // In a real application, you would send this data to your backend
    // For demonstration purposes, we'll just simulate a successful registration
    console.log('Registration data:', data)
    setRegistrationSuccess(true)

    // In a real app, you might redirect the user or update the app state
    // For now, we'll just keep the terminal open to show the success message
  }

  const handleCloseTerminal = () => {
    setShowRegistrationTerminal(false)
    navigate('/')
  }

  return (
    <div className="app">
      <RegistrationTerminal
        showTerminal={showRegistrationTerminal}
        setShowTerminal={handleCloseTerminal}
        onRegister={handleRegister}
      />

      {/* Additional content could go here if needed */}
      {registrationSuccess && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
          <div className="bg-gray-900 border border-cyan-400/30 rounded-lg p-8 max-w-md w-full mx-4">
            <h2 className="text-2xl font-bold text-cyan-400 mb-4 font-mono">Registration Successful</h2>
            <p className="text-gray-300 mb-6 font-mono">
              Welcome to the Mycelium Network. Your digital identity has been created.
            </p>
            <Button
              onClick={() => {
                setRegistrationSuccess(false)
                setShowRegistrationTerminal(false)
                navigate('/')
              }}
              className="bg-transparent border-2 border-cyan-400 text-cyan-400 hover:bg-cyan-400 hover:text-black font-bold px-4 py-2 transition-all duration-300 hover:shadow-lg hover:shadow-cyan-400/50 w-full font-mono"
            >
              {'>'} Continue to Network
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}

export default App
