// frontend/app/login/page.tsx — phase-15 로그인 화면(글래스 카드).
// 인증 꺼짐이어도 도달 가능(셸 밖, 자체 배경). 성공 시 ?next 또는 /dashboard 로 이동.
"use client";
import { Suspense, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Icon } from "@/components/Icon";
import { login } from "@/lib/auth";
import "@/styles/login.css";

function LoginForm() {
  const router = useRouter();
  const params = useSearchParams();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const canSubmit = email.trim() !== "" && password !== "" && !busy;

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!canSubmit) return; // 빈 입력은 422 방지 — 제출 자체를 막는다
    setBusy(true);
    setError(null);
    try {
      await login(email, password);
      const next = params.get("next");
      router.push(next ?? "/dashboard");
    } catch {
      setError("이메일 또는 비밀번호가 올바르지 않아요");
      setBusy(false);
    }
  }

  return (
    <div className="login-card">
      <div className="login-brand">
        <span className="login-mark" aria-hidden>
          <Icon name="spark" />
        </span>
        <span>
          <b>아리</b>
          <span>AI LIFE OS</span>
        </span>
      </div>

      <h1 className="login-title">다시 오셨네요</h1>
      <p className="login-sub">로그인하면 아리가 이어서 정리해 둘게요.</p>

      <form className="login-form" onSubmit={onSubmit} noValidate>
        <div className="login-field">
          <label htmlFor="login-email">이메일</label>
          <input
            id="login-email"
            type="email"
            autoComplete="email"
            placeholder="이메일"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <div className="login-field">
          <label htmlFor="login-password">비밀번호</label>
          <input
            id="login-password"
            type="password"
            autoComplete="current-password"
            placeholder="비밀번호"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>

        {error && (
          <p className="login-error" role="alert">
            {error}
          </p>
        )}

        <button type="submit" className="login-cta" disabled={!canSubmit}>
          로그인
        </button>
      </form>
    </div>
  );
}

export default function LoginPage() {
  return (
    <div className="loginpage">
      {/* useSearchParams() 는 Suspense 경계 필요(Next 16) */}
      <Suspense fallback={<div className="login-card" aria-busy="true" />}>
        <LoginForm />
      </Suspense>
    </div>
  );
}
