/**
 * WorkflowDiagram — Interactive chatbot conversation flow diagram
 * Design: Warm Showroom — forest green nodes, terracotta accents, cream background
 */
import { useState } from "react";
import { motion } from "framer-motion";
import {
  MessageCircle,
  ShoppingBag,
  MapPin,
  Package,
  Shield,
  Users,
  Bot,
  ArrowRight,
  Sparkles,
} from "lucide-react";

interface FlowNode {
  id: string;
  label: string;
  description: string;
  icon: React.ReactNode;
  color: string;
  children?: string[];
}

const FLOW_NODES: FlowNode[] = [
  {
    id: "entry",
    label: "User Visits Website",
    description: "A visitor lands on homelegance.com. The chatbot widget appears in the bottom-right corner after a short delay, with a gentle greeting animation.",
    icon: <MessageCircle className="w-5 h-5" />,
    color: "#14532D",
    children: ["greeting"],
  },
  {
    id: "greeting",
    label: "AI Greeting & Intent Detection",
    description: "The chatbot sends a warm welcome message and presents quick-action buttons. Natural Language Processing (NLP) analyzes the user's first message to detect intent.",
    icon: <Bot className="w-5 h-5" />,
    color: "#14532D",
    children: ["products", "dealer", "order", "warranty", "sales"],
  },
  {
    id: "products",
    label: "Product Discovery",
    description: "Guides users through furniture categories (Bedroom, Dining, Seating, etc.), shows best sellers, and helps filter by collection, style, or price range. Can display product images and specs inline.",
    icon: <ShoppingBag className="w-5 h-5" />,
    color: "#C2410C",
  },
  {
    id: "dealer",
    label: "Dealer Locator",
    description: "Asks for zip code or city, then queries the dealer database to find authorized Homelegance retailers nearby. Shows results with distance, contact info, and directions link.",
    icon: <MapPin className="w-5 h-5" />,
    color: "#C2410C",
  },
  {
    id: "order",
    label: "Order Status Tracking",
    description: "Authenticates the dealer/retailer via order number or account email, then retrieves real-time order status from the fulfillment system. Shows shipping tracking when available.",
    icon: <Package className="w-5 h-5" />,
    color: "#C2410C",
  },
  {
    id: "warranty",
    label: "Parts & Warranty",
    description: "Walks users through the warranty claim process: collects product info, purchase date, issue description, and photos. Creates a support ticket automatically.",
    icon: <Shield className="w-5 h-5" />,
    color: "#C2410C",
  },
  {
    id: "sales",
    label: "Live Agent Handoff",
    description: "When the chatbot detects complex queries or the user requests human help, it seamlessly transfers the conversation to a live sales representative with full context.",
    icon: <Users className="w-5 h-5" />,
    color: "#C2410C",
  },
];

export default function WorkflowDiagram() {
  const [activeNode, setActiveNode] = useState<string>("entry");
  const active = FLOW_NODES.find((n) => n.id === activeNode);

  return (
    <div className="w-full">
      {/* Flow visualization */}
      <div className="relative">
        {/* Entry node */}
        <div className="flex justify-center mb-6">
          <FlowNodeCard
            node={FLOW_NODES[0]}
            isActive={activeNode === "entry"}
            onClick={() => setActiveNode("entry")}
          />
        </div>

        {/* Connector line down */}
        <div className="flex justify-center mb-2">
          <div className="w-0.5 h-8" style={{ background: "#14532D" }} />
        </div>

        {/* AI Processing node */}
        <div className="flex justify-center mb-6">
          <FlowNodeCard
            node={FLOW_NODES[1]}
            isActive={activeNode === "greeting"}
            onClick={() => setActiveNode("greeting")}
          />
        </div>

        {/* Branching connector */}
        <div className="flex justify-center mb-2">
          <div className="relative w-full max-w-3xl h-8">
            <div className="absolute left-1/2 top-0 w-0.5 h-4 -translate-x-1/2" style={{ background: "#14532D" }} />
            <div className="absolute top-4 left-[10%] right-[10%] h-0.5" style={{ background: "#14532D" }} />
            {[10, 28, 50, 72, 90].map((pos) => (
              <div
                key={pos}
                className="absolute top-4 w-0.5 h-4"
                style={{ left: `${pos}%`, transform: "translateX(-50%)", background: "#14532D" }}
              />
            ))}
          </div>
        </div>

        {/* Branch nodes */}
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
          {FLOW_NODES.slice(2).map((node) => (
            <FlowNodeCard
              key={node.id}
              node={node}
              isActive={activeNode === node.id}
              onClick={() => setActiveNode(node.id)}
              compact
            />
          ))}
        </div>
      </div>

      {/* Detail panel */}
      <motion.div
        key={activeNode}
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="mt-8 p-6 rounded-xl"
        style={{
          background: "#fff",
          boxShadow: "0 4px 20px rgba(120, 113, 108, 0.1)",
          border: "1px solid #e7e0d5",
        }}
      >
        <div className="flex items-start gap-4">
          <div
            className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0"
            style={{ background: active?.color + "15", color: active?.color }}
          >
            {active?.icon}
          </div>
          <div>
            <h4
              className="text-lg font-semibold mb-2"
              style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
            >
              {active?.label}
            </h4>
            <p className="text-sm leading-relaxed" style={{ color: "#78716C", fontFamily: "'Source Sans 3', sans-serif" }}>
              {active?.description}
            </p>
            {active?.children && (
              <div className="flex flex-wrap gap-2 mt-3">
                <span className="text-xs font-medium" style={{ color: "#a8a29e" }}>
                  Leads to:
                </span>
                {active.children.map((childId) => {
                  const child = FLOW_NODES.find((n) => n.id === childId);
                  return (
                    <button
                      key={childId}
                      onClick={() => setActiveNode(childId)}
                      className="flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium transition-colors"
                      style={{
                        background: "rgba(194, 65, 12, 0.08)",
                        color: "#C2410C",
                      }}
                    >
                      {child?.label}
                      <ArrowRight className="w-3 h-3" />
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </motion.div>
    </div>
  );
}

function FlowNodeCard({
  node,
  isActive,
  onClick,
  compact,
}: {
  node: FlowNode;
  isActive: boolean;
  onClick: () => void;
  compact?: boolean;
}) {
  return (
    <motion.button
      whileHover={{ scale: 1.03, y: -2 }}
      whileTap={{ scale: 0.98 }}
      onClick={onClick}
      className={`relative rounded-xl transition-all ${compact ? "p-3 w-full" : "px-6 py-4"}`}
      style={{
        background: isActive ? node.color : "#fff",
        color: isActive ? "#fff" : node.color,
        boxShadow: isActive
          ? `0 8px 24px ${node.color}30`
          : "0 2px 8px rgba(120, 113, 108, 0.1)",
        border: `1.5px solid ${isActive ? node.color : "#e7e0d5"}`,
      }}
    >
      <div className={`flex items-center ${compact ? "flex-col gap-2" : "gap-3"}`}>
        <div
          className={`${compact ? "w-9 h-9" : "w-10 h-10"} rounded-lg flex items-center justify-center`}
          style={{
            background: isActive ? "rgba(255,255,255,0.2)" : node.color + "12",
          }}
        >
          {node.icon}
        </div>
        <span
          className={`font-semibold ${compact ? "text-xs text-center leading-tight" : "text-sm"}`}
          style={{ fontFamily: "'Source Sans 3', sans-serif" }}
        >
          {node.label}
        </span>
      </div>
      {isActive && (
        <motion.div
          layoutId="activeIndicator"
          className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 rounded-full"
          style={{ background: "#C2410C" }}
        />
      )}
    </motion.button>
  );
}
