"use client";

import Link from "next/link";
import { useState, useTransition } from "react";
import { PlatformHeader } from "@/components/platform/platform-header";

export default function RegisterPage() {
  const [error, setError] = useState<string | null>(null);
  const [alternatives, setAlternatives] = useState<string[]>([]);
  const [success, setSuccess] = useState<{
    slug: string;
    siteHost: string;
    siteUrl: string;
  } | null>(null);
  const [pending, startTransition] = useTransition();

  function onSubmit(formData: FormData) {
    setError(null);
    setAlternatives([]);
    startTransition(async () => {
      const payload = {
        name: String(formData.get("name") ?? ""),
        email: String(formData.get("email") ?? ""),
        password: String(formData.get("password") ?? ""),
        studioName: String(formData.get("studioName") ?? ""),
        slug: String(formData.get("slug") ?? "") || undefined,
      };

      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = (await res.json()) as {
        error?: string;
        alternatives?: string[];
        slug?: string;
        site?: string;
        siteHost?: string;
      };

      if (!res.ok) {
        setError(data.error ?? "Registration failed");
        setAlternatives(data.alternatives ?? []);
        return;
      }

      setSuccess({
        slug: data.slug ?? "",
        siteHost: data.siteHost ?? `${data.slug}.localhost`,
        siteUrl: data.site ?? "#",
      });
    });
  }

  return (
    <div className="min-h-full bg-[var(--archi-cream)]">
      <PlatformHeader />
      <div className="mx-auto grid min-h-[calc(100svh-4.25rem)] max-w-7xl lg:grid-cols-2">
        <aside className="relative hidden overflow-hidden bg-[var(--archi-dark)] text-white lg:block">
          <div
            aria-hidden
            className="absolute inset-0"
            style={{
              background:
                "radial-gradient(ellipse 80% 70% at 20% 30%, rgba(201,162,39,0.25), transparent 55%), linear-gradient(160deg, #16181c 0%, #0b0b0c 100%)",
            }}
          />
          <div className="studio-grain pointer-events-none absolute inset-0 opacity-35" />
          <div className="relative flex h-full flex-col justify-between p-10 xl:p-14">
            <div>
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-gold)] uppercase">
                ARCHI for architects
              </p>
              <h1 className="mt-6 max-w-md font-[family-name:var(--font-display)] text-5xl leading-[1.05] tracking-tight">
                Your studio. Your subdomain. Your leads.
              </h1>
              <p className="mt-6 max-w-sm text-sm leading-7 text-white/55">
                Claim an isolated website, portfolio CMS, and inquiry inbox —
                with tenant boundaries enforced on every request.
              </p>
            </div>
            <ul className="space-y-3 text-sm text-white/60">
              {[
                "Live public studio site included",
                "Draft → publish portfolio workflow",
                "Inquiries stay private to your studio",
              ].map((item) => (
                <li key={item} className="flex gap-3">
                  <span className="mt-1.5 h-1.5 w-1.5 shrink-0 bg-[var(--archi-gold)]" />
                  {item}
                </li>
              ))}
            </ul>
          </div>
        </aside>

        <main className="flex items-center px-[max(1.25rem,env(safe-area-inset-left))] py-10 pr-[max(1.25rem,env(safe-area-inset-right))] pb-[max(2.5rem,env(safe-area-inset-bottom))] sm:px-10 lg:px-14">
          <div className="mx-auto w-full max-w-md">
            {success ? (
              <div>
                <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                  Ready
                </p>
                <h2 className="mt-3 font-[family-name:var(--font-display)] text-[clamp(2rem,8vw,2.5rem)] tracking-tight sm:text-4xl">
                  Studio created
                </h2>
                <div className="archi-panel mt-8 p-5">
                  <p className="text-xs tracking-[0.18em] text-[var(--archi-ink-muted)] uppercase">
                    Your live site
                  </p>
                  <a
                    href={success.siteUrl}
                    className="mt-2 block font-[family-name:var(--font-display)] text-2xl text-[var(--archi-ink)] underline-offset-4 hover:underline"
                    target="_blank"
                    rel="noreferrer"
                  >
                    {success.siteHost}
                  </a>
                  <p className="mt-3 text-sm text-[var(--archi-ink-muted)]">
                    Subdomains follow the current hosting environment.
                  </p>
                </div>
                <Link
                  href="/?auth=login"
                  className="archi-btn-primary mt-8 inline-flex"
                >
                  Sign in to dashboard →
                </Link>
              </div>
            ) : (
              <div>
                <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase lg:hidden">
                  Start on ARCHI
                </p>
                <h2 className="mt-3 font-[family-name:var(--font-display)] text-[clamp(2rem,8vw,2.5rem)] tracking-tight sm:text-4xl">
                  Start your studio
                </h2>
                <p className="mt-3 text-[var(--archi-ink-muted)]">
                  Create an account and claim your subdomain.
                </p>
                <form action={onSubmit} className="mt-10 space-y-4">
                  <label className="block text-sm">
                    Full name
                    <input name="name" required className="archi-input mt-2" />
                  </label>
                  <label className="block text-sm">
                    Email
                    <input
                      name="email"
                      type="email"
                      required
                      className="archi-input mt-2"
                    />
                  </label>
                  <label className="block text-sm">
                    Password
                    <input
                      name="password"
                      type="password"
                      required
                      minLength={12}
                      className="archi-input mt-2"
                    />
                  </label>
                  <label className="block text-sm">
                    Studio name
                    <input
                      name="studioName"
                      required
                      placeholder="Atelier North"
                      className="archi-input mt-2"
                    />
                  </label>
                  <label className="block text-sm">
                    Preferred slug (optional)
                    <input
                      name="slug"
                      placeholder="atelier-north"
                      className="archi-input mt-2"
                    />
                  </label>
                  {error ? (
                    <p className="text-sm text-red-800" role="alert">
                      {error}
                    </p>
                  ) : null}
                  {alternatives.length > 0 ? (
                    <p className="text-sm text-[var(--archi-ink-muted)]">
                      Try: {alternatives.join(", ")}
                    </p>
                  ) : null}
                  <button
                    type="submit"
                    disabled={pending}
                    className="archi-btn-primary mt-2 min-h-12 w-full py-3 disabled:opacity-60"
                  >
                    {pending ? "Creating…" : "Create studio"}
                  </button>
                </form>
                <p className="mt-6 text-sm text-[var(--archi-ink-muted)]">
                  Already have an account?{" "}
                  <Link href="/?auth=login" className="underline underline-offset-4">
                    Sign in
                  </Link>
                </p>
              </div>
            )}
          </div>
        </main>
      </div>
    </div>
  );
}
