"use client";

import { useState } from "react";

export default function Home() {
  const [response, setResponse] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const testGrpc = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/grpc-test?msg=HelloBot");
      const data = await res.json();
      setResponse(data);
    } catch (err) {
      setResponse({ success: false, error: "Fetch error" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <main className="flex flex-col gap-8 row-start-2 items-center sm:items-start text-center sm:text-left">
        <h1 className="text-4xl font-bold">Kord Dashboard (gRPC Test)</h1>
        <p className="text-gray-500">대시보드와 봇 간의 gRPC 통신망을 테스트합니다.</p>

        <div className="flex gap-4 items-center flex-col sm:flex-row w-full justify-center">
          <button
            onClick={testGrpc}
            disabled={loading}
            className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-6 sm:px-8 font-medium"
          >
            {loading ? "통신 중..." : "봇에게 Ping 보내기"}
          </button>
        </div>

        {response && (
          <div className={`mt-8 p-6 rounded-lg border w-full max-w-md ${response.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
            <h2 className="text-lg font-semibold mb-2">테스트 결과</h2>
            <pre className="text-sm font-mono whitespace-pre-wrap">
              {JSON.stringify(response, null, 2)}
            </pre>
            {response.success && (
              <p className="mt-2 text-green-700 font-medium text-sm">✅ 봇으로부터 성공적으로 응답을 받았습니다!</p>
            )}
            {!response.success && (
              <p className="mt-2 text-red-700 font-medium text-sm">❌ 봇과 통신에 실패했습니다. (봇 구동 여부를 확인하세요)</p>
            )}
          </div>
        )}
      </main>
    </div>
  );
}
