'use client';

import { useState, useRef, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { AppToast } from '@/app/components/AppToast';
import type { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { ProgressSpinner } from 'primereact/progressspinner';
import { Image } from 'primereact/image';
import { useApi } from '@/hooks/useApi';
import { useSettingsApi } from '@/hooks/useSettingsApi';
import { useAuthStore } from '@/store/authStore';

interface RegisterResponse {
  msg?: string;
  message?: string;
  token?: string;
  data?: unknown;
  /** بعض الـ endpoints ترجع الحالة في `key` بدل `status` */
  key?: string;
  status?: string;
}

interface City {
  id: string;
  name: string;
}

interface CountryFromApi {
  id: number;
  name: string;
  key?: string;
  code?: string;
  image?: string;
}

interface SettingsBannerResponse {
  key?: string;
  data?: string;
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                             */
/* ------------------------------------------------------------------ */
/** عرض ثواني العدّاد كـ M:SS */
function formatMmSs(totalSeconds: number): string {
  const m = Math.floor(totalSeconds / 60);
  const sec = totalSeconds % 60;
  return `${m}:${sec.toString().padStart(2, '0')}`;
}

/** أرقام فقط، بدون صفر في البداية، حتى 9 أرقام */
function normalizeLocalPhoneDigits(raw: string): string {
  const digitsOnly = raw.replace(/\D/g, '');
  const withoutLeadingZeros = digitsOnly.replace(/^0+/, '');
  return withoutLeadingZeros.slice(0, 9);
}

function formatDialCode(country: CountryFromApi): string {
  const raw = String(country.code ?? country.key ?? '').replace(/\D/g, '');
  if (!raw) return '';
  return `+${raw}`;
}

function LegalHtmlBlock({ content }: { content: string }) {
  const trimmed = content.trim();
  if (!trimmed) {
    return <p className="text-sm text-slate-500">لا يوجد محتوى متاح حالياً.</p>;
  }
  const looksHtml = /<\/?[a-z][\s\S]*>/i.test(trimmed);
  if (looksHtml) {
    return (
      <div
        className="legal-html prose prose-sm max-w-none text-slate-700 text-sm leading-relaxed [&_a]:text-blue-700 [&_img]:max-w-full"
        dir="rtl"
        dangerouslySetInnerHTML={{ __html: trimmed }}
      />
    );
  }
  return <p className="whitespace-pre-wrap text-sm text-slate-700 leading-relaxed">{trimmed}</p>;
}

/* ------------------------------------------------------------------ */
/*  PhoneField component                                                */
/* ------------------------------------------------------------------ */
function PhoneField({
  required = false,
  countries,
  loading,
}: {
  required?: boolean;
  countries: CountryFromApi[];
  loading: boolean;
}) {
  const [phone, setPhone] = useState('');
  const [dial, setDial] = useState('');

  const options = useMemo(() => {
    return countries.map((c) => ({
      country: c,
      value: formatDialCode(c),
      label: `${c.name} (${formatDialCode(c)})`,
    })).filter((o) => o.value);
  }, [countries]);

  useEffect(() => {
    if (options.length === 0) return;
    setDial((prev) => {
      if (prev && options.some((o) => o.value === prev)) return prev;
      return options[0].value;
    });
  }, [options]);

  return (
    <div className="flex" dir="ltr">
      <div className="relative flex-shrink-0">
        <select
          name="country_code"
          required={required}
          value={dial}
          disabled={loading || options.length === 0}
          onChange={(e) => setDial(e.target.value)}
          className="h-full px-2 py-3 rounded-s-xl border border-e-0 border-slate-200 text-sm bg-slate-50 focus:outline-none focus:border-blue-400 cursor-pointer appearance-none text-slate-700 font-medium disabled:opacity-60 disabled:cursor-not-allowed"
          style={{ minWidth: '120px', paddingLeft: '20px' }}
        >
          {loading && (
            <option value="">جاري تحميل الدول...</option>
          )}
          {!loading &&
            options.map((o) => (
              <option key={o.country.id} value={o.value}>
                {o.label}
              </option>
            ))}
        </select>
        <i className="ri-arrow-down-s-line absolute left-1 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none text-xs"></i>
      </div>
      <input
        name="phone"
        required={required}
        type="tel"
        inputMode="numeric"
        autoComplete="tel-national"
        placeholder="5XXXXXXXX"
        maxLength={9}
        value={phone}
        onChange={(e) => setPhone(normalizeLocalPhoneDigits(e.target.value))}
        className="flex-1 px-4 py-3 rounded-e-xl border border-slate-200 text-sm focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all bg-white"
      />
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  ImageUpload component                                               */
/* ------------------------------------------------------------------ */
function ImageUpload({ name }: { name: string }) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (preview) URL.revokeObjectURL(preview);
    setPreview(URL.createObjectURL(file));
    setFileName(file.name);
  };

  const handleRemove = () => {
    if (preview) URL.revokeObjectURL(preview);
    setPreview(null);
    setFileName(null);
    if (inputRef.current) inputRef.current.value = '';
  };

  return (
    <div>
      <input
        ref={inputRef}
        name={name}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleChange}
      />
      {!preview ? (
        <button
          type="button"
          onClick={() => inputRef.current?.click()}
          className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl border-2 border-dashed border-slate-300 text-slate-500 hover:border-blue-400 hover:text-blue-600 hover:bg-blue-50 transition-all text-sm font-medium cursor-pointer"
        >
          <i className="ri-image-add-line text-xl"></i>
          <span>اختر صورة</span>
        </button>
      ) : (
        <div className="flex items-start gap-3">
          <div className="relative flex-shrink-0">
            <Image
              src={preview}
              alt={fileName || 'preview'}
              preview
              imageStyle={{
                objectFit: 'cover',
                borderRadius: '12px',
                width: '96px',
                height: '96px',
                display: 'block',
              }}
            />
            <button
              type="button"
              onClick={handleRemove}
              className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center text-xs shadow hover:bg-red-600 transition-colors z-10"
              title="إزالة الصورة"
            >
              <i className="ri-close-line"></i>
            </button>
          </div>
          <div className="flex flex-col justify-center min-w-0">
            <p className="text-xs font-medium text-slate-600 truncate max-w-[140px]">{fileName}</p>
            <button
              type="button"
              onClick={() => inputRef.current?.click()}
              className="mt-1 text-xs text-blue-600 hover:underline text-right"
            >
              تغيير الصورة
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Page                                                                */
/* ------------------------------------------------------------------ */
export default function RegisterPage() {
  const [selectedCity, setSelectedCity] = useState<string>('');
  const [cities, setCities] = useState<City[]>([]);
  const [citiesLoading, setCitiesLoading] = useState<boolean>(false);
  const [countries, setCountries] = useState<CountryFromApi[]>([]);
  const [countriesLoading, setCountriesLoading] = useState(false);

  const [termsDialogVisible, setTermsDialogVisible] = useState(false);
  const [privacyDialogVisible, setPrivacyDialogVisible] = useState(false);
  const [termsBody, setTermsBody] = useState('');
  const [privacyBody, setPrivacyBody] = useState('');
  const [termsLoading, setTermsLoading] = useState(false);
  const [privacyLoading, setPrivacyLoading] = useState(false);

  const [otpVisible, setOtpVisible] = useState(false);
  const [otpDigits, setOtpDigits] = useState(['', '', '', '']);
  const [pendingPhone, setPendingPhone] = useState('');
  const [pendingCountryCode, setPendingCountryCode] = useState('+966');
  const [successVisible, setSuccessVisible] = useState(false);
  /** ثوانٍ متبقية قبل السماح بإعادة إرسال الرمز (يبدأ من 60 عند فتح النافذة أو بعد إعادة إرسال ناجحة). */
  const [otpResendSeconds, setOtpResendSeconds] = useState(0);
  const otpRefs = useRef<(HTMLInputElement | null)[]>([null, null, null, null]);

  const { country_code: storeCountryCode, device_id: storeDeviceId, device_type: storeDeviceType } = useAuthStore();

  const router = useRouter();
  const toast = useRef<Toast>(null);
  const formRef = useRef<HTMLFormElement>(null);
  const { loading, request, lastError } = useApi<RegisterResponse, FormData>();
  const { loading: otpLoading, request: otpRequest, lastError: otpLastError } = useApi<RegisterResponse, Record<string, string>>();
  const { loading: resendLoading, request: resendRequest, lastError: resendLastError } = useApi<
    RegisterResponse,
    Record<string, string | undefined>
  >();
  const { request: settingsRequest } = useSettingsApi();

  async function loadTermsContent() {
    setTermsLoading(true);
    const json = (await settingsRequest('/terms', { skipAuth: true })) as SettingsBannerResponse | null;
    setTermsLoading(false);
    const raw = json?.data;
    setTermsBody(typeof raw === 'string' ? raw : '');
  }

  async function loadPrivacyContent() {
    setPrivacyLoading(true);
    const json = (await settingsRequest('/privacy', { skipAuth: true })) as SettingsBannerResponse | null;
    setPrivacyLoading(false);
    const raw = json?.data;
    setPrivacyBody(typeof raw === 'string' ? raw : '');
  }

  /* ── Fetch countries (country_code للجوال) ───────────────────────── */
  useEffect(() => {
    const fetchCountries = async () => {
      setCountriesLoading(true);
      const json = (await settingsRequest('/countries', { skipAuth: true })) as {
        data?: CountryFromApi[];
      } | null;
      if (json?.data && Array.isArray(json.data)) {
        setCountries(json.data);
      } else {
        toast.current?.show({
          severity: 'warn',
          summary: 'تنبيه',
          detail: 'تعذّر تحميل قائمة الدول',
          life: 4000,
        });
      }
      setCountriesLoading(false);
    };
    fetchCountries();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* ── Fetch cities on mount ──────────────────────────────────────── */
  useEffect(() => {
    const fetchCities = async () => {
      setCitiesLoading(true);

      const json = await settingsRequest('/cities', { skipAuth: true });

      if (json) {
        let list: City[] = [];
        if (Array.isArray(json)) list = json;
        else if (Array.isArray((json as { data: City[] }).data)) list = (json as { data: City[] }).data;
        else if (Array.isArray(((json as { data: { data: City[] } }).data as { data: City[] })?.data))
          list = ((json as { data: { data: City[] } }).data as { data: City[] }).data;
        setCities(list);
      } else {
        toast.current?.show({
          severity: 'warn',
          summary: 'تنبيه',
          detail: 'تعذّر تحميل قائمة المدن',
          life: 4000,
        });
      }

      setCitiesLoading(false);
    };
    fetchCities();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* ── عدّاد إعادة إرسال رمز OTP (دقيقة بعد استلام / إعادة إرسال الرمز) ── */
  useEffect(() => {
    if (!otpVisible) {
      setOtpResendSeconds(0);
      return;
    }
    setOtpResendSeconds(60);
    const id = window.setInterval(() => {
      setOtpResendSeconds((s) => Math.max(0, s - 1));
    }, 1000);
    return () => window.clearInterval(id);
  }, [otpVisible]);

  const showError = (msg: string) =>
    toast.current?.show({ severity: 'error', summary: 'خطأ', detail: msg, life: 4000 });

  const showSuccess = (msg: string) =>
    toast.current?.show({ severity: 'success', summary: 'تم', detail: msg, life: 3000 });

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;

    if (!selectedCity) {
      showError('يرجى اختيار المدينة');
      return;
    }

    const textarea = form.querySelector('textarea');
    if (textarea && textarea.value.length > 500) {
      showError('الحد الأقصى للنص 500 حرف');
      return;
    }

    const formData = new FormData(form);
    const termsChecked = (form.querySelector('[name="is_terms"]') as HTMLInputElement)?.checked;
    formData.set('is_terms', termsChecked ? '1' : '0');

    const normalizedPhone = normalizeLocalPhoneDigits(String(formData.get('phone') || '').trim());
    formData.set('phone', normalizedPhone);

    const result = await request('/auth/register', {
      method: 'POST',
      body: formData as unknown as FormData,
      headers: {},
      skipAuth: true,
    });

    if (!result) {
      showError(lastError.current || 'حدث خطأ أثناء التسجيل، يرجى المحاولة مجددًا');
      return;
    }

    const registerOutcome = result.key ?? result.status;

    if (registerOutcome === 'success') {
      showSuccess(result.msg || result.message || 'تم التسجيل بنجاح!');
      setTimeout(() => {
        router.push('/');
      }, 1200);
    } else if (registerOutcome === 'needActive') {
      showSuccess(result.msg || result.message || 'تم إرسال رمز التحقق إلى جوالك');
      const phone = normalizedPhone;
      const countryCode = (formData.get('country_code') as string) || '+966';
      setPendingPhone(phone);
      setPendingCountryCode(countryCode);
      setOtpDigits(['', '', '', '']);
      setOtpVisible(true);
      // focus أول خانة بعد فتح الـ dialog
      setTimeout(() => {
        otpRefs.current[0]?.focus();
      }, 300);
    } else {
      showError(result.msg || result.message || 'حدث خطأ أثناء التسجيل، يرجى المحاولة مجددًا');
    }
  }

  async function handleOtpSubmit() {
    const code = otpDigits.join('');
    if (code.length < 4) {
      showError('يرجى إدخال رمز التحقق كاملاً');
      return;
    }

    const result = await otpRequest('/auth/verify-phone', {
      method: 'POST',
      body: {
        code,
        phone: pendingPhone,
        country_code: storeCountryCode || pendingCountryCode,
        device_id: storeDeviceId || '',
        device_type: storeDeviceType,
      },
      skipAuth: true,
    });

    if (!result) {
      showError(otpLastError.current || 'فشل التحقق من الرمز');
      return;
    }

    if ((result.key ?? result.status) === 'needApprove') {
      setOtpVisible(false);
      setSuccessVisible(true);
      setTimeout(() => {
        router.push('/');
      }, 3000);
    } else {
      showError(result.msg || result.message || 'رمز التحقق غير صحيح');
    }
  }

  async function handleResendCode() {
    if (otpResendSeconds > 0 || resendLoading || !pendingPhone) return;

    const result = await resendRequest('/auth/resend-code', {
      method: 'POST',
      body: {
        phone: pendingPhone,
        country_code: storeCountryCode || pendingCountryCode,
        device_id: storeDeviceId || '',
        device_type: storeDeviceType,
      },
      skipAuth: true,
    });

    if (!result) {
      showError(resendLastError.current || 'تعذّر إعادة إرسال الرمز');
      return;
    }

    const ok =
      result.key === 'success' ||
      String(result.status ?? '').toLowerCase() === 'success';

    if (ok) {
      showSuccess(result.msg || result.message || 'تم إرسال رمز جديد إلى جوالك');
      setOtpResendSeconds(60);
    } else {
      showError(result.msg || result.message || 'تعذّر إعادة إرسال الرمز');
    }
  }

  const inputCls =
    'w-full px-4 py-3 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all bg-white';

  /* ── OTP Dialog Header ─────────────────────────────────────────── */
  const otpDialogHeader = (
    <div className="flex flex-col items-center gap-3 pt-2" dir="rtl">
      <div className="w-16 h-16 bg-blue-100 rounded-2xl flex items-center justify-center">
        <i className="ri-shield-keyhole-line text-blue-600 text-3xl"></i>
      </div>
      <div className="text-center">
        <h2 className="text-xl font-bold text-slate-800">التحقق من الجوال</h2>
        <p className="text-sm text-slate-500 mt-1">
          أدخل رمز التحقق المرسل إلى{' '}
          <span className="font-medium text-slate-700" dir="ltr">
            {pendingCountryCode} {pendingPhone}
          </span>
        </p>
      </div>
    </div>
  );

  /* ── Success Dialog Header ─────────────────────────────────────── */
  const successDialogHeader = (
    <div className="flex flex-col items-center gap-3 pt-2" dir="rtl">
      <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center">
        <i className="ri-checkbox-circle-fill text-green-500 text-5xl"></i>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-slate-50" dir="rtl">
      <AppToast ref={toast} />

      {/* Loading overlay */}
      {loading && (
        <div
          className="fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-4"
          style={{ background: 'rgba(15,23,42,0.55)', backdropFilter: 'blur(4px)' }}
        >
          <ProgressSpinner
            style={{ width: '60px', height: '60px' }}
            strokeWidth="4"
            animationDuration=".8s"
          />
          <p className="text-white font-semibold text-lg">جاري إرسال البيانات...</p>
        </div>
      )}

      {/* ── Header ─────────────────────────────────────────────── */}
      <header style={{ background: '#0F172A' }} className="sticky top-0 z-50 shadow-lg">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <Link href="/" className="flex items-center gap-3">
              <div
                className="w-10 h-10 rounded-xl flex items-center justify-center"
                style={{ background: '#1E3A8A' }}
              >
                <i className="ri-bus-2-fill text-white text-xl"></i>
              </div>
              <span className="text-2xl font-bold text-white">باصاتي</span>
            </Link>
            <Link
              href="/"
              className="flex items-center gap-2 text-slate-300 hover:text-blue-400 transition-colors font-medium"
            >
              <i className="ri-arrow-right-line"></i>
              <span>العودة للرئيسية</span>
            </Link>
          </div>
        </div>
      </header>

      {/* ── Hero ───────────────────────────────────────────────── */}
      <section
        className="py-16"
        style={{ background: 'linear-gradient(135deg, #0F172A 0%, #1E3A8A 50%, #0F172A 100%)' }}
      >
        <div className="max-w-3xl mx-auto px-4 text-center">
          <div
            className="inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium mb-6"
            style={{
              background: 'rgba(59,130,246,0.2)',
              color: '#93C5FD',
              border: '1px solid rgba(59,130,246,0.3)',
            }}
          >
            <i className="ri-time-line"></i>
            <span>التسجيل المبكر — قبل انطلاق التطبيق</span>
          </div>
          <h1 className="text-4xl lg:text-5xl font-bold text-white mb-4">
            سجّل الآن وكن من الأوائل
          </h1>
          <p className="text-lg" style={{ color: '#94a3b8' }}>
            سجّل بيانات شركتك الآن وسنتواصل معك فور إطلاق المنصة
          </p>
        </div>
      </section>

      {/* ── Form Section ───────────────────────────────────────── */}
      <section className="py-16">
        <div className="max-w-2xl mx-auto px-4">
          <div className="bg-white rounded-3xl shadow-xl overflow-hidden">

            {/* ── FORM ─────────────────────────────────────────── */}
            <form
              ref={formRef}
              onSubmit={handleSubmit}
              className="p-8 space-y-6"
              encType="multipart/form-data"
            >

              {/* صورة الشركة */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      صورة الشركة
                    </label>
                    <ImageUpload name="image" />
                  </div>

                  {/* اسم الشركة */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      اسم الشركة <span className="text-red-500">*</span>
                    </label>
                    <input
                      name="name"
                      required
                      type="text"
                      placeholder="شركة النقل الذهبي"
                      className={inputCls}
                    />
                  </div>

                  {/* رقم الجوال */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      رقم الجوال <span className="text-red-500">*</span>
                    </label>
                    <PhoneField required countries={countries} loading={countriesLoading} />
                  </div>

                  {/* البريد الإلكتروني */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      البريد الإلكتروني <span className="text-red-500">*</span>
                    </label>
                    <input
                      name="email"
                      required
                      type="email"
                      placeholder="info@company.sa"
                      dir="ltr"
                      className={inputCls}
                    />
                  </div>

                  {/* كلمة المرور */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-2">
                        كلمة المرور <span className="text-red-500">*</span>
                      </label>
                      <input
                        name="password"
                        required
                        type="password"
                        placeholder="••••••••"
                        dir="ltr"
                        className={inputCls}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-2">
                        تأكيد كلمة المرور <span className="text-red-500">*</span>
                      </label>
                      <input
                        name="password_confirmation"
                        required
                        type="password"
                        placeholder="••••••••"
                        dir="ltr"
                        className={inputCls}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      المدينة <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <select
                        name="city_id"
                        required
                        value={selectedCity}
                        onChange={(e) => setSelectedCity(e.target.value)}
                        disabled={citiesLoading}
                        className={`${inputCls} appearance-none pl-8 cursor-pointer`}
                      >
                        <option value="">
                          {citiesLoading ? 'جاري تحميل المدن...' : 'اختر المدينة'}
                        </option>
                        {cities.map((city) => (
                          <option key={city.id} value={city.id}>
                            {city.name}
                          </option>
                        ))}
                      </select>
                      <i className="ri-arrow-down-s-line absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
                    </div>
                  </div>

                  {/* السجل التجاري */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      رقم السجل التجاري <span className="text-red-500">*</span>
                    </label>
                    <input
                      name="commercial_register_number"
                      required
                      type="text"
                      placeholder="1234567890"
                      dir="ltr"
                      className={inputCls}
                    />
                  </div>

                  {/* ملاحظات إضافية */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      ملاحظات إضافية
                    </label>
                    <textarea
                      name="description"
                      maxLength={500}
                      rows={3}
                      placeholder="أي معلومات إضافية تود مشاركتها..."
                      className={`${inputCls} resize-none`}
                    ></textarea>
                  </div>

              {/* ── الموافقة على الشروط ───────────────────────── */}
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  name="is_terms"
                  className="w-5 h-5 mt-0.5 accent-blue-600 flex-shrink-0"
                />
                <span className="text-sm text-slate-600">
                  بالتسجيل أنت توافق على{' '}
                  <button
                    type="button"
                    className="font-medium bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                    style={{ color: '#1D4ED8' }}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setTermsDialogVisible(true);
                      void loadTermsContent();
                    }}
                  >
                    الشروط والأحكام
                  </button>{' '}
                  و{' '}
                  <button
                    type="button"
                    className="font-medium bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                    style={{ color: '#1D4ED8' }}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setPrivacyDialogVisible(true);
                      void loadPrivacyContent();
                    }}
                  >
                    سياسة الخصوصية
                  </button>
                </span>
              </label>

              {/* ── زر الإرسال ───────────────────────────────── */}
              <button
                type="submit"
                disabled={loading}
                className="w-full py-4 text-white rounded-xl font-bold text-lg whitespace-nowrap active:scale-95 transition-all shadow-lg flex items-center justify-center gap-2"
                style={{ background: loading ? '#93C5FD' : '#1D4ED8' }}
              >
                {loading ? (
                  <>
                    <i className="ri-loader-4-line animate-spin text-xl"></i>
                    <span>جاري الإرسال...</span>
                  </>
                ) : (
                  <>
                    <i className="ri-send-plane-line text-xl"></i>
                    <span>تسجيل الشركة</span>
                  </>
                )}
              </button>
            </form>
          </div>
        </div>
      </section>

      {/* ── Footer ─────────────────────────────────────────────── */}
      <footer style={{ background: '#0F172A' }} className="text-white py-8">
        <div className="max-w-7xl mx-auto px-4 text-center" style={{ color: '#64748b' }}>
          <p>© 2024 باصاتي. جميع الحقوق محفوظة.</p>
        </div>
      </footer>

      {/* ── الشروط والأحكام (PrimeReact) ─────────────────────────── */}
      <Dialog
        visible={termsDialogVisible}
        onHide={() => setTermsDialogVisible(false)}
        header="الشروط والأحكام"
        modal
        draggable={false}
        resizable={false}
        style={{ width: 'min(92vw, 560px)' }}
        contentStyle={{ padding: '1rem 1.25rem', direction: 'rtl', maxHeight: '70vh', overflow: 'auto' }}
      >
        {termsLoading ? (
          <div className="flex justify-center py-12">
            <ProgressSpinner style={{ width: '48px', height: '48px' }} strokeWidth="4" />
          </div>
        ) : (
          <LegalHtmlBlock content={termsBody} />
        )}
      </Dialog>

      {/* ── سياسة الخصوصية (PrimeReact) ─────────────────────────── */}
      <Dialog
        visible={privacyDialogVisible}
        onHide={() => setPrivacyDialogVisible(false)}
        header="سياسة الخصوصية"
        modal
        draggable={false}
        resizable={false}
        style={{ width: 'min(92vw, 560px)' }}
        contentStyle={{ padding: '1rem 1.25rem', direction: 'rtl', maxHeight: '70vh', overflow: 'auto' }}
      >
        {privacyLoading ? (
          <div className="flex justify-center py-12">
            <ProgressSpinner style={{ width: '48px', height: '48px' }} strokeWidth="4" />
          </div>
        ) : (
          <LegalHtmlBlock content={privacyBody} />
        )}
      </Dialog>

      {/* ── OTP Dialog (PrimeReact) ─────────────────────────────── */}
      <Dialog
        visible={otpVisible}
        onHide={() => setOtpVisible(false)}
        header={otpDialogHeader}
        modal
        draggable={false}
        resizable={false}
        closable={!otpLoading && !resendLoading}
        style={{ width: '360px' }}
        contentStyle={{ padding: '1.5rem', direction: 'rtl' }}
        className="otp-dialog"
      >
        {/* 4-digit OTP inputs */}
        <div className="flex justify-center gap-3 mb-6" dir="ltr">
          {otpDigits.map((digit, idx) => (
            <input
              key={idx}
              ref={(el) => { otpRefs.current[idx] = el; }}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={digit}
              onChange={(e) => {
                const val = e.target.value.replace(/\D/g, '');
                const newDigits = [...otpDigits];
                newDigits[idx] = val.slice(-1);
                setOtpDigits(newDigits);
                if (val && idx < 3) otpRefs.current[idx + 1]?.focus();
              }}
              onKeyDown={(e) => {
                if (e.key === 'Backspace' && !otpDigits[idx] && idx > 0) {
                  otpRefs.current[idx - 1]?.focus();
                }
              }}
              className="w-14 h-14 text-center text-2xl font-bold rounded-xl border-2 border-slate-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 outline-none transition-all"
            />
          ))}
        </div>

        <div className="mb-4 text-center">
          {otpResendSeconds > 0 ? (
            <p className="text-sm text-slate-500">
              يمكنك طلب رمز جديد خلال{' '}
              <span className="font-bold tabular-nums text-slate-700" dir="ltr">
                {formatMmSs(otpResendSeconds)}
              </span>
            </p>
          ) : (
            <button
              type="button"
              onClick={handleResendCode}
              disabled={resendLoading}
              className="text-sm font-bold disabled:opacity-50 disabled:cursor-not-allowed"
              style={{ color: '#1D4ED8' }}
            >
              {resendLoading ? (
                <span className="inline-flex items-center gap-2">
                  <i className="ri-loader-4-line animate-spin"></i>
                  جاري الإرسال...
                </span>
              ) : (
                <span className="inline-flex items-center gap-1">
                  <i className="ri-refresh-line"></i>
                  إعادة إرسال رمز التحقق
                </span>
              )}
            </button>
          )}
        </div>

        <button
          type="button"
          onClick={handleOtpSubmit}
          disabled={otpLoading || resendLoading || otpDigits.join('').length < 4}
          className="w-full py-3 text-white rounded-xl font-bold text-base flex items-center justify-center gap-2 transition-all active:scale-95"
          style={{
            background:
              otpLoading || resendLoading || otpDigits.join('').length < 4 ? '#93C5FD' : '#1D4ED8',
          }}
        >
          {otpLoading ? (
            <>
              <i className="ri-loader-4-line animate-spin"></i>
              <span>جاري التحقق...</span>
            </>
          ) : (
            <>
              <i className="ri-check-double-line"></i>
              <span>تأكيد</span>
            </>
          )}
        </button>

        <button
          type="button"
          onClick={() => setOtpVisible(false)}
          disabled={otpLoading || resendLoading}
          className="w-full mt-3 py-2 text-slate-400 text-sm hover:text-slate-600 transition-colors disabled:opacity-50"
        >
          إلغاء
        </button>
      </Dialog>

      {/* ── Success Dialog (PrimeReact) ─────────────────────────── */}
      <Dialog
        visible={successVisible}
        onHide={() => setSuccessVisible(false)}
        header={successDialogHeader}
        modal
        draggable={false}
        resizable={false}
        closable={false}
        style={{ width: '360px' }}
        contentStyle={{ padding: '0 1.5rem 1.5rem', direction: 'rtl' }}
        className="success-dialog"
      >
        <div className="text-center">
          <h2 className="text-2xl font-bold text-slate-800 mb-2">تم التحقق بنجاح!</h2>
          <p className="text-slate-500 text-sm">سيتم تحويلك إلى صفحة تسجيل الدخول خلال ثوانٍ...</p>
          <div className="mt-5 flex justify-center gap-1.5">
            {[0, 1, 2].map((i) => (
              <span
                key={i}
                className="w-2 h-2 rounded-full bg-green-400 animate-bounce"
                style={{ animationDelay: `${i * 0.15}s` }}
              />
            ))}
          </div>
        </div>
      </Dialog>
    </div>
  );
}