"use client";

import { useState, useRef } from "react";
import { usePathname } from "next/navigation";
import { Bot, X, Send } from "lucide-react";
import Fuse from "fuse.js";
import "./chatbot.css";
import { intents } from "./intents";

type Intent = {
  tag: string;
  patterns: string[];
  answer: string;
  suggestions?: string[]; // follow-up quick replies shown after this answer
};

const fuse = new Fuse(intents, {
  keys: ["patterns"],
  includeScore: true,
  threshold: 0.4, // lower = stricter match. 0.4 balances typo tolerance vs false positives
  minMatchCharLength: 2,
});

const FALLBACK =
  "I'm not 100% sure about that 🤔 — could you rephrase, or pick one of these?";

function linkify(text: string) {
  const urlRegex = /(https?:\/\/[^\s)]+)/g;
  return text.split(urlRegex).map((part, i) =>
    part.match(urlRegex) ? (
      <a key={i} href={part} target="_blank" rel="noopener noreferrer" className="chat-link">
        {part}
      </a>
    ) : (
      <span key={i}>{part}</span>
    )
  );
}

// short, low-information messages that should lean on conversation memory
const FOLLOW_UP_WORDS = ["yes", "more", "tell me more", "details", "ok", "sure", "yeah"];

export default function AIChatbot() {
  const pathname = usePathname();
  const isAiDriven = pathname?.startsWith("/ai-driven");

  const [open, setOpen] = useState(false);
  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState<{ role: "bot" | "user"; text: string; suggestions?: string[] }[]>([
        {
        role: "bot",
        text: "Hi 👋 I'm Digi AI. How can I help you today?",
        suggestions: ["What services do you offer?", "Website cost?", "Contact us"],
        },
    ]);

  const lastTagRef = useRef<string | null>(null);
  function normalize(text: string) {
    return text
        .toLowerCase()
        .replace(/[^\w\s]/g, "")
        .replace(/\s+/g, " ")
        .trim();
  }
  function resolveIntent(text: string): Intent | null {
    const input = normalize(text);

    // Follow-up memory
    if (FOLLOW_UP_WORDS.includes(input) && lastTagRef.current) {
        return intents.find((i) => i.tag === lastTagRef.current) ?? null;
    }

    // Greeting
    if (
        /^(hi|hii|hello|hey|good morning|good afternoon|good evening)\b/.test(input)
    ) {
        return intents.find((i) => i.tag === "greeting") ?? null;
    }

    // Introduction
    if (
        input.includes("my name is") ||
        input.startsWith("i am") ||
        input.startsWith("im ") ||
        input.startsWith("i'm ")
    ) {
        return intents.find((i) => i.tag === "greeting") ?? null;
    }

    // Thank you
    if (/(thank you|thanks|thx)/.test(input)) {
        return intents.find((i) => i.tag === "thanks") ?? null;
    }

    // Goodbye
    if (/(bye|goodbye|see you|take care)/.test(input)) {
        return intents.find((i) => i.tag === "goodbye") ?? null;
    }

    // Fuse search
    const results = fuse.search(input);

    if (results.length && (results[0].score ?? 1) < 0.45) {
        return results[0].item;
    }

    return null;
  }

  function getFallbackSuggestions(text: string): string[] {
    // even on a miss, surface the 3 closest-sounding topics as "did you mean"
    const loose = fuse.search(text, { limit: 3 });
    if (loose.length > 0) {
      return loose.map((r) => r.item.suggestions?.[0] || r.item.patterns[0]);
    }
    return ["What services do you offer?", "Website cost?", "Contact us"];
  }

  function respondTo(text: string) {
    const intent = resolveIntent(text);

    if (intent) {
      lastTagRef.current = intent.tag;
      setMessages((prev) => [
        ...prev,
        { role: "bot", text: intent.answer, suggestions: intent.suggestions },
      ]);
    } else {
      setMessages((prev) => [
        ...prev,
        {
          role: "bot",
          text: `${FALLBACK} Or reach us directly on WhatsApp: 8000361445.`,
          suggestions: getFallbackSuggestions(text),
        },
      ]);
    }
  }

  function sendMessage(overrideText?: string) {
    const text = (overrideText ?? message).trim();
    if (!text) return;

    setMessages((prev) => [...prev, { role: "user", text }]);
    setMessage("");

    setTimeout(() => respondTo(text), 600);
  }

  return (
    <div className={`ai-chat-widget-root ${isAiDriven ? "ai-driven-theme" : ""}`}>
       <button
            aria-label={open ? "Close AI chat assistant" : "Open AI chat assistant"}
            aria-expanded={open}
            aria-controls="ai-chat-box"
            className="ai-chat-button"
            onClick={() => setOpen(!open)}
            >
            {open ? (
                <X aria-hidden="true" />
            ) : (
                <Bot aria-hidden="true" />
            )}
        </button>

      {open && (
        <div
            id="ai-chat-box"
            className="ai-chat-box"
            role="dialog"
            aria-label="Digi AI chat assistant"
            aria-modal="false"
            >
          <div className="ai-header">
            <div>
              <Bot size={22} />
              <span>Digi AI</span>
            </div>
            <span className="online">● Online</span>
          </div>

          <div className="ai-body">
            {messages.map((msg, index) => (
              <div key={index}>
                <div className={msg.role === "bot" ? "bot-msg" : "user-msg"}>
                  {msg.role === "bot" ? linkify(msg.text) : msg.text}
                </div>

                {msg.role === "bot" && msg.suggestions && index === messages.length - 1 && (
                  <div className="inline-suggestions">
                    {msg.suggestions.map((s, i) => (
                      <button key={i} onClick={() => sendMessage(s)}>
                        {s}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>

          <div className="quick-buttons">
            <button onClick={() => sendMessage("What services do you provide?")}>Services</button>
            <button onClick={() => sendMessage("SEO service details")}>SEO</button>
            <button onClick={() => sendMessage("Website cost")}>Price</button>
            <button onClick={() => sendMessage("Contact us")}>Contact</button>
          </div>

          <div className="ai-input">
            <input
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") sendMessage();
              }}
              placeholder="Type message..."
            />
            <button onClick={() => sendMessage()}>
              <Send size={18} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
