import { useState } from "react";
import { Link } from "react-router-dom";
import { Button, Card, Textarea } from "../../components/ui";
import { apiRequest } from "../../data/live/http";
import { useI18n } from "../../i18n/I18nContext";

export function StyleQuizPage() {
  const { t } = useI18n();
  const [samples, setSamples] = useState("");
  const [result, setResult] = useState<{
    tone: string;
    rhythm: string;
    hooks: string;
    avoid: string;
    summary: string;
    tags: string[];
    signup_hint: string;
  } | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  async function run() {
    setBusy(true);
    setErr("");
    try {
      const data = await apiRequest<NonNullable<typeof result>>("/api/v1/public/tools/style-quiz", {
        method: "POST",
        body: { samples },
        // 免登入端點：不要把會員 JWT 送出去，也不要在 401 時觸發 refresh。
        auth: false,
      });
      setResult(data);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "fail");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hb-main__inner" style={{ maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
      <h1>{t("tools.style.title")}</h1>
      <p className="text-muted">{t("tools.style.subtitle")}</p>
      <Card>
        <Textarea label={t("tools.style.samples")} rows={8} value={samples} onChange={(e) => setSamples(e.target.value)} />
        <Button type="button" disabled={busy || !samples.trim()} onClick={() => void run()}>
          {busy ? t("tools.style.running") : t("tools.style.run")}
        </Button>
      </Card>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {result ? (
        <Card title={t("tools.style.result")}>
          <p>{result.summary}</p>
          <ul>
            <li>{t("tools.style.tone", { v: result.tone })}</li>
            <li>{t("tools.style.rhythm", { v: result.rhythm })}</li>
            <li>{t("tools.style.hooks", { v: result.hooks })}</li>
            <li>{t("tools.style.avoid", { v: result.avoid })}</li>
          </ul>
          <p className="text-muted">{result.signup_hint}</p>
          <Link to="/login">
            <Button type="button">{t("tools.style.login")}</Button>
          </Link>
        </Card>
      ) : null}
    </div>
  );
}
