import { useState, useEffect } from "react";
import { API_URL } from "../config";

export default function RandomMsg() {
  const [randomMsg, setRandomMsg] = useState("");

  const getRandomMsg = async () => {
    try {
      const response = await fetch(`${API_URL}/randmsg`, {
        method: "POST",
        headers: { "Content-Type": "application/json; charset=utf-8" },
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const data = await response.json();
      if (data?.msg) setRandomMsg(data.msg.replace(/<br\s*\/?>/gi, "\n"));
    } catch (err) {
      console.error("Failed to fetch random message:", err);
    }
  };

  useEffect(() => void getRandomMsg(), []);

  return (
    <div className="random-msg-container">
      <div className="random-msg">
        {randomMsg && (
          <small>
            <i>{randomMsg}</i>
          </small>
        )}
      </div>
      {randomMsg && (
        <button
          aria-label="New footer message"
          type="button"
          className="flex items-center justify-center px-2 py-1 rounded-md hover:bg-neutral-200 dark:hover:bg-neutral-800 transition-opacity new-msg-button"
          onClick={getRandomMsg}
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
            width="16"
            height="16"
            aria-hidden="true"
            focusable="false"
            className="inline-block"
          >
            <path
              d="M21 12a9 9 0 1 1-2.64-6.36"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <polyline
              points="21 3 21 9 15 9"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>

        </button>
      )}

    </div>
  );
}
