// @File: src/pages/Register.tsx
// @Desc: Premium 4-step registration wizard that visually matches the reference
//        design: 32/68 split, dark green/black gradient branding panel, large
//        white rounded card with numbered step progress bar, tall inline-label
//        inputs, and a right-aligned gradient Continue button.
import { useEffect, useMemo, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  AlertCircle,
  ArrowLeft,
  ArrowRight,
  Building2,
  Check,
  CheckCircle2,
  Eye,
  EyeOff,
  Globe,
  Headphones,
  Loader2,
  Lock,
  LogIn,
  Mail,
  MapPin,
  Phone,
  Shield,
  ShieldCheck,
  User,
  Zap,
} from "lucide-react";
import { client } from "@/lib/api";
import { extractErrorMessage, setSession } from "@/lib/auth";
import { useBranding } from "./admin/cms/useBranding";
import SocialLoginButtons from "@/components/auth/SocialLoginButtons";

// ---------- Theme tokens (match the reference image) ----------
const GREEN = "#0e8a20";
const GREEN_BRIGHT = "#12a12a";
const GREEN_DARK = "#066314";
const BG_DARK = "#020b08";
const BG_DARK_2 = "#05150d";
const TEXT_DARK = "#101418";
const TEXT_MUTED = "#5f6673";
const BORDER_GREEN = "rgba(14, 138, 32, 0.45)";
const BORDER_GREEN_SOFT = "rgba(14, 138, 32, 0.22)";

const COUNTRY_OPTIONS: Array<{ code: string; name: string }> = [
  { code: "SA", name: "Saudi Arabia" },
  { code: "AE", name: "United Arab Emirates" },
  { code: "KW", name: "Kuwait" },
  { code: "QA", name: "Qatar" },
  { code: "BH", name: "Bahrain" },
  { code: "OM", name: "Oman" },
  { code: "JO", name: "Jordan" },
  { code: "EG", name: "Egypt" },
  { code: "US", name: "United States" },
  { code: "GB", name: "United Kingdom" },
  { code: "CA", name: "Canada" },
  { code: "AU", name: "Australia" },
  { code: "IN", name: "India" },
  { code: "PK", name: "Pakistan" },
  { code: "TR", name: "Turkey" },
];

interface RegisterForm {
  firstname: string;
  lastname: string;
  email: string;
  password: string;
  confirmPassword: string;
  companyname: string;
  address1: string;
  address2: string;
  city: string;
  state: string;
  postcode: string;
  country: string;
  phonenumber: string;
  terms: boolean;
}

const INITIAL: RegisterForm = {
  firstname: "",
  lastname: "",
  email: "",
  password: "",
  confirmPassword: "",
  companyname: "",
  address1: "",
  address2: "",
  city: "",
  state: "",
  postcode: "",
  country: "SA",
  phonenumber: "",
  terms: false,
};

interface RegisterResponseData {
  token: string;
  user_id: string;
  email: string;
  name?: string | null;
  client_id: number;
}

const STEPS = [
  { title: "Basic Info", short: "Basic Info" },
  { title: "Security", short: "Security" },
  { title: "Contact Details", short: "Contact Details" },
  { title: "Company & Terms", short: "Company & Terms" },
];

// ---------- Tall inline-label input (reference style, ~78px tall) ----------
type InlineInputProps = {
  id: string;
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
  autoComplete?: string;
  icon: React.ReactNode;
  error?: string | null;
  success?: boolean;
  placeholder?: string;
  rightSlot?: React.ReactNode;
  inputMode?: React.HTMLAttributes<HTMLInputElement>["inputMode"];
};

function InlineInput({
  id,
  label,
  value,
  onChange,
  type = "text",
  autoComplete,
  icon,
  error,
  success,
  placeholder,
  rightSlot,
  inputMode,
}: InlineInputProps) {
  const [focused, setFocused] = useState(false);
  const borderStyle: React.CSSProperties = {
    borderColor: error
      ? "#ef4444"
      : focused
        ? GREEN
        : success
          ? BORDER_GREEN
          : BORDER_GREEN_SOFT,
    boxShadow: error
      ? "0 0 0 4px rgba(239, 68, 68, 0.12)"
      : focused
        ? `0 0 0 4px ${GREEN}26`
        : "0 1px 2px rgba(14, 138, 32, 0.06)",
  };
  return (
    <div className="w-full">
      <div
        className="relative flex items-stretch rounded-xl bg-white transition-all duration-200"
        style={{
          border: "1.5px solid",
          height: 78,
          ...borderStyle,
        }}
      >
        <div
          className="flex items-center justify-center pl-4 pr-1 shrink-0"
          style={{ color: GREEN }}
        >
          {icon}
        </div>
        <div className="flex-1 flex flex-col justify-center px-2 min-w-0">
          <label
            htmlFor={id}
            className="text-[11px] font-bold"
            style={{ color: GREEN }}
          >
            {label}
          </label>
          <input
            id={id}
            type={type}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            autoComplete={autoComplete}
            inputMode={inputMode}
            placeholder={placeholder}
            className="w-full bg-transparent outline-none text-[15px] font-semibold placeholder:text-slate-300"
            style={{ color: TEXT_DARK }}
          />
        </div>
        <div className="flex items-center pr-4 shrink-0 gap-1">
          {rightSlot}
          {!rightSlot && success && !error && (
            <CheckCircle2 className="w-5 h-5" style={{ color: GREEN }} />
          )}
        </div>
      </div>
      {error && (
        <div className="flex items-center gap-1 mt-1.5 ml-1 text-[11px] text-red-600 font-medium">
          <AlertCircle className="w-3 h-3" />
          {error}
        </div>
      )}
    </div>
  );
}

// ---------- Inline-label select ----------
type InlineSelectProps = {
  id: string;
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: Array<{ value: string; label: string }>;
  icon: React.ReactNode;
  error?: string | null;
};

function InlineSelect({
  id,
  label,
  value,
  onChange,
  options,
  icon,
  error,
}: InlineSelectProps) {
  const [focused, setFocused] = useState(false);
  const borderStyle: React.CSSProperties = {
    borderColor: error ? "#ef4444" : focused ? GREEN : BORDER_GREEN_SOFT,
    boxShadow: focused
      ? `0 0 0 4px ${GREEN}26`
      : "0 1px 2px rgba(14, 138, 32, 0.06)",
  };
  return (
    <div className="w-full">
      <div
        className="relative flex items-stretch rounded-xl bg-white transition-all duration-200"
        style={{ border: "1.5px solid", height: 78, ...borderStyle }}
      >
        <div
          className="flex items-center justify-center pl-4 pr-1 shrink-0"
          style={{ color: GREEN }}
        >
          {icon}
        </div>
        <div className="flex-1 flex flex-col justify-center px-2 min-w-0">
          <label
            htmlFor={id}
            className="text-[11px] font-bold"
            style={{ color: GREEN }}
          >
            {label}
          </label>
          <select
            id={id}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            className="w-full bg-transparent outline-none text-[15px] font-semibold appearance-none pr-6"
            style={{ color: TEXT_DARK }}
          >
            {options.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </div>
        <div className="flex items-center pr-4 shrink-0">
          <svg
            className="w-4 h-4 text-slate-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 9l-7 7-7-7"
            />
          </svg>
        </div>
      </div>
      {error && (
        <div className="flex items-center gap-1 mt-1.5 ml-1 text-[11px] text-red-600 font-medium">
          <AlertCircle className="w-3 h-3" />
          {error}
        </div>
      )}
    </div>
  );
}

// ---------- Password strength ----------
function computeStrength(pwd: string): {
  score: 0 | 1 | 2 | 3 | 4;
  label: string;
  color: string;
  tips: string[];
} {
  const tips: string[] = [];
  let score = 0;
  if (pwd.length >= 8) score++;
  else tips.push("At least 8 characters");
  if (/[A-Z]/.test(pwd)) score++;
  else tips.push("Add an uppercase letter");
  if (/[0-9]/.test(pwd)) score++;
  else tips.push("Add a number");
  if (/[^A-Za-z0-9]/.test(pwd)) score++;
  else tips.push("Add a symbol (!@#…)");
  const scoreCapped = Math.min(score, 4) as 0 | 1 | 2 | 3 | 4;
  const labels = ["Too weak", "Weak", "Fair", "Strong", "Excellent"];
  const colors = ["#ef4444", "#f97316", "#eab308", GREEN, "#047857"];
  return {
    score: scoreCapped,
    label: labels[scoreCapped],
    color: colors[scoreCapped],
    tips,
  };
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_RE = /^\+?[0-9\s\-()]{7,}$/;

export default function Register() {
  const brand = useBranding();
  const navigate = useNavigate();

  const [form, setForm] = useState<RegisterForm>(INITIAL);
  const [step, setStep] = useState(0);
  const [direction, setDirection] = useState<"forward" | "backward">("forward");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [touched, setTouched] = useState<Record<keyof RegisterForm, boolean>>(
    {} as Record<keyof RegisterForm, boolean>
  );
  const [showPwd, setShowPwd] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const countryDetected = useRef(false);

  const update = <K extends keyof RegisterForm>(
    key: K,
    value: RegisterForm[K]
  ) => {
    setForm((prev) => ({ ...prev, [key]: value }));
    setTouched((t) => ({ ...t, [key]: true }));
  };

  // Auto-detect country from browser locale (non-destructive).
  useEffect(() => {
    if (countryDetected.current) return;
    countryDetected.current = true;
    try {
      const lang = navigator.language || "";
      const region = (lang.split("-")[1] || "").toUpperCase();
      if (
        region &&
        COUNTRY_OPTIONS.some((c) => c.code === region) &&
        form.country === "SA"
      ) {
        setForm((prev) => ({ ...prev, country: region }));
      }
    } catch {
      /* ignore */
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fieldErrors: Partial<Record<keyof RegisterForm, string | null>> =
    useMemo(() => {
      const e: Partial<Record<keyof RegisterForm, string | null>> = {};
      e.firstname =
        form.firstname.trim().length < 2 ? "Enter your first name" : null;
      e.lastname =
        form.lastname.trim().length < 2 ? "Enter your last name" : null;
      e.email = !form.email
        ? "Email is required"
        : !EMAIL_RE.test(form.email)
          ? "Enter a valid email"
          : null;
      e.password =
        form.password.length === 0
          ? "Password is required"
          : form.password.length < 8
            ? "Use at least 8 characters"
            : null;
      e.confirmPassword =
        form.confirmPassword.length === 0
          ? "Please confirm your password"
          : form.confirmPassword !== form.password
            ? "Passwords don't match"
            : null;
      e.phonenumber = !form.phonenumber
        ? "Phone is required"
        : !PHONE_RE.test(form.phonenumber)
          ? "Enter a valid phone number"
          : null;
      e.country = !form.country ? "Country is required" : null;
      e.city = !form.city.trim() ? "City is required" : null;
      e.address1 = !form.address1.trim() ? "Address is required" : null;
      e.terms = !form.terms ? "You must accept the policies" : null;
      return e;
    }, [form]);

  const err = (k: keyof RegisterForm): string | null =>
    touched[k] ? fieldErrors[k] ?? null : null;

  const strength = useMemo(() => computeStrength(form.password), [form.password]);

  const stepValid = (s: number): boolean => {
    if (s === 0)
      return !fieldErrors.firstname && !fieldErrors.lastname && !fieldErrors.email;
    if (s === 1) return !fieldErrors.password && !fieldErrors.confirmPassword;
    if (s === 2)
      return (
        !fieldErrors.phonenumber &&
        !fieldErrors.country &&
        !fieldErrors.city &&
        !fieldErrors.address1
      );
    if (s === 3) return !fieldErrors.terms;
    return false;
  };

  const markStepTouched = (s: number) => {
    const sets: Record<number, Array<keyof RegisterForm>> = {
      0: ["firstname", "lastname", "email"],
      1: ["password", "confirmPassword"],
      2: ["phonenumber", "country", "city", "address1"],
      3: ["terms"],
    };
    setTouched((t) => {
      const next = { ...t };
      for (const k of sets[s] || []) next[k] = true;
      return next;
    });
  };

  const goNext = () => {
    markStepTouched(step);
    if (!stepValid(step)) return;
    setError(null);
    setDirection("forward");
    setStep((s) => Math.min(s + 1, STEPS.length - 1));
  };
  const goBack = () => {
    setError(null);
    setDirection("backward");
    setStep((s) => Math.max(s - 1, 0));
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setError(null);
    markStepTouched(3);
    if (!stepValid(0) || !stepValid(1) || !stepValid(2) || !stepValid(3)) {
      setError("Please review the highlighted fields before submitting.");
      if (!stepValid(0)) setStep(0);
      else if (!stepValid(1)) setStep(1);
      else if (!stepValid(2)) setStep(2);
      return;
    }
    setSubmitting(true);
    try {
      const res = await client.apiCall.invoke({
        url: "/api/v1/whmcs/register",
        method: "POST",
        data: {
          firstname: form.firstname.trim(),
          lastname: form.lastname.trim(),
          email: form.email.trim().toLowerCase(),
          password: form.password,
          companyname: form.companyname.trim() || null,
          address1: form.address1.trim(),
          address2: form.address2.trim() || null,
          city: form.city.trim(),
          state: form.state.trim() || form.city.trim(),
          postcode: form.postcode.trim() || "00000",
          country: form.country.toUpperCase(),
          phonenumber: form.phonenumber.trim(),
        },
      });
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const data: RegisterResponseData = (res as any)?.data;
      if (!data?.token) throw new Error("Registration response was incomplete.");
      setSession({
        token: data.token,
        user_id: data.user_id,
        email: data.email,
        name: data.name ?? null,
        client_id: data.client_id,
      });
      setSuccess(true);
      setTimeout(() => navigate("/client", { replace: true }), 1200);
    } catch (e2) {
      setError(extractErrorMessage(e2, "Registration failed. Please try again."));
    } finally {
      setSubmitting(false);
    }
  };

  // -------- Success screen --------
  if (success) {
    return (
      <div
        className="min-h-screen flex items-center justify-center p-6"
        style={{
          fontFamily: `'Inter', ${brand.fontBody || "system-ui"}, sans-serif`,
          background: `radial-gradient(1200px 600px at 20% 20%, ${GREEN}22 0%, transparent 60%), radial-gradient(1000px 500px at 80% 80%, ${GREEN_DARK}33 0%, transparent 60%), ${BG_DARK}`,
        }}
      >
        <div className="bg-white rounded-[28px] shadow-2xl p-10 max-w-md text-center animate-in fade-in zoom-in-95 duration-500">
          <div
            className="w-20 h-20 rounded-full mx-auto mb-5 flex items-center justify-center shadow-lg"
            style={{
              background: `linear-gradient(135deg, ${GREEN}, ${GREEN_BRIGHT})`,
            }}
          >
            <Check className="w-10 h-10 text-white" strokeWidth={3} />
          </div>
          <h1 className="text-2xl font-extrabold mb-2" style={{ color: TEXT_DARK }}>
            Welcome aboard!
          </h1>
          <p className="mb-6" style={{ color: TEXT_MUTED }}>
            Your account was created and you're signed in. Redirecting you to
            your dashboard…
          </p>
          <Loader2 className="w-6 h-6 mx-auto animate-spin" style={{ color: GREEN }} />
        </div>
      </div>
    );
  }

  // -------- Step progress bar (numbered circles + connecting line) --------
  const StepBar = (
    <div className="w-full mb-8">
      <div className="relative">
        {/* Background line */}
        <div
          className="absolute left-0 right-0 top-5 h-[2px]"
          style={{ backgroundColor: "#e5e7eb" }}
        />
        {/* Filled progress line */}
        <div
          className="absolute left-0 top-5 h-[2px] transition-all duration-500"
          style={{
            width: `${(step / (STEPS.length - 1)) * 100}%`,
            background: `linear-gradient(90deg, ${GREEN} 0%, ${GREEN_BRIGHT} 100%)`,
          }}
        />
        <div className="relative flex items-start justify-between">
          {STEPS.map((s, i) => {
            const done = i < step;
            const active = i === step;
            return (
              <div
                key={s.title}
                className="flex flex-col items-center gap-2"
                style={{ width: `${100 / STEPS.length}%` }}
              >
                <div
                  className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold transition-all duration-300 ${
                    active ? "scale-110 shadow-lg" : ""
                  }`}
                  style={{
                    background:
                      active || done
                        ? `linear-gradient(135deg, ${GREEN}, ${GREEN_BRIGHT})`
                        : "#f1f5f9",
                    color: active || done ? "#fff" : "#94a3b8",
                    boxShadow: active ? `0 8px 24px ${GREEN}55` : undefined,
                    border: active || done ? "none" : "1.5px solid #e2e8f0",
                  }}
                >
                  {done ? <Check className="w-4 h-4" strokeWidth={3} /> : i + 1}
                </div>
                <div
                  className="text-[11px] sm:text-xs font-semibold text-center leading-tight transition-colors"
                  style={{
                    color: active ? GREEN : done ? TEXT_DARK : "#94a3b8",
                  }}
                >
                  {s.short}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );

  // -------- Step contents --------
  const Step1 = (
    <div className="space-y-4">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <InlineInput
          id="firstname"
          label="First Name"
          value={form.firstname}
          onChange={(v) => update("firstname", v)}
          icon={<User className="w-5 h-5" />}
          error={err("firstname")}
          success={!!form.firstname && !fieldErrors.firstname}
          autoComplete="given-name"
          placeholder="Ahmed"
        />
        <InlineInput
          id="lastname"
          label="Last Name"
          value={form.lastname}
          onChange={(v) => update("lastname", v)}
          icon={<User className="w-5 h-5" />}
          error={err("lastname")}
          success={!!form.lastname && !fieldErrors.lastname}
          autoComplete="family-name"
          placeholder="Al-Rashed"
        />
      </div>
      <InlineInput
        id="email"
        label="Email Address"
        value={form.email}
        onChange={(v) => update("email", v)}
        type="email"
        icon={<Mail className="w-5 h-5" />}
        error={err("email")}
        success={!!form.email && !fieldErrors.email}
        autoComplete="email"
        placeholder="you@company.com"
        inputMode="email"
      />
      <p className="text-xs ml-1" style={{ color: TEXT_MUTED }}>
        We'll never share your email with anyone else.
      </p>
    </div>
  );

  const Step2 = (
    <div className="space-y-4">
      <InlineInput
        id="password"
        label="Password"
        value={form.password}
        onChange={(v) => update("password", v)}
        type={showPwd ? "text" : "password"}
        icon={<Lock className="w-5 h-5" />}
        error={err("password")}
        success={!!form.password && !fieldErrors.password}
        autoComplete="new-password"
        placeholder="Min 8 characters"
        rightSlot={
          <button
            type="button"
            onClick={() => setShowPwd((s) => !s)}
            className="p-1 rounded-md hover:bg-slate-50 transition-colors"
            style={{ color: GREEN }}
            aria-label={showPwd ? "Hide password" : "Show password"}
          >
            {showPwd ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        }
      />

      {/* Strength meter */}
      <div className="px-1">
        <div className="flex items-center gap-1.5 mb-2">
          {[0, 1, 2, 3].map((i) => (
            <div
              key={i}
              className="h-1.5 flex-1 rounded-full transition-all duration-300"
              style={{
                backgroundColor:
                  form.password && i < strength.score ? strength.color : "#e2e8f0",
              }}
            />
          ))}
        </div>
        <div className="flex items-center justify-between text-[11px]">
          <span style={{ color: TEXT_MUTED }}>Password strength</span>
          <span
            className="font-bold"
            style={{ color: form.password ? strength.color : "#94a3b8" }}
          >
            {form.password ? strength.label : "—"}
          </span>
        </div>
        {form.password && strength.tips.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-1.5">
            {strength.tips.map((t) => (
              <span
                key={t}
                className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px]"
                style={{
                  backgroundColor: `${GREEN}10`,
                  color: GREEN_DARK,
                }}
              >
                <AlertCircle className="w-2.5 h-2.5" />
                {t}
              </span>
            ))}
          </div>
        )}
      </div>

      <InlineInput
        id="confirmPassword"
        label="Confirm Password"
        value={form.confirmPassword}
        onChange={(v) => update("confirmPassword", v)}
        type={showConfirm ? "text" : "password"}
        icon={<Lock className="w-5 h-5" />}
        error={err("confirmPassword")}
        success={
          !!form.confirmPassword &&
          !fieldErrors.confirmPassword &&
          form.password === form.confirmPassword
        }
        autoComplete="new-password"
        placeholder="Repeat password"
        rightSlot={
          <button
            type="button"
            onClick={() => setShowConfirm((s) => !s)}
            className="p-1 rounded-md hover:bg-slate-50 transition-colors"
            style={{ color: GREEN }}
            aria-label={showConfirm ? "Hide password" : "Show password"}
          >
            {showConfirm ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        }
      />
    </div>
  );

  const Step3 = (
    <div className="space-y-4">
      <InlineInput
        id="phonenumber"
        label="Phone Number"
        value={form.phonenumber}
        onChange={(v) => update("phonenumber", v)}
        icon={<Phone className="w-5 h-5" />}
        error={err("phonenumber")}
        success={!!form.phonenumber && !fieldErrors.phonenumber}
        autoComplete="tel"
        placeholder="+966 55 000 0000"
        inputMode="tel"
      />
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <InlineSelect
          id="country"
          label="Country"
          value={form.country}
          onChange={(v) => update("country", v)}
          icon={<Globe className="w-5 h-5" />}
          options={COUNTRY_OPTIONS.map((c) => ({
            value: c.code,
            label: c.name,
          }))}
          error={err("country")}
        />
        <InlineInput
          id="city"
          label="City"
          value={form.city}
          onChange={(v) => update("city", v)}
          icon={<MapPin className="w-5 h-5" />}
          error={err("city")}
          success={!!form.city && !fieldErrors.city}
          autoComplete="address-level2"
          placeholder="Riyadh"
        />
      </div>
      <InlineInput
        id="address1"
        label="Street Address"
        value={form.address1}
        onChange={(v) => update("address1", v)}
        icon={<MapPin className="w-5 h-5" />}
        error={err("address1")}
        success={!!form.address1 && !fieldErrors.address1}
        autoComplete="address-line1"
        placeholder="123 Main St"
      />
    </div>
  );

  const Step4 = (
    <div className="space-y-5">
      <InlineInput
        id="companyname"
        label="Company (optional)"
        value={form.companyname}
        onChange={(v) => update("companyname", v)}
        icon={<Building2 className="w-5 h-5" />}
        autoComplete="organization"
        placeholder="ACME Corp"
      />

      <div
        className="rounded-xl p-4"
        style={{
          backgroundColor: `${GREEN}08`,
          border: `1px solid ${BORDER_GREEN_SOFT}`,
        }}
      >
        <div
          className="text-[11px] font-bold uppercase tracking-wider mb-2"
          style={{ color: GREEN }}
        >
          Review your details
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
          <div style={{ color: TEXT_MUTED }}>
            <span>Name:</span>{" "}
            <span className="font-semibold" style={{ color: TEXT_DARK }}>
              {form.firstname} {form.lastname}
            </span>
          </div>
          <div className="truncate" style={{ color: TEXT_MUTED }}>
            <span>Email:</span>{" "}
            <span className="font-semibold" style={{ color: TEXT_DARK }}>
              {form.email}
            </span>
          </div>
          <div style={{ color: TEXT_MUTED }}>
            <span>Phone:</span>{" "}
            <span className="font-semibold" style={{ color: TEXT_DARK }}>
              {form.phonenumber}
            </span>
          </div>
          <div style={{ color: TEXT_MUTED }}>
            <span>Country:</span>{" "}
            <span className="font-semibold" style={{ color: TEXT_DARK }}>
              {COUNTRY_OPTIONS.find((c) => c.code === form.country)?.name ||
                form.country}
            </span>
          </div>
        </div>
      </div>

      <label
        className="flex items-start gap-3 p-3 rounded-xl border cursor-pointer transition-all"
        style={{
          backgroundColor: form.terms ? `${GREEN}08` : "#fff",
          borderColor: form.terms
            ? BORDER_GREEN
            : err("terms")
              ? "#ef4444"
              : BORDER_GREEN_SOFT,
        }}
      >
        <input
          type="checkbox"
          checked={form.terms}
          onChange={(e) => update("terms", e.target.checked)}
          className="mt-0.5 w-4 h-4"
          style={{ accentColor: GREEN }}
        />
        <span className="text-xs leading-relaxed" style={{ color: TEXT_DARK }}>
          I agree to the{" "}
          <Link
            to="/service-terms"
            target="_blank"
            rel="noopener noreferrer"
            className="font-bold hover:underline"
            style={{ color: GREEN }}
          >
            Service Terms
          </Link>
          ,{" "}
          <Link
            to="/refund-policy"
            target="_blank"
            rel="noopener noreferrer"
            className="font-bold hover:underline"
            style={{ color: GREEN }}
          >
            Refund Policy
          </Link>
          , and{" "}
          <Link
            to="/privacy-center"
            target="_blank"
            rel="noopener noreferrer"
            className="font-bold hover:underline"
            style={{ color: GREEN }}
          >
            Privacy Policy
          </Link>
          .
        </span>
      </label>
      {err("terms") && (
        <div className="flex items-center gap-1 -mt-2 ml-1 text-[11px] text-red-600 font-medium">
          <AlertCircle className="w-3 h-3" />
          {err("terms")}
        </div>
      )}
    </div>
  );

  const CurrentStep =
    step === 0 ? Step1 : step === 1 ? Step2 : step === 2 ? Step3 : Step4;

  const stepTitles = [
    {
      title: "Let's start with your basic information",
      subtitle: "Please enter your name and email address.",
    },
    {
      title: "Secure your account",
      subtitle: "Create a strong password to protect your account.",
    },
    {
      title: "How can we reach you?",
      subtitle: "Your contact details help us deliver services and support.",
    },
    {
      title: "Final details",
      subtitle: "Add your company (optional) and accept our terms.",
    },
  ];

  // -------- Left branding panel (~32%) --------
  const LeftPanel = (
    <aside
      className="relative hidden lg:flex flex-col justify-between p-10 xl:p-12 text-white overflow-hidden"
      style={{
        background: `radial-gradient(900px 600px at 20% 10%, ${GREEN}33 0%, transparent 55%), radial-gradient(700px 500px at 80% 90%, ${GREEN_DARK}55 0%, transparent 60%), linear-gradient(180deg, ${BG_DARK_2} 0%, ${BG_DARK} 100%)`,
      }}
    >
      {/* Logo */}
      <Link to="/" className="relative z-10 inline-flex items-center gap-2">
        <img
          src={brand.logoUrl}
          alt="DoItEasy"
          className="h-11 w-auto brightness-0 invert"
          onError={(e) =>
            ((e.target as HTMLImageElement).style.display = "none")
          }
        />
      </Link>

      {/* Headline + benefits */}
      <div className="relative z-10 max-w-md">
        <h1
          className="text-3xl xl:text-[40px] font-extrabold leading-[1.15] mb-4 tracking-tight"
          style={{ fontFamily: `'Inter', sans-serif` }}
        >
          Create your account
          <br />
          and{" "}
          <span
            style={{
              background: `linear-gradient(90deg, ${GREEN_BRIGHT} 0%, ${GREEN} 100%)`,
              WebkitBackgroundClip: "text",
              WebkitTextFillColor: "transparent",
              backgroundClip: "text",
            }}
          >
            get started today
          </span>
        </h1>
        <p className="text-white/70 mb-8 leading-relaxed text-[15px]">
          Join thousands of customers who trust DoItEasy for fast, secure and
          reliable hosting solutions.
        </p>

        <ul className="space-y-5">
          {[
            {
              icon: Zap,
              title: "Lightning Fast",
              desc: "Deploy your services in seconds, not hours.",
            },
            {
              icon: ShieldCheck,
              title: "Secure & Reliable",
              desc: "Enterprise-grade security with 99.9% uptime.",
            },
            {
              icon: Headphones,
              title: "24/7 Expert Support",
              desc: "Our experts are always here to help you succeed.",
            },
          ].map(({ icon: Icon, title, desc }) => (
            <li key={title} className="flex items-start gap-4">
              <span
                className="w-11 h-11 rounded-full flex items-center justify-center shrink-0 shadow-lg"
                style={{
                  background: `linear-gradient(135deg, ${GREEN} 0%, ${GREEN_BRIGHT} 100%)`,
                  boxShadow: `0 8px 24px ${GREEN}55`,
                }}
              >
                <Icon className="w-5 h-5 text-white" />
              </span>
              <div>
                <div className="font-bold text-white text-[15px]">{title}</div>
                <div className="text-white/60 text-[13px] leading-relaxed">
                  {desc}
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>

      {/* Datacenter line-art illustration */}
      <div className="relative z-10 pt-8">
        <svg
          viewBox="0 0 360 120"
          className="w-full h-auto opacity-60"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          aria-hidden="true"
        >
          <defs>
            <linearGradient id="dcG" x1="0" x2="1" y1="0" y2="0">
              <stop offset="0%" stopColor={GREEN_DARK} stopOpacity="0.2" />
              <stop offset="50%" stopColor={GREEN} stopOpacity="0.9" />
              <stop offset="100%" stopColor={GREEN_DARK} stopOpacity="0.2" />
            </linearGradient>
          </defs>
          {/* ground line */}
          <line
            x1="0"
            y1="110"
            x2="360"
            y2="110"
            stroke="url(#dcG)"
            strokeWidth="1"
          />
          {/* server racks */}
          {[20, 70, 170, 220, 290].map((x, i) => (
            <g key={i} stroke={GREEN} strokeWidth="1.2">
              <rect
                x={x}
                y={40}
                width="48"
                height="70"
                rx="4"
                fill="none"
                opacity="0.7"
              />
              {[0, 1, 2, 3].map((r) => (
                <g key={r}>
                  <line
                    x1={x + 4}
                    y1={50 + r * 14}
                    x2={x + 44}
                    y2={50 + r * 14}
                    opacity="0.5"
                  />
                  <circle
                    cx={x + 8}
                    cy={50 + r * 14 + 3}
                    r="1.5"
                    fill={GREEN}
                    opacity={r === i % 4 ? "1" : "0.3"}
                  />
                </g>
              ))}
            </g>
          ))}
          {/* connecting cables */}
          <path
            d="M 20 40 Q 100 10, 180 40 T 340 40"
            stroke={GREEN}
            strokeWidth="1"
            fill="none"
            strokeDasharray="2 3"
            opacity="0.5"
          />
          {/* cloud */}
          <path
            d="M 130 28 q 0 -12 12 -12 q 6 -8 16 -8 q 12 0 16 10 q 10 0 10 10 q 0 8 -10 8 h -34 q -10 0 -10 -8 z"
            stroke={GREEN}
            strokeWidth="1.2"
            fill="none"
            opacity="0.7"
          />
        </svg>
      </div>
    </aside>
  );

  // -------- Right panel (~68%) --------
  const RightPanel = (
    <main
      className="flex items-center justify-center p-5 md:p-10 xl:p-14"
      style={{
        background:
          "linear-gradient(180deg, #f8fafc 0%, #ffffff 40%, #f1f5f9 100%)",
      }}
    >
      <div className="w-full max-w-[720px]">
        {/* Mobile logo */}
        <div className="lg:hidden mb-6 flex justify-center">
          <Link to="/" className="inline-flex items-center gap-2">
            <img
              src={brand.logoUrl}
              alt="DoItEasy"
              className="h-11 w-auto"
              onError={(e) =>
                ((e.target as HTMLImageElement).style.display = "none")
              }
            />
          </Link>
        </div>

        <div
          className="bg-white p-6 md:p-10"
          style={{
            borderRadius: 28,
            boxShadow:
              "0 24px 60px -20px rgba(14, 138, 32, 0.18), 0 8px 24px -12px rgba(0, 0, 0, 0.08)",
          }}
        >
          {StepBar}

          {/* Step label */}
          <div
            className="text-[12px] font-bold uppercase tracking-wider mb-1"
            style={{ color: GREEN }}
          >
            Step {step + 1} of {STEPS.length}
          </div>
          <h2
            className="text-[22px] md:text-[26px] font-extrabold mb-1 tracking-tight"
            style={{ color: TEXT_DARK, fontFamily: "'Inter', sans-serif" }}
          >
            {stepTitles[step].title}
          </h2>
          <p className="text-sm mb-6" style={{ color: TEXT_MUTED }}>
            {stepTitles[step].subtitle}
          </p>

          {step === 0 && (
            <div className="mb-6">
              <SocialLoginButtons mode="register" dividerLabel="sign up with" />
              <div className="relative my-5">
                <div className="absolute inset-0 flex items-center" aria-hidden="true">
                  <div className="w-full border-t border-slate-200" />
                </div>
                <div className="relative flex justify-center text-xs">
                  <span className="bg-white px-3 uppercase tracking-wider text-slate-400">
                    or with email
                  </span>
                </div>
              </div>
            </div>
          )}

          <form onSubmit={handleSubmit} noValidate>
            <div className="relative overflow-hidden">
              <div
                key={step}
                className={`${
                  direction === "forward"
                    ? "animate-in slide-in-from-right-8"
                    : "animate-in slide-in-from-left-8"
                } fade-in duration-300`}
              >
                {CurrentStep}
              </div>
            </div>

            {error && (
              <div className="mt-5 flex items-start gap-2 p-3 rounded-xl bg-red-50 border border-red-200 text-sm text-red-700 animate-in fade-in slide-in-from-top-2 duration-300">
                <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
                <span>{error}</span>
              </div>
            )}

            {/* Action row: Back (left) + Continue/Submit (right, ~42% wide) */}
            <div className="mt-8 flex items-center justify-between gap-3">
              {step > 0 ? (
                <button
                  type="button"
                  onClick={goBack}
                  disabled={submitting}
                  className="inline-flex items-center gap-1.5 px-5 py-3 rounded-[10px] border text-sm font-semibold transition-all hover:-translate-x-0.5 disabled:opacity-50"
                  style={{
                    borderColor: BORDER_GREEN_SOFT,
                    color: TEXT_DARK,
                    backgroundColor: "#fff",
                  }}
                >
                  <ArrowLeft className="w-4 h-4" />
                  Back
                </button>
              ) : (
                <div />
              )}

              {step < STEPS.length - 1 ? (
                <button
                  type="button"
                  onClick={goNext}
                  className="group inline-flex items-center justify-center gap-2 text-white text-[15px] font-bold transition-all duration-200 hover:-translate-y-0.5 active:translate-y-0"
                  style={{
                    width: "min(45%, 320px)",
                    height: 64,
                    borderRadius: 10,
                    background: `linear-gradient(135deg, ${GREEN} 0%, ${GREEN_BRIGHT} 100%)`,
                    boxShadow: `0 14px 30px ${GREEN}55, inset 0 1px 0 rgba(255,255,255,0.2)`,
                  }}
                >
                  Continue
                  <ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-1" />
                </button>
              ) : (
                <button
                  type="submit"
                  disabled={submitting}
                  className="group inline-flex items-center justify-center gap-2 text-white text-[15px] font-extrabold transition-all duration-200 hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-80 disabled:cursor-not-allowed disabled:hover:translate-y-0"
                  style={{
                    width: "min(45%, 320px)",
                    height: 64,
                    borderRadius: 10,
                    background: `linear-gradient(135deg, ${GREEN_DARK} 0%, ${GREEN} 50%, ${GREEN_BRIGHT} 100%)`,
                    boxShadow: `0 14px 30px ${GREEN}55, inset 0 1px 0 rgba(255,255,255,0.2)`,
                  }}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Creating your account…
                    </>
                  ) : (
                    <>
                      Create My Account
                      <ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-1" />
                    </>
                  )}
                </button>
              )}
            </div>

            {/* Footer inside card */}
            <div
              className="mt-7 pt-5 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs"
              style={{ borderTop: `1px solid ${BORDER_GREEN_SOFT}` }}
            >
              <div
                className="inline-flex items-center gap-1.5"
                style={{ color: TEXT_MUTED }}
              >
                <Shield className="w-3.5 h-3.5" style={{ color: GREEN }} />
                Your account will be created securely in our billing system.
              </div>
              <div
                className="hidden sm:block w-px h-4"
                style={{ backgroundColor: "#e5e7eb" }}
              />
              <div style={{ color: TEXT_MUTED }}>
                Already have an account?{" "}
                <Link
                  to="/login"
                  className="inline-flex items-center gap-1 font-bold hover:underline"
                  style={{ color: GREEN }}
                >
                  <LogIn className="w-3 h-3" />
                  Sign in
                </Link>
              </div>
            </div>
          </form>
        </div>
      </div>
    </main>
  );

  return (
    <div
      className="__reg_root min-h-screen grid"
      style={{
        fontFamily: `'Inter', ${brand.fontBody || "system-ui"}, sans-serif`,
      }}
    >
      <style>{`
        .__reg_root { grid-template-columns: 32% 68%; }
        @media (max-width: 1023px) {
          .__reg_root { grid-template-columns: 1fr !important; }
        }
      `}</style>
      {LeftPanel}
      {RightPanel}
    </div>
  );
}