/**
 * Polderfest 2027 — chat pagina
 * --------------------------------------------------
 * Les 11 — useChat hook + Tailwind chat UI.
 * Plaats dit bestand op: app/chat/page.tsx
 *
 * Werking:
 *   - useChat() regelt messages, input, submit-handler, streaming
 *   - Praat met /api/chat (de route.ts)
 *   - Disabled tijdens streaming
 *
 * Vereist:
 *   - app/api/chat/route.ts (zie route.ts)
 *   - npm i ai
 *   - Tailwind aanwezig in project (standaard in create-next-app)
 */

"use client";

import { useState } from "react";
import { useChat } from "@ai-sdk/react";

export default function ChatPage() {
  const { messages, sendMessage, status } = useChat();
  const [input, setInput] = useState("");

  return (
    <main className="max-w-2xl mx-auto p-6 flex flex-col h-screen">
      <div className="flex items-center justify-between gap-3 mb-4">
        <h1 className="text-2xl font-bold">Polderfest 2027 — vraag de AI</h1>
        <a
          href="/supabase"
          className="text-sm px-3 py-2 rounded-lg border hover:bg-gray-50"
        >
          Supabase test
        </a>
      </div>

      <div className="flex-1 overflow-y-auto space-y-4 mb-4">
        {messages.map((m) => (
          <div
            key={m.id}
            className={
              m.role === "user"
                ? "bg-blue-50 p-3 rounded-lg ml-12"
                : "bg-gray-50 p-3 rounded-lg mr-12"
            }
          >
            <div className="font-medium text-sm text-gray-500 mb-1">
              {m.role === "user" ? "Jij" : "Festival AI"}
            </div>
            <div className="whitespace-pre-wrap">
              {m.parts
                .filter((p) => p.type === "text")
                .map((p) => p.text)
                .join("")}
            </div>
          </div>
        ))}
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          const text = input.trim();
          if (!text || status !== "ready") return;
          setInput("");
          void sendMessage({ text });
        }}
        className="flex gap-2"
      >
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Stel een vraag over de line-up..."
          className="flex-1 p-3 border rounded-lg"
          disabled={status !== "ready"}
        />
        <button
          type="submit"
          disabled={status !== "ready"}
          className="px-6 py-3 bg-blue-600 text-white rounded-lg disabled:opacity-50"
        >
          Stuur
        </button>
      </form>
    </main>
  );
}
