'use client';

import { Suspense, useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import SocialAuthButtons from '@/components/auth/SocialAuthButtons';
import { createClient } from '@/lib/supabase/client';

function safeNext(next: string | null): string {
  if (!next) return '/forum';
  if (!next.startsWith('/') || next.startsWith('//')) return '/forum';
  return next;
}

function ForumRegisterInner() {
  const router = useRouter();
  const params = useSearchParams();
  const next = safeNext(params.get('next'));
  const supabase = createClient();

  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    supabase.auth.getUser().then(({ data: { user } }) => {
      if (user) router.replace(next);
    });
  }, [next, router, supabase]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setInfo(null);

    if (!fullName.trim()) return setError('Please enter your name.');
    if (!email) return setError('Email is required.');
    if (password.length < 6) return setError('Password must be at least 6 characters.');
    if (password !== confirm) return setError('Passwords do not match.');

    setLoading(true);
    // Check first: if this email is already in our subscriber pool (existing
    // newsletter reader), we send them a magic-link login instead of creating
    // a new account — they already 'exist' to us. They can then set a
    // password from /account if they want.
    let knownSubscriber = false;
    try {
      const probe = await fetch(`/api/auth/lookup-email?email=${encodeURIComponent(email)}`);
      if (probe.ok) {
        const j = await probe.json();
        knownSubscriber = !!j.known;
      }
    } catch { /* probe failure → fall through to signUp */ }

    if (knownSubscriber) {
      const { error: otpErr } = await supabase.auth.signInWithOtp({
        email,
        options: {
          emailRedirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}`,
          shouldCreateUser: true,
          data: { full_name: fullName.trim() },
        },
      });
      setLoading(false);
      if (otpErr) { setError(otpErr.message); return; }
      setInfo("Welcome back! You're already on our list. We sent a one-time login link to your inbox — click it to sign in. You can set a password from your account afterwards.");
      return;
    }

    const { data, error: signUpError } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: { full_name: fullName.trim(), avatar_url: '' },
        emailRedirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}`,
      },
    });
    setLoading(false);

    if (signUpError) {
      setError(signUpError.message);
      return;
    }

    // If email confirmation is off (auto-confirm), session is already live.
    if (data?.session) {
      window.location.href = next;
      return;
    }

    // Confirmation required path.
    setInfo('Check your email for a confirmation link to finish signing up.');
  };

  return (
    <>
      <Header />
      <main className="min-h-screen bg-gradient-to-b from-[#F8FAFC] via-[#F8FAFC] to-[#F8FAFC]">
        <div className="max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 lg:grid-cols-[1fr_440px] gap-10 items-start">
          {/* Left rail — what membership gets you */}
          <aside className="hidden lg:block">
            <div className="text-[10px] uppercase tracking-widest text-[#1D4ED8] font-mono mb-3">Membership</div>
            <h1 className="font-heading text-[#0F172A] text-4xl xl:text-5xl font-bold leading-tight mb-4">
              Join AV Beat
            </h1>
            <p className="text-[#cbd5e1] text-base leading-relaxed mb-6 max-w-md">
              One free account for the broadcast engineering community — covering NAB, IBC, and the people behind every signal chain.
            </p>
            <ul className="space-y-3 text-sm text-[#d1d5db] max-w-md">
              {[
                ["💬", "Join the broadcast engineering forum", "Threads, replies, and a verified industry community"],
                ["📧", "Manage your newsletter preferences", "Pick which categories — Commercial TV, Radio, Industry News, SMPTE — you want delivered"],
                ["🔖", "Save articles to read later", "Bookmark coverage, build your own reading list"],
                ["🔔", "Get notified of replies and follow-ups", "Email you when someone responds to a thread you're in"],
              ].map(([icon, title, desc]) => (
                <li key={String(title)} className="flex gap-3 items-start">
                  <span className="text-xl leading-none flex-shrink-0">{icon}</span>
                  <div>
                    <div className="font-semibold text-[#0F172A]">{title}</div>
                    <div className="text-xs text-[#9ca3af] mt-0.5">{desc}</div>
                  </div>
                </li>
              ))}
            </ul>
            <div className="mt-6 text-[11px] text-[#666] leading-relaxed max-w-md border-t border-[#DCE6F2] pt-4">
              <strong className="text-[#888]">PR firms &amp; contributors:</strong> a separate contributor application is required to submit press releases.
              {" "}
              <Link href="/about/advertise" className="text-[#1D4ED8] hover:underline">Contact us</Link> if you represent a manufacturer or agency.
            </div>
          </aside>

          {/* Mobile-only hero (collapsed copy) */}
          <div className="lg:hidden text-center mb-2">
            <h1 className="font-heading text-[#0F172A] text-2xl font-bold">Join AV Beat</h1>
            <p className="text-[#888] font-body text-sm mt-1">
              One account for the forum, newsletter preferences, and saved articles.
            </p>
          </div>

          <form
            onSubmit={handleSubmit}
            className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-6 space-y-4 shadow-2xl"
          >
            <div className="hidden lg:block mb-2">
              <div className="text-[10px] uppercase tracking-widest text-[#1D4ED8] font-mono mb-1">Create your account</div>
              <div className="text-[#888] text-xs">Takes 30 seconds. Free, no card needed.</div>
            </div>
            {error && (
              <div className="bg-[#2a0a0a] border border-[#1D4ED8] text-[#ff8a8a] font-body text-sm px-3 py-2 rounded">
                {error}
              </div>
            )}
            {info && (
              <div className="bg-[#0a1f2a] border border-[#1e6c8c] text-[#7adbff] font-body text-sm px-3 py-2 rounded">
                {info}
              </div>
            )}
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Full Name
              </label>
              <input
                type="text"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                autoComplete="name"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Email
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoComplete="email"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Password
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete="new-password"
                required
                minLength={6}
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Confirm Password
              </label>
              <input
                type="password"
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                autoComplete="new-password"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#1D4ED8] hover:bg-[#1E3A8A] disabled:opacity-50 text-white font-body font-semibold text-sm px-5 py-3 rounded-lg transition-colors"
            >
              {loading ? 'Creating account…' : 'Create Free Account'}
            </button>
            <p className="text-[10px] text-[#666] leading-relaxed text-center px-2">
              By creating an account you agree to our{' '}
              <Link href="/terms" className="text-[#888] hover:text-[#1D4ED8] underline">terms</Link>
              {' '}and{' '}
              <Link href="/privacy" className="text-[#888] hover:text-[#1D4ED8] underline">privacy policy</Link>.
              We&rsquo;ll never sell your email.
            </p>
            <SocialAuthButtons next={next} />
            <div className="text-center text-xs font-body text-[#888] pt-2 border-t border-[#DCE6F2]">
              Already have an account?{' '}
              <Link
                href={`/forum/login?next=${encodeURIComponent(next)}`}
                className="text-[#1D4ED8] hover:underline font-semibold"
              >
                Sign in
              </Link>
            </div>
          </form>
        </div>
      </main>
      <Footer />
    </>
  );
}

export default function ForumRegisterPage() {
  return (
    <Suspense fallback={null}>
      <ForumRegisterInner />
    </Suspense>
  );
}
