/**
 * Search-box.ai
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File: apps/web/components/NewResearchForm.tsx
 * Description: Question composer — example chips, keyboard submit, session start.
 */

"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Glyph } from "./Pastille";

const EXAMPLES = [
  "Can transformer KV cache be compressed 10x without hurting quality?",
  "Do heat pumps still beat gas boilers in very cold climates?",
  "Is open-source AI closing the gap with frontier labs?"
];

export function NewResearchForm() {
  const router = useRouter();
  const [question, setQuestion] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit() {
    const q = question.trim();
    if (q.length < 8 || busy) return;
    setBusy(true);
    setError(null);
    try {
      const res = await fetch("/api/research", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: q })
      });
      if (!res.ok) {
        const body = (await res.json().catch(() => ({}))) as { error?: string };
        throw new Error(body.error ?? `request failed (${res.status})`);
      }
      const { id } = (await res.json()) as { id: string };
      router.push(`/r/${id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
      setBusy(false);
    }
  }

  return (
    <div className="ask">
      <div className="box">
        <textarea
          value={question}
          onChange={(e) => setQuestion(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
              e.preventDefault();
              void submit();
            }
          }}
          placeholder="Ask a question that deserves real research…"
          aria-label="Research question"
        />
        <div className="box-foot">
          <span className="hint">⌘⏎ to launch</span>
          <button className="btn" onClick={() => void submit()} disabled={busy || question.trim().length < 8}>
            <Glyph kind="search" size={14} />
            {busy ? "starting…" : "Start research"}
          </button>
        </div>
      </div>
      <div className="chips">
        {EXAMPLES.map((ex) => (
          <button key={ex} className="chip" onClick={() => setQuestion(ex)}>
            {ex}
          </button>
        ))}
      </div>
      {error && <div className="error-box">{error}</div>}
    </div>
  );
}
