"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowRight, Loader2, AlertTriangle, CheckCircle,
  Gauge, Bot, Activity, Mail, RotateCcw, ChevronLeft,
} from "lucide-react";
import { getAuditResultPath } from "@/lib/audit/redirect-helpers";

// ─── Constants ────────────────────────────────────────────────────────────────

const FREE_EMAIL_DOMAINS = new Set([
  "gmail.com", "googlemail.com",
  "yahoo.com", "yahoo.co.uk", "yahoo.fr", "yahoo.de", "yahoo.es", "yahoo.it",
  "yahoo.ca", "yahoo.com.au", "ymail.com",
  "hotmail.com", "hotmail.co.uk", "hotmail.fr", "hotmail.de",
  "outlook.com", "outlook.co.uk", "live.com", "msn.com",
  "icloud.com", "me.com", "mac.com",
  "aol.com", "mail.com",
  "protonmail.com", "proton.me", "pm.me",
  "gmx.com", "gmx.net", "gmx.de",
]);

const FEATURES = [
  {
    icon: Gauge,
    title: "Technical SEO Score",
    body: "Instant grading on crawlability, metadata, content structure, and on-page signals — with a ranked list of what to fix first.",
  },
  {
    icon: Bot,
    title: "AI Visibility Preview",
    body: "See how AI search engines interpret your site. Unlock full attribution by connecting the meSEO Site Tag.",
  },
  {
    icon: Activity,
    title: "Behavioral Signals",
    body: "Bounce rate, session duration, and conversion data tied to each finding. Available when you install the Site Tag.",
  },
];

const RESEND_COOLDOWN_S = 60;

// ─── Helpers ──────────────────────────────────────────────────────────────────

function isFreeEmail(email: string): boolean {
  const domain = email.split("@")[1]?.toLowerCase() ?? "";
  return FREE_EMAIL_DOMAINS.has(domain);
}

function formatPhone(raw: string): string {
  const digits = raw.replace(/\D/g, "");
  if (digits.length === 10) return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
  if (digits.length === 11 && digits[0] === "1")
    return `+1 (${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7)}`;
  return raw;
}

function trackEvent(event: string): void {
  fetch("/api/public-audit/track", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ auditId: null, event }),
  }).catch(() => {/* non-fatal */});
}

// ─── Field component ──────────────────────────────────────────────────────────

function Field({
  id, label, type = "text", placeholder, value, onChange, onBlur,
  autoComplete, disabled, error, hint,
}: {
  id: string; label: string; type?: string; placeholder: string;
  value: string; onChange: (v: string) => void; onBlur?: () => void;
  autoComplete?: string; disabled?: boolean; error?: string | null; hint?: string;
}) {
  return (
    <div>
      <label htmlFor={id} className="block text-sm font-semibold text-slate-700 mb-1.5">
        {label}
      </label>
      <input
        id={id} type={type} placeholder={placeholder} value={value}
        onChange={(e) => onChange(e.target.value)} onBlur={onBlur}
        autoComplete={autoComplete} disabled={disabled}
        className={`w-full px-4 py-3 rounded-xl border bg-slate-50 text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:border-transparent disabled:opacity-50 text-base transition-colors ${
          error ? "border-red-300 focus:ring-red-400" : "border-slate-200 focus:ring-slate-900"
        }`}
      />
      {error && (
        <p className="mt-1.5 text-xs text-red-600 flex items-center gap-1">
          <AlertTriangle className="w-3 h-3 shrink-0" />
          {error}
        </p>
      )}
      {!error && hint && <p className="mt-1 text-xs text-slate-400">{hint}</p>}
    </div>
  );
}

// ─── OTP Step ─────────────────────────────────────────────────────────────────

interface OtpFormProps {
  maskedEmail: string;
  formData: {
    firstName: string; lastName: string; email: string;
    companyName: string; phoneNumber: string; websiteUrl: string;
  };
  onSuccess: (auditId: string) => void;
  onBack: () => void;
}

function OtpForm({ maskedEmail, formData, onSuccess, onBack }: OtpFormProps) {
  const [code, setCode] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [cooldown, setCooldown] = useState(RESEND_COOLDOWN_S);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
    const timer = setInterval(() => {
      setCooldown((s) => (s <= 1 ? 0 : s - 1));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  async function handleVerify(e: React.FormEvent) {
    e.preventDefault();
    const clean = code.replace(/\D/g, "");
    if (clean.length !== 6) {
      setError("Please enter the 6-digit code.");
      return;
    }
    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/public-audit/verify", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ email: formData.email, code: clean, formData }),
      });
      const data = await res.json() as {
        auditId?: string; error?: string; remaining?: number; tooManyAttempts?: boolean;
      };

      if (!res.ok) {
        if (data.tooManyAttempts) {
          setError("Too many incorrect attempts. Please request a new code.");
        } else {
          const remaining = data.remaining;
          setError(
            data.error ??
            (remaining != null ? `Incorrect code — ${remaining} attempt${remaining === 1 ? "" : "s"} left.` : "Incorrect code."),
          );
        }
        setLoading(false);
        return;
      }

      if (data.auditId) {
        trackEvent("audit_submitted");
        onSuccess(data.auditId);
      }
    } catch {
      setError("Network error. Please check your connection and try again.");
      setLoading(false);
    }
  }

  async function handleResend() {
    if (cooldown > 0 || resending) return;
    setResending(true);
    setError(null);
    setCode("");

    try {
      const res = await fetch("/api/public-audit/resend-code", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ email: formData.email }),
      });
      const data = await res.json() as { sent?: boolean; error?: string; waitSec?: number };

      if (!res.ok) {
        setError(data.error ?? "Failed to resend. Try again shortly.");
      } else {
        setCooldown(RESEND_COOLDOWN_S);
      }
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setResending(false);
    }
  }

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="text-center">
        <div className="w-12 h-12 rounded-full bg-indigo-50 flex items-center justify-center mx-auto mb-3">
          <Mail className="w-6 h-6 text-indigo-600" />
        </div>
        <h2 className="text-lg font-bold text-slate-900 mb-1">Check your email</h2>
        <p className="text-sm text-slate-500">
          We sent a 6-digit code to <span className="font-semibold text-slate-700">{maskedEmail}</span>
        </p>
      </div>

      <form onSubmit={handleVerify} className="space-y-4">
        <div>
          <label htmlFor="otp-code" className="block text-sm font-semibold text-slate-700 mb-1.5">
            Verification code
          </label>
          <input
            ref={inputRef}
            id="otp-code"
            type="text"
            inputMode="numeric"
            pattern="[0-9]*"
            autoComplete="one-time-code"
            placeholder="000000"
            maxLength={6}
            value={code}
            onChange={(e) => {
              setCode(e.target.value.replace(/\D/g, "").slice(0, 6));
              setError(null);
            }}
            disabled={loading}
            className={`w-full px-4 py-4 rounded-xl border bg-slate-50 text-slate-900 placeholder-slate-300 focus:outline-none focus:ring-2 focus:border-transparent disabled:opacity-50 text-3xl font-mono font-bold tracking-[0.5em] text-center transition-colors ${
              error ? "border-red-300 focus:ring-red-400" : "border-slate-200 focus:ring-slate-900"
            }`}
          />
          {error && (
            <p className="mt-1.5 text-xs text-red-600 flex items-center gap-1">
              <AlertTriangle className="w-3 h-3 shrink-0" />
              {error}
            </p>
          )}
        </div>

        <button
          type="submit"
          disabled={loading || code.replace(/\D/g, "").length !== 6}
          className="w-full flex items-center justify-center gap-2 bg-slate-900 hover:bg-slate-700 disabled:opacity-60 text-white text-base font-bold px-6 py-4 rounded-xl transition-colors"
        >
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              Verifying…
            </>
          ) : (
            <>
              Verify and run audit
              <ArrowRight className="w-4 h-4" />
            </>
          )}
        </button>
      </form>

      {/* Resend + back */}
      <div className="flex items-center justify-between pt-1">
        <button
          type="button"
          onClick={onBack}
          className="flex items-center gap-1 text-sm text-slate-400 hover:text-slate-600 transition-colors"
        >
          <ChevronLeft className="w-4 h-4" />
          Change email
        </button>

        <button
          type="button"
          onClick={handleResend}
          disabled={cooldown > 0 || resending}
          className="flex items-center gap-1.5 text-sm font-medium text-indigo-600 hover:text-indigo-800 disabled:text-slate-400 disabled:cursor-not-allowed transition-colors"
        >
          {resending ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
          ) : (
            <RotateCcw className="w-3.5 h-3.5" />
          )}
          {cooldown > 0 ? `Resend in ${cooldown}s` : "Resend code"}
        </button>
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

type Step = "form" | "otp" | "done";

interface PendingFormData {
  firstName: string; lastName: string; email: string;
  companyName: string; phoneNumber: string; websiteUrl: string;
}

