const { useState, useEffect, useRef } = React;

const SERVICES = [
  {
    id: "engineering",
    title: "Engineering Optimization",
    icon: "⚙️",
    description: "Map and optimize manufacturing processes with AI-guided discovery",
    functional: true,
    route: "engineering",
    color: "#3B82F6",
    chatPreview: [
      { role: "user", text: "We have a CNC machining line with 6 stations" },
      { role: "assistant", text: "I'll help map your process flow. What's the cycle time at your first station?" },
      { role: "user", text: "About 4.5 minutes per part" }
    ]
  },
  {
    id: "sourcing",
    title: "Global Supplier Search",
    icon: "🔍",
    description: "Find suppliers worldwide, build RFQ shortlists, compare quotes, and track sourcing",
    functional: true,
    route: "sourcing",
    color: "#8B5CF6",
    chatPreview: [
      { role: "user", text: "I need quotes for 316L stainless steel bar stock" },
      { role: "assistant", text: "I'll help source that. What diameter range and quantity are you looking at?" },
      { role: "user", text: "1 inch diameter, 500 feet monthly" }
    ]
  },
  {
    id: "supply-chain",
    title: "Supply Chain Optimization",
    icon: "🔗",
    description: "End-to-end visibility and optimization of your supply network",
    functional: false,
    color: "#059669",
    chatPreview: [
      { role: "user", text: "Our lead times from Asia have increased 40%" },
      { role: "assistant", text: "Let me analyze your supply network for reshoring opportunities and alternative routes..." }
    ]
  },
  {
    id: "lean",
    title: "LEAN Process Redesign",
    icon: "📐",
    description: "AI-driven waste elimination and continuous improvement",
    functional: false,
    color: "#D97706",
    chatPreview: [
      { role: "user", text: "We're seeing high WIP between stations 3 and 4" },
      { role: "assistant", text: "That suggests a bottleneck. Let me analyze your takt time versus cycle times..." }
    ]
  },
  {
    id: "automation",
    title: "Smart Factory Automation",
    icon: "🤖",
    description: "Intelligent automation planning and ROI analysis",
    functional: false,
    color: "#DC2626",
    chatPreview: [
      { role: "user", text: "Which stations should we automate first?" },
      { role: "assistant", text: "Based on your cycle times and defect rates, station 3 shows the highest ROI for automation..." }
    ]
  },
  {
    id: "consulting",
    title: "Technical Consulting",
    icon: "💡",
    description: "Expert guidance on manufacturing technology decisions",
    functional: false,
    color: "#0891B2",
    chatPreview: [
      { role: "user", text: "Should we invest in additive manufacturing?" },
      { role: "assistant", text: "For your part geometries and volumes, let me compare AM vs traditional machining costs..." }
    ]
  }
];

function MiniChatWindow({ messages, color }) {
  return (
    <div className="mini-chat">
      <div className="mini-chat-header">
        <span className="mini-chat-dot" style={{ background: "#EF4444" }} />
        <span className="mini-chat-dot" style={{ background: "#F59E0B" }} />
        <span className="mini-chat-dot" style={{ background: "#22C55E" }} />
        <span style={{ fontSize: 8, color: "#94A3B8", marginLeft: 4, fontWeight: 600 }}>AI Agent</span>
      </div>
      <div className="mini-chat-body">
        {messages.map((msg, i) => (
          <div
            key={i}
            className={`mini-chat-bubble ${msg.role}`}
            style={msg.role === "user" ? { background: color || "#3B82F6" } : {}}
          >
            {msg.text}
          </div>
        ))}
        <div className="mini-chat-typing">
          <span className="mini-chat-typing-dot" style={{ animationDelay: "0s" }} />
          <span className="mini-chat-typing-dot" style={{ animationDelay: "0.15s" }} />
          <span className="mini-chat-typing-dot" style={{ animationDelay: "0.3s" }} />
        </div>
      </div>
    </div>
  );
}

