// src/AssistantMessage.jsx
import React, { useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";

export default function AssistantMessage({ content, theme, timestamp }) {
  return (
    <div className="mb-2 text-start">
      <div
        className={`d-inline-block p-2 rounded ${theme.assistantBg}`}
        style={{ maxWidth: "95%" }}
      >
        <ReactMarkdown
          remarkPlugins={[remarkGfm, remarkMath]}
          rehypePlugins={[rehypeKatex]}
          components={{
            table: (props) => (
              <table className="table table-sm table-bordered" {...props} />
            ),
            th: (props) => <th className="bg-light" {...props} />,
            code: CodeWithCopy
          }}
        >
          {content}
        </ReactMarkdown>
      </div>
      {timestamp && (
        <div
          style={{
            fontSize: "0.75rem",
            color: "#666",
            marginTop: "0.2rem",
            marginLeft: "0.25rem"
          }}
        >
          {formatDateTime(timestamp)}
        </div>
      )}
    </div>
  );
}

function CodeWithCopy({ inline, className = "", children, ...props }) {
  const [copied, setCopied] = useState(false);
  const codeText = String(children).replace(/\n$/, "");

  // Only show copy button for fenced code with language
  const isFencedBlock = !inline && /^language-/.test(className);

  if (!isFencedBlock) {
    return (
      <code className={className} {...props}>
        {children}
      </code>
    );
  }

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(codeText);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch (err) {
      console.error("Copy failed", err);
    }
  };

  return (
    <div style={{ position: "relative" }}>
      <pre className={className} {...props} style={{ paddingRight: "2rem" }}>
        <code>{codeText}</code>
      </pre>
      <button
        onClick={handleCopy}
        style={{
          position: "absolute",
          top: "0.25rem",
          right: "0.25rem",
          border: "none",
          background: "transparent",
          cursor: "pointer",
          fontSize: "0.85rem"
        }}
        title="Copy to clipboard"
      >
        📋
      </button>
      {copied && (
        <span
          style={{
            position: "absolute",
            top: "0.25rem",
            right: "2rem",
            fontSize: "0.8rem",
            color: "green"
          }}
        >
          Copied!
        </span>
      )}
    </div>
  );
}

// Utility to format timestamp nicely
function formatDateTime(dateTime) {
  try {
    const date = new Date(dateTime);
    return date.toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit"
    });
  } catch {
    return dateTime;
  }
}