export default function PublicAuditLanding() {
  const router = useRouter();

  const [step, setStep] = useState<Step>("form");
  const [maskedEmail, setMaskedEmail] = useState("");
  const [pendingFormData, setPendingFormData] = useState<PendingFormData | null>(null);

  // Form fields
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [companyName, setCompanyName] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [websiteUrl, setWebsiteUrl] = useState("");

  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [globalError, setGlobalError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  function setFieldError(field: string, msg: string | null) {
    setFieldErrors((prev) => {
      if (msg === null) { const next = { ...prev }; delete next[field]; return next; }
      return { ...prev, [field]: msg };
    });
  }

  function validateEmailField() {
    if (!email) return;
    if (!email.includes("@")) { setFieldError("email", "Please enter a valid email address."); return; }
    if (isFreeEmail(email)) { setFieldError("email", "Please use your business email address."); return; }
    setFieldError("email", null);
  }

  function handlePhoneBlur() {
    if (!phoneNumber) return;
    const digits = phoneNumber.replace(/\D/g, "");
    if (digits.length < 7) { setFieldError("phoneNumber", "Please enter a valid phone number."); return; }
    setFieldError("phoneNumber", null);
    setPhoneNumber(formatPhone(phoneNumber));
  }

  function validateAll(): boolean {
    const errors: Record<string, string> = {};
    if (!firstName.trim()) errors.firstName = "Required.";
    if (!lastName.trim()) errors.lastName = "Required.";
    if (!email.trim()) { errors.email = "Required."; }
    else if (!email.includes("@")) { errors.email = "Please enter a valid email address."; }
    else if (isFreeEmail(email)) { errors.email = "Please use your business email address."; }
    if (!companyName.trim()) errors.companyName = "Required.";
    if (!phoneNumber.trim()) { errors.phoneNumber = "Required."; }
    else if (phoneNumber.replace(/\D/g, "").length < 7) { errors.phoneNumber = "Please enter a valid phone number."; }
    if (!websiteUrl.trim()) errors.websiteUrl = "Required.";
    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setGlobalError(null);
    if (!validateAll()) return;
    setLoading(true);

    try {
      const res = await fetch("/api/public-audit", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ firstName, lastName, email, companyName, phoneNumber, websiteUrl }),
      });

      const data = await res.json() as {
        auditId?: string; statusUrl?: string; leadId?: string; error?: string;
        existingAudit?: boolean; resultUrl?: string; status?: string;
        verificationRequired?: boolean; maskedEmail?: string;
        formData?: PendingFormData;
      };

      if (!res.ok) {
        const msg = data.error ?? "Something went wrong. Please try again.";
        if (msg.toLowerCase().includes("business email")) { setFieldError("email", msg); }
        else if (msg.toLowerCase().includes("phone")) { setFieldError("phoneNumber", msg); }
        else if (msg.toLowerCase().includes("url") || msg.toLowerCase().includes("domain")) { setFieldError("websiteUrl", msg); }
        else { setGlobalError(msg); }
        setLoading(false);
        return;
      }

      // Returning visitor
      if (data.existingAudit && data.auditId) {
        const suffix = data.status === "completed" ? "?welcome=1" : "";
        router.push(`${getAuditResultPath(data.auditId)}${suffix}`);
        return;
      }

      // New visitor — OTP required
      if (data.verificationRequired && data.maskedEmail && data.formData) {
        setMaskedEmail(data.maskedEmail);
        setPendingFormData(data.formData);
        setLoading(false);
        setStep("otp");
        return;
      }

      // Bypass active or direct-success path
      if (data.auditId && data.statusUrl) {
        window.location.href = getAuditResultPath(data.auditId);
        return;
      }

      setGlobalError("Unexpected response. Please try again.");
      setLoading(false);
    } catch {
      setGlobalError("Network error. Please check your connection and try again.");
      setLoading(false);
    }
  }

  function handleVerifySuccess(auditId: string) {
    setStep("done");
    router.push(getAuditResultPath(auditId));
  }

  function handleBack() {
    setStep("form");
    setGlobalError(null);
  }

  return (
    <div className="flex flex-col">
      {/* ── Hero + Form ── */}
      <div
        className="flex flex-col items-center justify-center px-4 py-12 sm:py-16"
        style={{
          backgroundImage:
            "radial-gradient(ellipse 80% 50% at 50% 0%, rgba(99,102,241,0.07) 0%, transparent 70%)",
        }}
      >
        <div className="w-full max-w-xl">
          {/* Eyebrow */}
          <p className="text-center text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-6">
            Free · No signup · Results in 2–4 min
          </p>

          {/* Headline */}
          <h1 className="text-5xl sm:text-6xl font-black text-slate-900 tracking-tight leading-[1.08] text-center mb-5">
            See what AI search<br className="hidden sm:block" /> thinks of your site
          </h1>

          {/* Subhead */}
          <p className="text-[17px] text-slate-500 text-center max-w-sm mx-auto leading-relaxed mb-10">
            Get your technical SEO score, key findings, and a prioritized action plan — instantly.
          </p>

          {/* Form card */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 sm:p-8">
            {step === "done" ? (
              <div className="text-center py-6">
                <CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-3" />
                <p className="text-lg font-bold text-slate-900 mb-1">Audit started!</p>
                <p className="text-sm text-slate-500">Redirecting to your results…</p>
              </div>
            ) : step === "otp" && pendingFormData ? (
              <OtpForm
                maskedEmail={maskedEmail}
                formData={pendingFormData}
                onSuccess={handleVerifySuccess}
                onBack={handleBack}
              />
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid grid-cols-2 gap-3">
                  <Field
                    id="audit-first-name" label="First name" placeholder="Jane"
                    value={firstName} onChange={setFirstName}
                    autoComplete="given-name" disabled={loading} error={fieldErrors.firstName}
                  />
                  <Field
                    id="audit-last-name" label="Last name" placeholder="Smith"
                    value={lastName} onChange={setLastName}
                    autoComplete="family-name" disabled={loading} error={fieldErrors.lastName}
                  />
                </div>

                <Field
                  id="audit-email" label="Business email" type="email"
                  placeholder="jane@company.com" value={email}
                  onChange={(v) => { setEmail(v); setFieldError("email", null); }}
                  onBlur={validateEmailField} autoComplete="email"
                  disabled={loading} error={fieldErrors.email}
                />

                <Field
                  id="audit-company" label="Company name" placeholder="Acme Corp"
                  value={companyName} onChange={setCompanyName}
                  autoComplete="organization" disabled={loading} error={fieldErrors.companyName}
                />

                <Field
                  id="audit-phone" label="Phone number" type="tel"
                  placeholder="+1 (555) 000-0000" value={phoneNumber}
                  onChange={(v) => { setPhoneNumber(v); setFieldError("phoneNumber", null); }}
                  onBlur={handlePhoneBlur} autoComplete="tel"
                  disabled={loading} error={fieldErrors.phoneNumber}
                />

                <Field
                  id="audit-url" label="Website URL" placeholder="yoursite.com"
                  value={websiteUrl} onChange={setWebsiteUrl}
                  autoComplete="url" disabled={loading} error={fieldErrors.websiteUrl}
                />

                {globalError && (
                  <div className="flex items-start gap-2 text-sm text-red-600 bg-red-50 border border-red-100 rounded-xl px-4 py-3">
                    <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
                    <span>{globalError}</span>
                  </div>
                )}

                <button
                  type="submit" disabled={loading}
                  className="w-full flex items-center justify-center gap-2 bg-slate-900 hover:bg-slate-700 disabled:opacity-60 text-white text-base font-bold px-6 py-4 rounded-xl transition-colors"
                >
                  {loading ? (
                    <><Loader2 className="w-4 h-4 animate-spin" />Sending code…</>
                  ) : (
                    <>Run Free AI Search Audit<ArrowRight className="w-4 h-4" /></>
                  )}
                </button>

                <p className="text-center text-xs text-slate-400">
                  Your audit is private. No spam, no SDR calls without your invitation.
                </p>
              </form>
            )}
          </div>

          {/* Demo link */}
          <p className="text-center text-sm text-slate-400 mt-6">
            Want continuous monitoring?{" "}
            <a
              href="https://meseoapp.com/book-demo"
              target="_blank" rel="noopener noreferrer"
              className="text-slate-700 hover:text-slate-900 font-semibold underline underline-offset-2"
            >
              Book a demo →
            </a>
          </p>
        </div>
      </div>

      {/* ── Feature row ── */}
      <div className="border-t border-slate-200 bg-white/80">
        <div className="max-w-4xl mx-auto px-4 py-12 sm:py-16">
          <p className="text-center text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-10">
            What you&apos;ll see in your report
          </p>
          <div className="grid sm:grid-cols-3 gap-8">
            {FEATURES.map(({ icon: Icon, title, body }) => (
              <div key={title} className="flex flex-col gap-3">
                <div className="w-10 h-10 rounded-xl bg-white border border-slate-200 shadow-sm flex items-center justify-center shrink-0">
                  <Icon className="w-5 h-5 text-slate-700" />
                </div>
                <div>
                  <p className="text-[15px] font-bold text-slate-900 mb-1">{title}</p>
                  <p className="text-sm text-slate-500 leading-relaxed">{body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
