"use client";

import { useLocale, useT } from "@/components/LocaleProvider";
import { FormEvent, useId, useState } from "react";

type EarlyAccessFormProps = {
  layout?: "hero" | "compact";
  className?: string;
  /** Gdy true, nie renderuj blurbu hero — użyj go osobno (np. osobny parallax w Hero). */
  omitHeroBlurb?: boolean;
};

type Platform = "ios" | "android";

function IconIos({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      aria-hidden
      fill="currentColor"
    >
      <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" />
    </svg>
  );
}

function IconAndroid({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      aria-hidden
      fill="currentColor"
    >
      <path d="M17.6 9.48l1.84-2.83c.11-.17.06-.4-.12-.5-.17-.11-.4-.06-.5.12l-1.87 2.89C15.16 7.97 13.69 7.5 12 7.5s-3.16.47-4.45 1.16L5.68 5.77c-.1-.18-.33-.23-.5-.12-.18.1-.23.33-.12.5l1.84 2.83C4.55 10.75 3.5 12.88 3.5 15.23V16.5c0 .83.67 1.5 1.5 1.5h1.5v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V18h7v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V18h1.5c.83 0 1.5-.67 1.5-1.5v-1.27c0-2.35-1.05-4.48-2.9-5.75zM7 12.25c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25zm10 0c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25z" />
    </svg>
  );
}

export function EarlyAccessForm({
  layout = "hero",
  className = "",
  omitHeroBlurb = false,
}: EarlyAccessFormProps) {
  const t = useT();
  const locale = useLocale();
  const fieldId = useId();
  const [email, setEmail] = useState("");
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pending, setPending] = useState(false);
  const [osRevealed, setOsRevealed] = useState(false);
  const [platform, setPlatform] = useState<Platform | null>(null);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const v = email.trim();
    if (!v) return;
    if (!platform) {
      setOsRevealed(true);
      setError(t("earlyAccess.errorPlatform"));
      return;
    }
    setError(null);
    setPending(true);
    try {
      const res = await fetch("/api/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: v,
          locale,
          platform,
        }),
      });
      const data = (await res.json().catch(() => ({}))) as {
        error?: string;
      };
      if (res.status === 201 || res.status === 409) {
        setDone(true);
        return;
      }
      if (res.status === 400) {
        if (data.error === "invalid_platform") {
          setError(t("earlyAccess.errorPlatform"));
          return;
        }
        setError(t("earlyAccess.errorInvalid"));
        return;
      }
      setError(
        data.error === "server_error"
          ? t("earlyAccess.errorServer")
          : t("earlyAccess.errorGeneric"),
      );
    } catch {
      setError(t("earlyAccess.errorNetwork"));
    } finally {
      setPending(false);
    }
  }

  const inputBase =
    "min-h-[48px] w-full min-w-0 rounded-full border border-white/15 bg-white/[0.06] px-5 py-3 text-[15px] text-foreground outline-none ring-accent/40 transition-[border,box-shadow] placeholder:text-muted focus:border-accent/50 focus:ring-2";

  const buttonBase =
    "inline-flex min-h-[48px] shrink-0 items-center justify-center rounded-full bg-white px-6 py-3 text-[15px] font-semibold text-black transition-transform duration-300 hover:-translate-y-0.5 hover:shadow-[0_12px_40px_-8px_rgba(168,85,247,0.5)] active:translate-y-0";

  const osBtnBase =
    "inline-flex h-10 w-[100px] shrink-0 items-center justify-center gap-1.5 rounded-xl border px-2.5 text-sm font-medium transition-[border,background-color,box-shadow] sm:w-[108px]";

  function osBtnClasses(p: Platform) {
    const on = platform === p;
    return `${osBtnBase} ${
      on
        ? "border-accent/55 bg-white/10 text-foreground shadow-[0_0_0_1px_rgba(168,85,247,0.35)] ring-2 ring-accent/30"
        : "border-white/12 bg-white/[0.04] text-muted hover:border-white/25 hover:bg-white/[0.07] hover:text-foreground"
    }`;
  }

  if (done) {
    return (
      <p
        className={`text-center text-sm text-accent-bright md:text-base ${className}`}
        role="status"
      >
        {t("earlyAccess.success")}
      </p>
    );
  }

  return (
    <div className={className}>
      {layout === "hero" && !omitHeroBlurb && (
        <p className="mx-auto mb-4 max-w-md text-pretty text-center text-sm text-muted md:text-base">
          {t("earlyAccess.heroBlurb")}
        </p>
      )}
      <form
        onSubmit={onSubmit}
        className={
          layout === "hero"
            ? "flex w-full flex-col gap-3"
            : "mx-auto flex w-full max-w-md flex-col gap-3"
        }
      >
        <div
          className={
            layout === "hero"
              ? "flex w-full flex-col gap-3 sm:flex-row sm:items-start sm:justify-center"
              : "flex w-full flex-col gap-3 sm:flex-row sm:items-start"
          }
        >
          <div className="flex min-w-0 w-full flex-1 flex-col gap-2">
            <label htmlFor={fieldId} className="sr-only">
              {t("earlyAccess.emailLabel")}
            </label>
            <input
              id={fieldId}
              name="email"
              type="email"
              autoComplete="email"
              inputMode="email"
              required
              placeholder={t("earlyAccess.placeholder")}
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onFocus={() => setOsRevealed(true)}
              className={inputBase}
            />

            {osRevealed ? (
              <div
                className="flex w-full flex-col items-center gap-2"
                role="group"
                aria-label={t("earlyAccess.platformLabel")}
              >
                <p className="w-full text-center text-xs text-muted">
                  {t("earlyAccess.platformLabel")}
                </p>
                <div className="flex justify-center gap-2">
                  <button
                    type="button"
                    aria-pressed={platform === "ios"}
                    aria-label={t("earlyAccess.platformIosAria")}
                    onMouseDown={(e) => e.preventDefault()}
                    onClick={() => {
                      setPlatform("ios");
                      setError(null);
                    }}
                    className={osBtnClasses("ios")}
                  >
                    <IconIos className="h-5 w-5 shrink-0" />
                    <span>iOS</span>
                  </button>
                  <button
                    type="button"
                    aria-pressed={platform === "android"}
                    aria-label={t("earlyAccess.platformAndroidAria")}
                    onMouseDown={(e) => e.preventDefault()}
                    onClick={() => {
                      setPlatform("android");
                      setError(null);
                    }}
                    className={osBtnClasses("android")}
                  >
                    <IconAndroid className="h-5 w-5 shrink-0" />
                    <span>Android</span>
                  </button>
                </div>
              </div>
            ) : null}
          </div>

          <button type="submit" className={buttonBase} disabled={pending}>
            {pending ? t("earlyAccess.submitting") : t("earlyAccess.submit")}
          </button>
        </div>
      </form>
      {error ? (
        <p className="mt-3 text-center text-sm text-red-400" role="alert">
          {error}
        </p>
      ) : null}
    </div>
  );
}
