"use client";

import Image from "next/image";
import React, { useState, useRef, useEffect } from "react";

interface Props {
  text: string;
  rate?: number;
  pitch?: number;
  lang?: string;
  title?: string;
}

const TextToSpeechChatbot: React.FC<Props> = ({
  text,
  rate = 1,
  pitch = 1,
  lang = "en-US",
  title=''
}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [currentCharIndex, setCurrentCharIndex] = useState<number | null>(null);
  const [isOpen, setIsOpen] = useState(true);
  const [isHovered, setIsHovered] = useState(false);

  const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);
  const textLength = text.length;

  useEffect(() => {
    return () => {
      window.speechSynthesis.cancel();
    };
  }, []);

  const speak = () => {
    if (!("speechSynthesis" in window)) return;

    if (isPaused) {
      window.speechSynthesis.resume();
      setIsPaused(false);
      setIsPlaying(true);
      return;
    }

    window.speechSynthesis.cancel();

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = rate;
    utterance.pitch = pitch;
    utterance.lang = lang;

    utterance.onboundary = (event: SpeechSynthesisEvent) => {
      if (event.name === "word") {
        setCurrentCharIndex(event.charIndex);
      }
    };

    utterance.onend = () => {
      setIsPlaying(false);
      setIsPaused(false);
      setCurrentCharIndex(null)
    };

    utterance.onerror = () => {
      setIsPlaying(false);
      setIsPaused(false);
      setCurrentCharIndex(null);
    };

    utteranceRef.current = utterance;
    window.speechSynthesis.speak(utterance);
    setIsPlaying(true);
  };


  const pause = () => {
    window.speechSynthesis.pause();
    setIsPaused(true);
    setIsPlaying(false);
  };

  const stop = () => {
    window.speechSynthesis.cancel();
    setIsPlaying(false);
    setIsPaused(false);
    setCurrentCharIndex(null);
  };

  const highlightedText = (
    <span>
      <span style={{ backgroundColor: "#6c63ff", color: "#fff" }}>
        {text.substring(0, currentCharIndex ?? 0)}
      </span>
      <span>{text.substring(currentCharIndex ?? 0)}</span>
    </span>
  );

  const progressPercent =
    currentCharIndex !== null
      ? Math.min(100, Math.floor((currentCharIndex / textLength) * 100))
      : 0;
      

  return (
    <div
      style={{
        ...containerStyle,
        backgroundColor: !isOpen && isHovered ? "#6d4baa" : "#5d3997ff",
        transform: !isOpen && isHovered ? "translateY(-2px)" : "none",
        transition: "all 0.2s ease"
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {isOpen && <Image
        src="/images/robo.gif"
        alt="Speaker Icon"
        width={80}
        height={80}
        style={{ 
          position: "absolute",
          top: '-18%',
          left: "50%",
          transform: "translate(-50%, -50%)",
          borderRadius: "50%",
          objectFit: "cover",
          width: "clamp(60px, 15vw, 80px)",
          height: "clamp(60px, 15vw, 80px)"
        }}
      />}
      {/* ── Header / Toggle row ── */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: isOpen ? 12 : 0,
          cursor: "pointer",
          userSelect: "none",
        }}
        onClick={() => {
          if (isOpen && isPlaying) stop();
          setIsOpen((v) => !v);
        }}
      >
        <span className="truncate" style={{ fontWeight: 700, fontSize: 14, letterSpacing: 0.5 }}>
          🔊 {title}
        </span>
        <span style={{ fontSize: 40, lineHeight: 1 }}>{isOpen ? "▾" : "▸"}</span>
      </div>

      {/* ── Collapsible body ── */}
      {isOpen && (
        <>
          <div
            style={{
              fontSize: "14px",
              lineHeight: 1.5,
              marginBottom: "10px",
              userSelect: "none",
              whiteSpace: "pre-wrap",
              maxHeight: "120px",
              overflowY: "auto",
            }}
          >
            {highlightedText}
          </div>

          <div style={progressBarContainerStyle}>
            <div
              style={{
                height: "100%",
                width: `${progressPercent}%`,
                backgroundColor: "#6c63ff",
                transition: "width 0.2s ease",
              }}
            />
          </div>

          <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
            {!isPlaying ? (
              <button onClick={speak} style={buttonStyle}>
                🔊 {isPaused ? "Resume" : "Listen"}
              </button>
            ) : (
              <button onClick={pause} style={buttonStyle}>
                ⏸ Pause
              </button>
            )}

            {(isPlaying || isPaused) && (
              <button
                onClick={stop}
                style={{ ...buttonStyle, background: "#c0392b" }}
              >
                ⏹ Stop
              </button>
            )}
          </div>
        </>
      )}
    </div>
  );
};

const containerStyle: React.CSSProperties = {
  position: "fixed",
  bottom: 24,
  right: 24,
  width: 320,
  backgroundColor: "#5d3997ff",
  color: "white",
  borderRadius: 16,
  boxShadow: "0 8px 24px rgba(59, 64, 164, 0.25)",
  padding: "6px 20px",
  fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
  zIndex: 1000,
  display: "flex",
  flexDirection: "column",
};

const progressBarContainerStyle: React.CSSProperties = {
  height: 8,
  width: "100%",
  backgroundColor: "#1f0364ff",
  borderRadius: 8,
  overflow: "hidden",
  marginBottom: 20,
  userSelect: "none",
};

const buttonStyle: React.CSSProperties = {
  flex: 1,
  padding: "10px 0",
  borderRadius: 12,
  border: "none",
  cursor: "pointer",
  fontSize: 16, 
  background:
    "linear-gradient(90deg, #020b43ff, #2f09a0ff)", // teal gradient
  color: "#fff",
  fontWeight: 600,
  userSelect: "none",
};

export default TextToSpeechChatbot;