function ServiceCard({ service, onNavigate }) {
  const handleClick = () => {
    if (service.functional && service.route) {
      onNavigate(service.route);
    }
  };

  return (
    <div
      className={`service-card ${service.functional ? "functional" : ""}`}
      onClick={handleClick}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 22, background: `${service.color}15`, border: `1.5px solid ${service.color}30`
        }}>
          {service.icon}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: "#1E293B" }}>{service.title}</div>
          <div style={{ fontSize: 12, color: "#64748B", lineHeight: 1.4 }}>{service.description}</div>
        </div>
      </div>

      <MiniChatWindow messages={service.chatPreview} color={service.color} />

      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        {service.functional ? (
          <button
            style={{
              background: service.color, color: "white", border: "none", borderRadius: 8,
              padding: "8px 20px", fontSize: 13, fontWeight: 600, cursor: "pointer",
              transition: "opacity 0.15s", display: "flex", alignItems: "center", gap: 6
            }}
            onMouseOver={e => e.currentTarget.style.opacity = "0.85"}
            onMouseOut={e => e.currentTarget.style.opacity = "1"}
          >
            Launch <span style={{ fontSize: 14 }}>→</span>
          </button>
        ) : (
          <span style={{
            background: "#F1F5F9", color: "#94A3B8", borderRadius: 8,
            padding: "8px 16px", fontSize: 12, fontWeight: 600
          }}>
            Coming Soon
          </span>
        )}
      </div>
    </div>
  );
}

function LandingPage({ onNavigate, user, onLogout }) {
  return (
    <div className="landing-container">
      {/* Header */}
      <div className="landing-header" style={{ display: "flex", alignItems: "center" }}>
        <img src="neurachain.png" alt="NeuraChain" style={{ height: 36, borderRadius: 6 }} />
        <span style={{ fontSize: 18, fontWeight: 800, color: "white", letterSpacing: "-0.02em" }}>
          NeuraChain
        </span>
        <span style={{ fontSize: 13, color: "#94A3B8", fontWeight: 500 }}>
          AI Manufacturing Solutions
        </span>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12 }}>
          {user && (
            <>
              <span style={{ fontSize: 13, color: "#94A3B8" }}>
                {user.name} <span style={{
                  background: "#334155", padding: "2px 8px", borderRadius: 4,
                  fontSize: 11, color: "#3B82F6", fontWeight: 600, marginLeft: 4
                }}>{user.role}</span>
              </span>
              <button
                onClick={onLogout}
                style={{
                  background: "#334155", border: "1px solid #475569", borderRadius: 8,
                  padding: "6px 14px", color: "#CBD5E1", fontSize: 12, fontWeight: 600,
                  cursor: "pointer", transition: "background 0.15s"
                }}
                onMouseOver={e => e.currentTarget.style.background = "#475569"}
                onMouseOut={e => e.currentTarget.style.background = "#334155"}
              >
                Logout
              </button>
            </>
          )}
        </div>
      </div>

      {/* Hero */}
      <div className="landing-hero">
        <div style={{
          display: "inline-block", background: "#EFF6FF", borderRadius: 20,
          padding: "6px 16px", fontSize: 12, fontWeight: 600, color: "#3B82F6",
          marginBottom: 20, border: "1px solid #BFDBFE"
        }}>
          Powered by AI Agents
        </div>
        <h1 style={{
          fontSize: 42, fontWeight: 900, color: "#0F172A", lineHeight: 1.15,
          marginBottom: 16, letterSpacing: "-0.03em"
        }}>
          AI-Powered Manufacturing<br />Reshoring
        </h1>
        <p style={{
          fontSize: 18, color: "#64748B", maxWidth: 560, margin: "0 auto 12px",
          lineHeight: 1.6
        }}>
          Intelligent agents that optimize every stage of your manufacturing operations — from process mapping to strategic sourcing.
        </p>
        <p style={{
          fontSize: 14, color: "#94A3B8", maxWidth: 480, margin: "0 auto"
        }}>
          Each tool features a conversational AI interface. Just describe your needs and our agents will guide you through the analysis.
        </p>
      </div>

      {/* Service Grid */}
      <div className="service-grid">
        {SERVICES.map(service => (
          <ServiceCard key={service.id} service={service} onNavigate={onNavigate} />
        ))}
      </div>

      {/* Footer */}
      <div style={{
        textAlign: "center", padding: "32px 24px 48px", fontSize: 12, color: "#94A3B8"
      }}>
        NeuraChain Solutions — AI-Powered Manufacturing Intelligence
      </div>
    </div>
  );
}

window.LandingPage = LandingPage;
