'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowRight } from 'lucide-react';
import { motion, useReducedMotion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import Mark from '@/components/Mark';

/* ══════════════════════════════════════════════════════════════
   DATA
   ══════════════════════════════════════════════════════════════ */

const BUSINESS_TYPES = [
  'Wholesale / Distribution',
  'Construction / Building Materials',
  'Hardware / General Merchandise',
  'Freight / Logistics / Shipping',
  'Auto Parts / Mechanics',
  'Agriculture / Farm Supplies',
  'Food / Beverage',
  'Textiles / Fashion',
  'Beauty / Cosmetics / Personal Care',
  'Electronics',
  'Pharmaceuticals / Medical Supplies',
  'Import / Export',
  'Manufacturing',
  'Hospitality / Hotels / Restaurants',
  'Professional Services',
  'Freelancer / Contractor',
  'Other',
];

const PRODUCT_OPTIONS = [
  'Smart Contact (voice-to-invoice for my business)',
  'Multilingual Intelligence API (enterprise extraction engine)',
  'Both',
  'Not sure yet',
];

const REFERRAL_SOURCES = [
  'Instagram','TikTok','YouTube','X (Twitter)','A friend or colleague','Web search','Other',
];

const COUNTRIES: [string, string][] = [
  // Alphabetical, no pinning
  ['Afghanistan','af'],['Albania','al'],['Algeria','dz'],['Andorra','ad'],['Angola','ao'],['Antigua and Barbuda','ag'],['Argentina','ar'],['Armenia','am'],['Australia','au'],['Austria','at'],['Azerbaijan','az'],['Bahamas','bs'],['Bahrain','bh'],['Bangladesh','bd'],['Barbados','bb'],['Belarus','by'],['Belgium','be'],['Belize','bz'],['Benin','bj'],['Bhutan','bt'],['Bolivia','bo'],['Bosnia and Herzegovina','ba'],['Botswana','bw'],['Brazil','br'],['Brunei','bn'],['Bulgaria','bg'],['Burkina Faso','bf'],['Burundi','bi'],['Cabo Verde','cv'],['Cambodia','kh'],['Cameroon','cm'],['Canada','ca'],['Central African Republic','cf'],['Chad','td'],['Chile','cl'],['China','cn'],['Colombia','co'],['Comoros','km'],['Congo (Democratic Republic)','cd'],['Congo (Republic)','cg'],['Costa Rica','cr'],['Croatia','hr'],['Cuba','cu'],['Cyprus','cy'],['Czech Republic','cz'],['Denmark','dk'],['Djibouti','dj'],['Dominica','dm'],['Dominican Republic','do'],['Ecuador','ec'],['Egypt','eg'],['El Salvador','sv'],['Equatorial Guinea','gq'],['Eritrea','er'],['Estonia','ee'],['Eswatini','sz'],['Ethiopia','et'],['Fiji','fj'],['Finland','fi'],['France','fr'],['Gabon','ga'],['Gambia','gm'],['Georgia','ge'],['Germany','de'],['Ghana','gh'],['Greece','gr'],['Grenada','gd'],['Guatemala','gt'],['Guinea','gn'],['Guinea-Bissau','gw'],['Guyana','gy'],['Haiti','ht'],['Honduras','hn'],['Hungary','hu'],['Iceland','is'],['India','in'],['Indonesia','id'],['Iran','ir'],['Iraq','iq'],['Ireland','ie'],['Israel','il'],['Italy','it'],['Ivory Coast','ci'],['Jamaica','jm'],['Japan','jp'],['Jordan','jo'],['Kazakhstan','kz'],['Kenya','ke'],['Kiribati','ki'],['Kosovo','xk'],['Kuwait','kw'],['Kyrgyzstan','kg'],['Laos','la'],['Latvia','lv'],['Lebanon','lb'],['Lesotho','ls'],['Liberia','lr'],['Libya','ly'],['Liechtenstein','li'],['Lithuania','lt'],['Luxembourg','lu'],['Madagascar','mg'],['Malawi','mw'],['Malaysia','my'],['Maldives','mv'],['Mali','ml'],['Malta','mt'],['Marshall Islands','mh'],['Mauritania','mr'],['Mauritius','mu'],['Mexico','mx'],['Micronesia','fm'],['Moldova','md'],['Monaco','mc'],['Mongolia','mn'],['Montenegro','me'],['Morocco','ma'],['Mozambique','mz'],['Myanmar','mm'],['Namibia','na'],['Nauru','nr'],['Nepal','np'],['Netherlands','nl'],['New Zealand','nz'],['Nicaragua','ni'],['Niger','ne'],['Nigeria','ng'],['North Korea','kp'],['North Macedonia','mk'],['Norway','no'],['Oman','om'],['Pakistan','pk'],['Palau','pw'],['Palestine','ps'],['Panama','pa'],['Papua New Guinea','pg'],['Paraguay','py'],['Peru','pe'],['Philippines','ph'],['Poland','pl'],['Portugal','pt'],['Qatar','qa'],['Romania','ro'],['Russia','ru'],['Rwanda','rw'],['Saint Kitts and Nevis','kn'],['Saint Lucia','lc'],['Saint Vincent and the Grenadines','vc'],['Samoa','ws'],['San Marino','sm'],['Sao Tome and Principe','st'],['Saudi Arabia','sa'],['Senegal','sn'],['Serbia','rs'],['Seychelles','sc'],['Sierra Leone','sl'],['Singapore','sg'],['Slovakia','sk'],['Slovenia','si'],['Solomon Islands','sb'],['Somalia','so'],['South Africa','za'],['South Korea','kr'],['South Sudan','ss'],['Spain','es'],['Sri Lanka','lk'],['Sudan','sd'],['Suriname','sr'],['Sweden','se'],['Switzerland','ch'],['Syria','sy'],['Taiwan','tw'],['Tajikistan','tj'],['Tanzania','tz'],['Thailand','th'],['Timor-Leste','tl'],['Togo','tg'],['Tonga','to'],['Trinidad and Tobago','tt'],['Tunisia','tn'],['Turkey','tr'],['Turkmenistan','tm'],['Tuvalu','tv'],['Uganda','ug'],['Ukraine','ua'],['United Arab Emirates','ae'],['United Kingdom','gb'],['United States','us'],['Uruguay','uy'],['Uzbekistan','uz'],['Vanuatu','vu'],['Vatican City','va'],['Venezuela','ve'],['Vietnam','vn'],['Yemen','ye'],['Zambia','zm'],['Zimbabwe','zw'],
];

const COUNTRY_ISO: Record<string, string> = Object.fromEntries(COUNTRIES);

/* Dial codes: gist CountryCodes.json (anubhavshrimal), cross-checked against the
   World Atlas country list. Deviations logged in the build report: KZ +7, GY +592,
   DO +1-809 (primary of three NANP codes), XK +383 (ITU; absent from both sources). */
const DIAL: Record<string, string> = { ad: '+376', ae: '+971', af: '+93', ag: '+1-268', al: '+355', am: '+374', ao: '+244', ar: '+54', at: '+43', au: '+61', az: '+994', ba: '+387', bb: '+1-246', bd: '+880', be: '+32', bf: '+226', bg: '+359', bh: '+973', bi: '+257', bj: '+229', bn: '+673', bo: '+591', br: '+55', bs: '+1-242', bt: '+975', bw: '+267', by: '+375', bz: '+501', ca: '+1', cd: '+243', cf: '+236', cg: '+242', ch: '+41', ci: '+225', cl: '+56', cm: '+237', cn: '+86', co: '+57', cr: '+506', cu: '+53', cv: '+238', cy: '+357', cz: '+420', de: '+49', dj: '+253', dk: '+45', dm: '+1-767', do: '+1-809', dz: '+213', ec: '+593', ee: '+372', eg: '+20', er: '+291', es: '+34', et: '+251', fi: '+358', fj: '+679', fm: '+691', fr: '+33', ga: '+241', gb: '+44', gd: '+1-473', ge: '+995', gh: '+233', gm: '+220', gn: '+224', gq: '+240', gr: '+30', gt: '+502', gw: '+245', gy: '+592', hn: '+504', hr: '+385', ht: '+509', hu: '+36', id: '+62', ie: '+353', il: '+972', in: '+91', iq: '+964', ir: '+98', is: '+354', it: '+39', jm: '+1-876', jo: '+962', jp: '+81', ke: '+254', kg: '+996', kh: '+855', ki: '+686', km: '+269', kn: '+1-869', kp: '+850', kr: '+82', kw: '+965', kz: '+7', la: '+856', lb: '+961', lc: '+1-758', li: '+423', lk: '+94', lr: '+231', ls: '+266', lt: '+370', lu: '+352', lv: '+371', ly: '+218', ma: '+212', mc: '+377', md: '+373', me: '+382', mg: '+261', mh: '+692', mk: '+389', ml: '+223', mm: '+95', mn: '+976', mr: '+222', mt: '+356', mu: '+230', mv: '+960', mw: '+265', mx: '+52', my: '+60', mz: '+258', na: '+264', ne: '+227', ng: '+234', ni: '+505', nl: '+31', no: '+47', np: '+977', nr: '+674', nz: '+64', om: '+968', pa: '+507', pe: '+51', pg: '+675', ph: '+63', pk: '+92', pl: '+48', ps: '+970', pt: '+351', pw: '+680', py: '+595', qa: '+974', ro: '+40', rs: '+381', ru: '+7', rw: '+250', sa: '+966', sb: '+677', sc: '+248', sd: '+249', se: '+46', sg: '+65', si: '+386', sk: '+421', sl: '+232', sm: '+378', sn: '+221', so: '+252', sr: '+597', ss: '+211', st: '+239', sv: '+503', sy: '+963', sz: '+268', td: '+235', tg: '+228', th: '+66', tj: '+992', tl: '+670', tm: '+993', tn: '+216', to: '+676', tr: '+90', tt: '+1-868', tv: '+688', tw: '+886', tz: '+255', ua: '+380', ug: '+256', us: '+1', uy: '+598', uz: '+998', va: '+379', vc: '+1-784', ve: '+58', vn: '+84', vu: '+678', ws: '+685', xk: '+383', ye: '+967', za: '+27', zm: '+260', zw: '+263', };


/* ══════════════════════════════════════════════════════════════
   ILLUSTRATION — the approved voice-to-invoice composition
   ══════════════════════════════════════════════════════════════ */

function WaitlistVisual() {
  const reduce = useReducedMotion();
  const bars = [5,10,17,8,20,12,16,6,14,21,9,18,7,13,19,10,15,8];
  return (
    <div className="relative hidden lg:flex min-h-[560px] items-center justify-center" aria-hidden="true">
      {/* Ambient washes — static */}
      <div className="absolute w-72 h-72 rounded-full bg-blue/[0.08] blur-[100px] top-6 right-10" />
      <div className="absolute w-44 h-44 rounded-full bg-coral/[0.05] blur-[80px] bottom-10 left-6" />

      {/* Voice note card */}
      <motion.div
        className="absolute top-[12%] left-[8%]"
        animate={reduce ? undefined : { y: [0, -8, 0] }}
        transition={{ duration: 5.5, repeat: Infinity, ease: 'easeInOut' }}
      >
        <div className="bg-elevated/90 backdrop-blur-xl border border-white/[0.08] rounded-xl px-5 py-4 w-[240px] shadow-xl shadow-navy-deep/40">
          <div className="flex items-center justify-between mb-3">
            <div className="font-mono text-[8px] text-white/35 uppercase tracking-[0.15em]">Voice Note</div>
            <div className="flex items-center gap-1.5">
              <span className="w-[5px] h-[5px] bg-blue rounded-full animate-pulse-soft" />
              <span className="font-mono text-[8px] text-blue/70">Received</span>
            </div>
          </div>
          <div className="flex items-center justify-center gap-[2px] h-10 mb-2">
            {bars.map((h, i) => (
              <div key={i} className="w-[2.5px] rounded-full animate-wave"
                style={{
                  height: `${h}px`,
                  animationDelay: `${i * 0.07}s`,
                  background: i < 6 ? 'rgba(25,156,244,0.7)' : i < 12 ? 'rgba(25,156,244,0.5)' : 'rgba(25,156,244,0.3)',
                }} />
            ))}
          </div>
          <div className="flex items-center justify-between">
            <span className="font-mono text-[9px] text-white/25">0:19</span>
            <span className="font-mono text-[8px] text-white/20 px-1.5 py-0.5 rounded bg-white/[0.04]">EN</span>
          </div>
        </div>
      </motion.div>

      {/* Invoice card */}
      <motion.div
        className="absolute bottom-[10%] right-[6%]"
        animate={reduce ? undefined : { y: [0, -10, 0] }}
        transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut', delay: 0.8 }}
      >
        <div className="bg-elevated/90 backdrop-blur-xl border border-white/[0.08] rounded-xl w-[264px] shadow-2xl shadow-navy-deep/50 overflow-hidden">
          <div className="px-4 py-2.5 border-b border-white/[0.06] flex justify-between items-center">
            <span className="font-mono text-[9px] text-white/35 tracking-wide">MAR-0051</span>
            <span className="text-[7px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-md bg-verify/15 text-verify border border-verify/20">Verified</span>
          </div>
          <div className="px-4 py-3">
            <div className="flex justify-between items-baseline py-1 border-b border-white/[0.04]">
              <div>
                <div className="text-[10px] text-white/55 font-medium">Portland Cement 94lb</div>
                <div className="text-[8px] text-white/25 font-mono">bags {"×"} 50 @ $14.00</div>
              </div>
              <span className="text-[11px] text-white/70 font-mono font-medium">$700.00</span>
            </div>
            <div className="flex justify-between items-baseline py-1 border-b border-white/[0.04]">
              <div>
                <div className="text-[10px] text-white/55 font-medium">{"Plywood 1/2\u201d CDX"}</div>
                <div className="text-[8px] text-white/25 font-mono">{"4\u00d78 sheets \u00d7 24 @ $42.00"}</div>
              </div>
              <span className="text-[11px] text-white/70 font-mono font-medium">$1,008.00</span>
            </div>
            <div className="flex justify-between items-center pt-2.5 mt-1 border-t border-white/[0.08]">
              <span className="text-[10px] text-white/60 font-bold">Total</span>
              <span className="text-[15px] text-white font-bold font-mono">$1,708.00</span>
            </div>
          </div>
          <div className="px-4 pb-3">
            <div className="w-full py-2 rounded-lg bg-verify/15 border border-verify/20 text-center text-[10px] text-verify font-bold tracking-wide">
              Pay
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}

/* ══════════════════════════════════════════════════════════════
   COMPONENT
   ══════════════════════════════════════════════════════════════ */

type BtnPhase = 'idle' | 'morphing' | 'success' | 'holding' | 'error';

export default function WaitlistForm() {
  const router = useRouter();
  const [btnPhase, setBtnPhase] = useState<BtnPhase>('idle');
  const [error, setError] = useState('');
  const [valErrors, setValErrors] = useState<Record<string, string>>({});
  const [selectedCountry, setSelectedCountry] = useState('');

  // Country combobox state
  const [countryQuery, setCountryQuery] = useState('');
  const [countryOpen, setCountryOpen] = useState(false);
  const [hl, setHl] = useState(0);
  const listRef = useRef<HTMLDivElement>(null);

  const phoneRef = useRef<HTMLInputElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);
  const apiResultRef = useRef<{ ok: boolean; error?: string } | null>(null);

  // Dial selector state: country identity drives the code, which is the
  // correct disambiguation model for shared codes (+1 NANP, +44, +7).
  const [dialIso, setDialIso] = useState('us');
  const [dialOpen, setDialOpen] = useState(false);
  const [dialQuery, setDialQuery] = useState('');
  const [dialHl, setDialHl] = useState(0);
  const dialListRef = useRef<HTMLDivElement>(null);

  // Sync country selection to the dial code and flag
  const handleCountryChange = useCallback((countryName: string) => {
    setSelectedCountry(countryName);
    const iso = COUNTRY_ISO[countryName];
    if (iso && DIAL[iso]) setDialIso(iso);
  }, []);

  const dq = dialQuery.trim().toLowerCase();
  const dialFiltered = dq === ''
    ? COUNTRIES
    : COUNTRIES.filter(([name, iso]) => name.toLowerCase().includes(dq) || DIAL[iso].replace('-', '').includes(dq.replace(/[^\d+]/g, '')) && dq.replace(/[^\d+]/g, '') !== '');

  const pickDial = useCallback((iso: string) => {
    setDialIso(iso);
    setDialOpen(false);
    setDialQuery('');
    setDialHl(0);
    phoneRef.current?.focus();
  }, []);

  function onDialKey(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === 'ArrowDown') { e.preventDefault(); setDialHl(h => Math.min(h + 1, dialFiltered.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setDialHl(h => Math.max(h - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); if (dialFiltered[dialHl]) pickDial(dialFiltered[dialHl][1]); }
    else if (e.key === 'Escape') { setDialOpen(false); }
  }

  useEffect(() => {
    const el = dialListRef.current?.children[dialHl] as HTMLElement | undefined;
    el?.scrollIntoView({ block: 'nearest' });
  }, [dialHl, dialOpen]);

  // Combobox helpers: empty query, or a completed selection, shows the full
  // list so scroll-and-select stays available alongside type-ahead.
  const q = countryQuery.trim().toLowerCase();
  const showAll = q === '' || !!COUNTRY_ISO[countryQuery.trim()];
  const filtered = showAll ? COUNTRIES : COUNTRIES.filter(([name]) => name.toLowerCase().includes(q));

  const pickCountry = useCallback((name: string) => {
    setCountryQuery(name);
    setCountryOpen(false);
    setHl(0);
    handleCountryChange(name);
  }, [handleCountryChange]);

  function onCountryInput(v: string) {
    setCountryQuery(v);
    setCountryOpen(true);
    setHl(0);
    if (COUNTRY_ISO[v.trim()]) handleCountryChange(v.trim());
  }

  function onCountryKey(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === 'ArrowDown') { e.preventDefault(); if (!countryOpen) { setCountryOpen(true); return; } setHl(h => Math.min(h + 1, filtered.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setHl(h => Math.max(h - 1, 0)); }
    else if (e.key === 'Enter') { if (countryOpen && filtered[hl]) { e.preventDefault(); pickCountry(filtered[hl][0]); } }
    else if (e.key === 'Escape') { setCountryOpen(false); }
    else if (e.key === 'Tab') { setCountryOpen(false); }
  }

  // Keep the highlighted option in view while arrowing
  useEffect(() => {
    const el = listRef.current?.children[hl] as HTMLElement | undefined;
    el?.scrollIntoView({ block: 'nearest' });
  }, [hl, countryOpen]);

  // ── Submit handler ──
  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (btnPhase !== 'idle') return;

    setError('');
    setValErrors({});
    apiResultRef.current = null;

    const fd = new FormData(e.currentTarget);
    const national = (fd.get('phone') as string || '').trim();
    const phone = national ? `${DIAL[dialIso]} ${national}` : '';
    const businessName = (fd.get('businessName') as string || '').trim();
    const country = (fd.get('country') as string || '').trim();
    const businessType = (fd.get('businessType') as string || '').trim();

    // Validate required
    const errs: Record<string, string> = {};
    if (!country || !COUNTRY_ISO[country]) errs.country = 'Select a country from the list.';
    if (!phone || phone.replace(/\D/g, '').length < 7) errs.phone = 'Enter a valid phone number.';
    if (!businessName) errs.businessName = 'Business name is required.';
    if (!businessType) errs.businessType = 'Business type is required.';
    if (Object.keys(errs).length) { setValErrors(errs); return; }

    const payload = {
      phone, businessName, businessType, country,
      productInterest: (fd.get('productInterest') as string) || '',
      email: (fd.get('email') as string) || '',
      referralSource: (fd.get('referralSource') as string) || '',
    };

    // Start animation + API call in parallel
    setBtnPhase('morphing');

    // API call
    const apiPromise = (async () => {
      try {
        const res = await fetch('/.netlify/functions/waitlist-submit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (res.ok) {
          apiResultRef.current = { ok: true };
        } else {
          const d = await res.json().catch(() => ({}));
          apiResultRef.current = { ok: false, error: d.error || 'Something went wrong. Please try again.' };
        }
      } catch {
        apiResultRef.current = { ok: false, error: 'Something went wrong. Please try again.' };
      }
    })();

    // Animation timeline
    // Phase 1: morphing (400ms after text fade 150ms)
    await sleep(550);

    // Phase 2: checkmark draw
    setBtnPhase('success');
    await sleep(500);

    // Phase 3: hold — wait for API if not done
    setBtnPhase('holding');
    await apiPromise;

    const result = apiResultRef.current as { ok: boolean; error?: string } | null;
    if (result?.ok) {
      // Hold checkmark for 2.3s then redirect
      await sleep(2300);
      router.push('/');
    } else {
      // Reverse animation
      setBtnPhase('error');
      setError(result?.error || 'Something went wrong. Please try again.');
      await sleep(400);
      setBtnPhase('idle');
    }
  }

  // ── Styles ──
  const inp = "w-full bg-white/[0.04] border border-white/[0.08] rounded-lg px-4 py-3 text-[15px] text-white placeholder-white/25 focus:outline-none focus:border-[rgba(25,156,244,0.4)] focus:bg-white/[0.06] transition-all duration-200";
  const sel = "w-full bg-elevated border border-white/[0.08] rounded-lg px-4 py-3 text-[15px] text-white/50 focus:outline-none focus:border-[rgba(25,156,244,0.4)] transition-all duration-200 appearance-none cursor-pointer";
  const lbl = "block text-[13px] font-medium text-white/50 mb-1.5 tracking-tight";
  const req = <span className="text-coral/70 ml-0.5">*</span>;
  const chevron = <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"><svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M3 4.5L6 7.5L9 4.5" stroke="rgba(255,255,255,0.3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div>;

  // ── Button rendering ──
  const isAnimating = btnPhase !== 'idle';
  const isCircle = btnPhase === 'morphing' || btnPhase === 'success' || btnPhase === 'holding';
  const isGreen = btnPhase === 'success' || btnPhase === 'holding';
  const showCheck = btnPhase === 'success' || btnPhase === 'holding';

  return (
    <>
      <div className="min-h-screen bg-navy flex flex-col relative overflow-hidden">
        {/* Ambient backdrop — static washes and grid, per the approved page */}
        <div className="absolute w-[700px] h-[700px] rounded-full opacity-[0.08] pointer-events-none" style={{ background: 'radial-gradient(circle, rgba(25,156,244,0.5) 0%, transparent 65%)', top: '-15%', left: '-10%' }} />
        <div className="absolute w-[500px] h-[500px] rounded-full opacity-[0.06] pointer-events-none" style={{ background: 'radial-gradient(circle, rgba(248,112,92,0.5) 0%, transparent 65%)', bottom: '-5%', right: '-5%' }} />
        <div className="absolute inset-0 bg-[radial-gradient(rgba(255,255,255,0.02)_1px,transparent_1px)] bg-[length:24px_24px] pointer-events-none" />

        {/* Nav */}
        <nav className="relative z-10 border-b border-white/[0.06]">
          <div className="max-w-[1200px] mx-auto px-6 flex items-center h-[72px]">
            <a href="/" className="flex items-center gap-2.5 hover:opacity-80 transition-opacity">
              <Mark dark />
              <span className="font-display text-[15px] font-extrabold text-white uppercase tracking-[0.18em]">MARIDIAN</span>
            </a>
          </div>
        </nav>

        {/* Body */}
        <div className="relative z-10 flex-1">
          <div className="max-w-[1200px] mx-auto px-6 pt-14 pb-24 grid lg:grid-cols-[minmax(0,520px)_1fr] gap-16 items-center">
            <div className="w-full max-w-[520px]">
              <h1 className="font-display text-[clamp(32px,5vw,44px)] font-extrabold text-white leading-[1.05] tracking-[-0.03em] mb-10">
                Join the Waitlist
              </h1>

              <form onSubmit={onSubmit} noValidate className="flex flex-col gap-5">

                {/* 1. Country (required) — type-ahead combobox with full-list scroll */}
                <div>
                  <label htmlFor="country" className={lbl}>Country{req}</label>
                  <div className="relative">
                    <input
                      id="country"
                      name="country"
                      type="text"
                      role="combobox"
                      aria-expanded={countryOpen}
                      aria-controls="country-listbox"
                      aria-autocomplete="list"
                      autoComplete="off"
                      placeholder="Select or type your country"
                      value={countryQuery}
                      onChange={(e) => onCountryInput(e.target.value)}
                      onFocus={() => setCountryOpen(true)}
                      onBlur={() => setTimeout(() => setCountryOpen(false), 120)}
                      onKeyDown={onCountryKey}
                      className={inp}
                    />
                    <button
                      type="button"
                      tabIndex={-1}
                      aria-label="Show all countries"
                      onMouseDown={(e) => { e.preventDefault(); setCountryOpen(o => !o); (document.getElementById('country') as HTMLInputElement | null)?.focus(); }}
                      className="absolute right-0 top-0 h-full px-3 flex items-center cursor-pointer"
                    >
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" className={`transition-transform duration-200 ${countryOpen ? 'rotate-180' : ''}`}><path d="M3 4.5L6 7.5L9 4.5" stroke="rgba(255,255,255,0.35)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </button>
                    {countryOpen && filtered.length > 0 && (
                      <div
                        id="country-listbox"
                        role="listbox"
                        ref={listRef}
                        className="absolute z-30 mt-2 w-full max-h-[264px] overflow-y-auto rounded-lg border border-white/10 bg-elevated shadow-lg py-1"
                      >
                        {filtered.map(([name], i) => (
                          <div
                            key={name}
                            role="option"
                            aria-selected={name === selectedCountry}
                            onMouseDown={(e) => { e.preventDefault(); pickCountry(name); }}
                            onMouseEnter={() => setHl(i)}
                            className={`px-4 py-2.5 text-[14px] cursor-pointer transition-colors duration-100 ${i === hl ? 'bg-white/[0.08] text-white' : 'text-white/75'}`}
                          >
                            {name}
                          </div>
                        ))}
                      </div>
                    )}
                    {countryOpen && filtered.length === 0 && (
                      <div className="absolute z-30 mt-2 w-full rounded-lg border border-white/10 bg-elevated shadow-lg px-4 py-3 text-[13px] text-white/40">
                        No matching country
                      </div>
                    )}
                  </div>
                  {valErrors.country && <p className="text-coral text-[12px] mt-1.5 font-mono">{valErrors.country}</p>}
                </div>

                {/* 2. Phone (required) — full global dial codes, flag first, code right, shared-code aware */}
                <div>
                  <label htmlFor="phone" className={lbl}>Your number{req}</label>
                  <div className="relative flex">
                    <button
                      type="button"
                      aria-haspopup="listbox"
                      aria-expanded={dialOpen}
                      aria-label="Select dial code"
                      onMouseDown={(e) => { e.preventDefault(); setDialOpen(o => !o); setDialQuery(''); setDialHl(0); }}
                      className="flex items-center gap-2 px-3 bg-white/[0.04] border border-white/[0.08] border-r-0 rounded-l-lg cursor-pointer hover:bg-white/[0.07] transition-colors duration-200"
                    >
                      <img src={`https://flagcdn.com/${dialIso}.svg`} alt="" aria-hidden="true" className="h-[13px] w-auto rounded-[2px] ring-1 ring-white/15" />
                      <span className="font-mono text-[13px] text-white/60 whitespace-nowrap">{DIAL[dialIso]}</span>
                      <svg width="10" height="10" viewBox="0 0 12 12" fill="none" className={`transition-transform duration-200 ${dialOpen ? 'rotate-180' : ''}`}><path d="M3 4.5L6 7.5L9 4.5" stroke="rgba(255,255,255,0.35)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </button>
                    <input ref={phoneRef} id="phone" name="phone" type="tel" placeholder="(555) 000-0000" className={`${inp} rounded-l-none`} autoComplete="tel" />
                    {dialOpen && (
                      <div className="absolute z-30 left-0 top-[calc(100%+8px)] w-[320px] max-w-full rounded-lg border border-white/10 bg-elevated shadow-lg overflow-hidden">
                        <input
                          autoFocus
                          value={dialQuery}
                          onChange={(e) => { setDialQuery(e.target.value); setDialHl(0); }}
                          onKeyDown={onDialKey}
                          onBlur={() => setTimeout(() => setDialOpen(false), 120)}
                          placeholder="Search country or code"
                          aria-label="Search dial codes"
                          className="w-full px-3.5 py-2.5 bg-white/[0.05] border-b border-white/10 text-[13px] text-white placeholder-white/25 focus:outline-none"
                        />
                        <div ref={dialListRef} role="listbox" className="max-h-[240px] overflow-y-auto py-1">
                          {dialFiltered.map(([name, iso], i) => (
                            <div
                              key={iso}
                              role="option"
                              aria-selected={iso === dialIso}
                              onMouseDown={(e) => { e.preventDefault(); pickDial(iso); }}
                              onMouseEnter={() => setDialHl(i)}
                              className={`flex items-center gap-2.5 px-3.5 py-2 cursor-pointer transition-colors duration-100 ${i === dialHl ? 'bg-white/[0.08]' : ''}`}
                            >
                              <img src={`https://flagcdn.com/${iso}.svg`} alt="" aria-hidden="true" className="h-[12px] w-auto rounded-[2px] ring-1 ring-white/15 shrink-0" />
                              <span className="flex-1 truncate text-[13px] text-white/80">{name}</span>
                              <span className="font-mono text-[12px] text-white/45 whitespace-nowrap">{DIAL[iso]}</span>
                            </div>
                          ))}
                          {dialFiltered.length === 0 && (
                            <div className="px-3.5 py-3 text-[13px] text-white/40">No matching country</div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                  {valErrors.phone && <p className="text-coral text-[12px] mt-1.5 font-mono">{valErrors.phone}</p>}
                </div>

                {/* 3. Business Name (required) */}
                <div>
                  <label htmlFor="businessName" className={lbl}>Business name{req}</label>
                  <input id="businessName" name="businessName" type="text" placeholder="e.g. Kariakoo Textiles Ltd" className={inp} autoComplete="organization" />
                  {valErrors.businessName && <p className="text-coral text-[12px] mt-1.5 font-mono">{valErrors.businessName}</p>}
                </div>

                {/* 4. Business Type (required) */}
                <div>
                  <label htmlFor="businessType" className={lbl}>Business type{req}</label>
                  <div className="relative">
                    <select id="businessType" name="businessType" defaultValue="" className={sel}>
                      <option value="" disabled>Select your business type</option>
                      {BUSINESS_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                    {chevron}
                  </div>
                  {valErrors.businessType && <p className="text-coral text-[12px] mt-1.5 font-mono">{valErrors.businessType}</p>}
                </div>

                {/* 5. Product Interest (optional) */}
                <div>
                  <label htmlFor="productInterest" className={lbl}>Which product interests you?</label>
                  <div className="relative">
                    <select id="productInterest" name="productInterest" defaultValue="" className={sel}>
                      <option value="" disabled>Select one</option>
                      {PRODUCT_OPTIONS.map(p => <option key={p} value={p}>{p}</option>)}
                    </select>
                    {chevron}
                  </div>
                </div>

                {/* 6. Email (optional) */}
                <div>
                  <label htmlFor="email" className={lbl}>Email</label>
                  <input id="email" name="email" type="email" placeholder="you@company.com" className={inp} autoComplete="email" />
                </div>

                {/* 7. Referral Source (optional) */}
                <div>
                  <label htmlFor="referralSource" className={lbl}>How did you hear about us?</label>
                  <div className="relative">
                    <select id="referralSource" name="referralSource" defaultValue="" className={sel}>
                      <option value="" disabled>Select one</option>
                      {REFERRAL_SOURCES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                    {chevron}
                  </div>
                </div>

                {/* Error */}
                {error && <div className="text-coral text-[13px] font-mono p-3 bg-coral/[0.06] border border-coral/20 rounded-lg">{error}</div>}

                {/* Submit — animated "Enter" button */}
                <div className="flex justify-center mt-3">
                  <button
                    ref={btnRef}
                    type="submit"
                    disabled={isAnimating}
                    className="relative overflow-hidden disabled:cursor-default"
                    style={{
                      width: isCircle ? '52px' : '100%',
                      height: '52px',
                      borderRadius: isCircle ? '50%' : '14px',
                      backgroundColor: isGreen ? '#2ECC71' : '#FFFFFF',
                      transition: 'width 400ms cubic-bezier(0.22,1,0.36,1), border-radius 400ms cubic-bezier(0.22,1,0.36,1), background-color 400ms cubic-bezier(0.22,1,0.36,1)',
                    }}
                  >
                    {/* Text — fades when animating */}
                    <span
                      className="absolute inset-0 flex items-center justify-center gap-2 font-display font-bold text-[15px] text-[#0D0F1A] tracking-tight"
                      style={{
                        opacity: isAnimating ? 0 : 1,
                        transition: 'opacity 150ms ease-out',
                      }}
                    >
                      Enter <ArrowRight size={16} />
                    </span>

                    {/* Checkmark SVG — draws when success */}
                    <span className="absolute inset-0 flex items-center justify-center">
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                        <path
                          d="M5 13l4 4L19 7"
                          stroke="white"
                          strokeWidth="2.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          style={{
                            strokeDasharray: 30,
                            strokeDashoffset: showCheck ? 0 : 30,
                            transition: showCheck ? 'stroke-dashoffset 500ms ease-out' : 'none',
                          }}
                        />
                      </svg>
                    </span>
                  </button>
                </div>
              </form>
            </div>

            {/* The approved page illustration */}
            <WaitlistVisual />
          </div>
        </div>

        {/* Footer */}
        <footer className="relative z-10 border-t border-white/[0.04] py-8">
          <div className="max-w-[520px] mx-auto px-6 text-center">
            <div className="flex justify-center gap-6 mb-4">
              <a href="mailto:davis@maridian.co" className="text-[12px] text-white/35 hover:text-white transition-colors">Contact</a>
              <a href="/privacy" className="text-[12px] text-white/35 hover:text-white transition-colors">Privacy</a>
              <a href="/terms" className="text-[12px] text-white/35 hover:text-white transition-colors">Terms</a>
            </div>
            <div className="text-[11px] text-white/20 leading-relaxed">
              Maridian generates invoices and payment instructions. We do not hold, route, or settle funds. Licensed Payment Service Providers handle all financial transactions.<br />&copy; 2026 MARIDIAN, INC. All rights reserved.
            </div>
          </div>
        </footer>
      </div>

      <style jsx global>{`
        select option { background: #1B2562; color: rgba(255,255,255,0.8); }
      `}</style>
    </>
  );
}

/* Utility */
function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }
