import React, { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { useLang } from '@/context/LangContext'

const GOLD = '#CD9E53'
const NAVY = '#032340'

type Mode = 'login' | 'register'

export default function AuthPage({ defaultMode = 'login', onSuccess, onClose }: { defaultMode?: Mode; onSuccess?: () => void; onClose?: () => void }) {
  const { lang } = useLang()
  const { login } = useAuth()
  const navigate = useNavigate()
  const [mode, setMode] = useState<Mode>(defaultMode)
  const handleSuccess = () => { if (onSuccess) { onSuccess() } else { navigate('/profile') } }
  const [isMobile, setIsMobile] = useState(() => window.innerWidth < 1024)

  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 1023px)')
    const h = (e: MediaQueryListEvent | MediaQueryList) => setIsMobile(e.matches)
    h(mq); mq.addEventListener('change', h)
    return () => mq.removeEventListener('change', h)
  }, [])

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1100,
      display: 'flex', flexDirection: lang === 'fa' ? 'row-reverse' : 'row',
      background: isMobile ? '#fafaf8' : '#fff', overflow: 'hidden',
    }}>
      {onClose && (
        <button onClick={onClose} style={{
          position: 'absolute', top: 16, zIndex: 10,
          ...(lang === 'fa' ? { left: 16 } : { right: 16 }),
          width: 36, height: 36, borderRadius: '50%', border: 'none',
          background: 'rgba(7,29,73,0.1)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#032340" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      )}
      {/* ── Brand Panel — desktop only ── */}
      {!isMobile && <BrandPanel mode={mode} lang={lang} />}

      {/* ── Form Panel ── */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', background: '#fafaf8', overflowY: 'auto',
      }}>

        {/* Mobile top bar */}
        {isMobile && (
          <div style={{
            width: '100%', background: NAVY, padding: '1rem 1.5rem',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            direction: 'rtl', flexShrink: 0,
          }}>
            <Link to="/" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
              <img src="/Frame%202095585206%20(2).png" alt="" style={{ height: 36, filter: 'brightness(0) invert(1)' }} />
              <span style={{ color: '#fff', fontWeight: 800, fontSize: '0.95rem' }}>اندیشکده فولاد آینده</span>
            </Link>
            <Link to="/" style={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.75rem', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 4 }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>
              </svg>
              {lang === 'fa' ? 'بازگشت' : 'Back'}
            </Link>
          </div>
        )}

        <div style={{
          width: '100%', maxWidth: 440,
          padding: isMobile ? '1.5rem 1.25rem 3rem' : '2rem',
          flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
        }}>

          {/* Tab switcher */}
          <div style={{
            display: 'flex', background: '#ececea', borderRadius: 12,
            padding: 4, marginBottom: '1.75rem', direction: 'rtl',
          }}>
            {(['login', 'register'] as Mode[]).map(m => (
              <button key={m} onClick={() => setMode(m)} style={{
                flex: 1, padding: '0.65rem', borderRadius: 9, border: 'none',
                background: mode === m ? '#fff' : 'transparent',
                color: mode === m ? NAVY : '#aaa',
                fontWeight: mode === m ? 700 : 500,
                fontSize: '0.88rem', cursor: 'pointer', transition: 'all 0.2s',
                boxShadow: mode === m ? '0 1px 6px rgba(0,0,0,0.1)' : 'none',
                fontFamily: 'inherit',
              }}>
                {m === 'login'
                  ? (lang === 'fa' ? 'ورود' : 'Login')
                  : (lang === 'fa' ? 'ثبت‌نام' : 'Register')}
              </button>
            ))}
          </div>

          {mode === 'login'
            ? <LoginForm lang={lang} login={login} navigate={handleSuccess} />
            : <RegisterForm lang={lang} navigate={handleSuccess} />
          }

          {!isMobile && (
            <div style={{ marginTop: '1.75rem', paddingTop: '1.25rem', borderTop: '1px solid #eee', textAlign: 'center' }}>
              <Link to="/" style={{
                color: '#bbb', fontSize: '0.78rem', textDecoration: 'none',
                display: 'inline-flex', alignItems: 'center', gap: 5, direction: 'rtl',
              }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>
                </svg>
                {lang === 'fa' ? 'بازگشت به سایت' : 'Back to site'}
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

/* ─── Login Form — phone + password, with an OTP alternative ─── */
function LoginForm({ lang, login, navigate }: {
  lang: 'fa' | 'en'
  login: (e: string, p: string) => Promise<void>
  navigate: (to?: string) => void
}) {
  const fa = lang === 'fa'
  const { otpLogin } = useAuth()
  const [otpMode, setOtpMode] = useState(false)
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [showPass, setShowPass] = useState(false)
  const [otpSent, setOtpSent] = useState(false)
  const [code, setCode] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const API = (import.meta as ImportMeta & { env?: Record<string, string> }).env?.VITE_PANEL_API || ''

  async function submitPassword(e: React.FormEvent) {
    e.preventDefault(); setError(''); setLoading(true)
    try { await login(phone, password); navigate('/profile') }
    catch (err: unknown) { setError(err instanceof Error ? err.message : (fa ? 'خطا در ورود' : 'Login error')) }
    finally { setLoading(false) }
  }

  async function sendOtp(e: React.FormEvent) {
    e.preventDefault(); setError('')
    if (!/^09\d{9}$/.test(phone)) { setError(fa ? 'شماره موبایل معتبر وارد کنید' : 'Enter a valid phone number'); return }
    setLoading(true)
    try {
      const res = await fetch(`${API}/api/members/otp/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ phone }) })
      if (!res.ok) throw new Error()
      setOtpSent(true)
    } catch { setError(fa ? 'ارسال کد ناموفق بود' : 'Failed to send code') }
    finally { setLoading(false) }
  }

  async function verifyOtp(e: React.FormEvent) {
    e.preventDefault(); setError(''); setLoading(true)
    try {
      await otpLogin(phone, code)
      navigate('/profile')
    } catch (err: unknown) { setError(err instanceof Error ? err.message : (fa ? 'خطا در تأیید کد' : 'Verification error')) }
    finally { setLoading(false) }
  }

  return (
    <div dir="rtl" style={{ display: 'flex', flexDirection: 'column', gap: '1.1rem' }}>
      <div style={{ marginBottom: '0.5rem', direction: 'rtl' }}>
        <h2 style={{ margin: '0 0 0.3rem', color: NAVY, fontSize: '1.5rem', fontWeight: 800 }}>{fa ? 'خوش آمدید' : 'Welcome back'}</h2>
        <p style={{ margin: 0, color: '#999', fontSize: '0.875rem' }}>{fa ? 'برای ادامه وارد حساب خود شوید' : 'Sign in to continue'}</p>
      </div>

      {!otpMode ? (
        <>
          <form onSubmit={submitPassword} style={{ display: 'flex', flexDirection: 'column', gap: '1.1rem' }}>
            <FField label={fa ? 'شماره موبایل یا ایمیل' : 'Phone or email'}>
              <FInput type="text" required value={phone} onChange={e => setPhone(e.target.value)} placeholder={fa ? 'شماره موبایل یا ایمیل' : 'Phone or email'} dir="ltr" icon={<PhoneIcon />} />
            </FField>
            <FField label={fa ? 'رمز عبور' : 'Password'}>
              <FInput type={showPass ? 'text' : 'password'} required value={password} onChange={e => setPassword(e.target.value)} dir="ltr" icon={<LockIcon />} suffix={<EyeToggle show={showPass} onToggle={() => setShowPass(s => !s)} />} />
            </FField>
            {error && <ErrBox>{error}</ErrBox>}
            <SubmitBtn loading={loading}>{fa ? 'ورود به حساب' : 'Sign In'}</SubmitBtn>
          </form>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0.15rem 0' }}>
            <div style={{ flex: 1, height: 1, background: '#e8e8e8' }} />
            <span style={{ fontSize: '0.75rem', color: '#bbb' }}>{fa ? 'یا' : 'or'}</span>
            <div style={{ flex: 1, height: 1, background: '#e8e8e8' }} />
          </div>

          <button type="button" onClick={() => { setOtpMode(true); setError('') }} style={{
            width: '100%', padding: '0.85rem', borderRadius: 10, border: `1.5px solid ${NAVY}22`,
            background: '#fff', color: NAVY, fontWeight: 700, fontSize: '0.9rem', cursor: 'pointer',
            fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <PhoneIcon />
            {fa ? 'ورود با رمز یکبار مصرف (OTP)' : 'Sign in with OTP'}
          </button>
        </>
      ) : (
        <form onSubmit={otpSent ? verifyOtp : sendOtp} style={{ display: 'flex', flexDirection: 'column', gap: '1.1rem' }}>
          <FField label={fa ? 'شماره موبایل' : 'Phone number'}>
            <FInput type="tel" required value={phone} onChange={e => setPhone(e.target.value)} placeholder="09123456789" dir="ltr" icon={<PhoneIcon />} disabled={otpSent} />
          </FField>
          {otpSent && (
            <FField label={fa ? 'کد تأیید پیامک‌شده' : 'Verification code'}>
              <FInput inputMode="numeric" required maxLength={6} value={code} onChange={e => setCode(e.target.value.replace(/\D/g, ''))} placeholder="------" dir="ltr" style={{ letterSpacing: '0.5em', textAlign: 'center', fontWeight: 700 }} />
            </FField>
          )}
          {error && <ErrBox>{error}</ErrBox>}
          <SubmitBtn loading={loading}>{otpSent ? (fa ? 'تأیید و ورود' : 'Verify & Sign In') : (fa ? 'ارسال کد' : 'Send Code')}</SubmitBtn>
          <button type="button" onClick={() => { setOtpMode(false); setOtpSent(false); setCode(''); setError('') }} style={{ background: 'none', border: 'none', color: '#999', fontSize: '0.82rem', cursor: 'pointer', fontFamily: 'inherit' }}>
            ← {fa ? 'ورود با رمز عبور' : 'Sign in with password'}
          </button>
        </form>
      )}
    </div>
  )
}

/* ─── Register Form — full details, then OTP phone verification (SFsignup) ─── */
function RegisterForm({ lang, navigate }: { lang: 'fa' | 'en'; navigate: (to?: string) => void }) {
  const fa = lang === 'fa'
  const { registerVerify } = useAuth()
  const API = (import.meta as ImportMeta & { env?: Record<string, string> }).env?.VITE_PANEL_API || ''
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [org, setOrg] = useState('')
  const [password, setPassword] = useState('')
  const [showPass, setShowPass] = useState(false)
  const [otpStep, setOtpStep] = useState(false)
  const [code, setCode] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  async function sendCode(e: React.FormEvent) {
    e.preventDefault(); setError('')
    if (!/^09\d{9}$/.test(phone)) { setError(fa ? 'شماره موبایل معتبر وارد کنید (۰۹...)' : 'Enter a valid phone'); return }
    if (password.length < 6) { setError(fa ? 'رمز عبور باید حداقل ۶ کاراکتر باشد' : 'Password min 6 chars'); return }
    setLoading(true)
    try {
      const res = await fetch(`${API}/api/members/otp/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ phone }) })
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || (fa ? 'ارسال کد ناموفق بود' : 'Failed to send code')) }
      setOtpStep(true)
    } catch (err: unknown) { setError(err instanceof Error ? err.message : (fa ? 'خطا' : 'Error')) }
    finally { setLoading(false) }
  }

  async function verifyAndRegister(e: React.FormEvent) {
    e.preventDefault(); setError(''); setLoading(true)
    try { await registerVerify(name, email, password, phone, code); navigate('/profile') }
    catch (err: unknown) { setError(err instanceof Error ? err.message : (fa ? 'خطا در ثبت‌نام' : 'Registration error')) }
    finally { setLoading(false) }
  }

  if (otpStep) {
    return (
      <form onSubmit={verifyAndRegister} dir="rtl" style={{ display: 'flex', flexDirection: 'column', gap: '1.1rem' }}>
        <div style={{ marginBottom: '0.5rem', direction: 'rtl' }}>
          <h2 style={{ margin: '0 0 0.3rem', color: NAVY, fontSize: '1.4rem', fontWeight: 800 }}>{fa ? 'تأیید شماره موبایل' : 'Verify your phone'}</h2>
          <p style={{ margin: 0, color: '#999', fontSize: '0.85rem', direction: 'rtl' }}>{fa ? `کد تأیید به شماره ${phone} پیامک شد` : `Code sent to ${phone}`}</p>
        </div>
        <FField label={fa ? 'کد تأیید' : 'Verification code'}>
          <FInput inputMode="numeric" required maxLength={6} value={code} onChange={e => setCode(e.target.value.replace(/\D/g, ''))} placeholder="------" dir="ltr" style={{ letterSpacing: '0.5em', textAlign: 'center', fontWeight: 700 }} />
        </FField>
        {error && <ErrBox>{error}</ErrBox>}
        <SubmitBtn loading={loading}>{fa ? 'تأیید و ساخت حساب' : 'Verify & Create Account'}</SubmitBtn>
        <button type="button" onClick={() => { setOtpStep(false); setCode(''); setError('') }} style={{ background: 'none', border: 'none', color: '#999', fontSize: '0.82rem', cursor: 'pointer', fontFamily: 'inherit' }}>
          ← {fa ? 'ویرایش اطلاعات' : 'Edit details'}
        </button>
      </form>
    )
  }

  return (
    <form onSubmit={sendCode} dir="rtl" style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <div style={{ marginBottom: '0.5rem', direction: 'rtl' }}>
        <h2 style={{ margin: '0 0 0.3rem', color: NAVY, fontSize: '1.5rem', fontWeight: 800 }}>{fa ? 'ثبت‌نام' : 'Create account'}</h2>
        <p style={{ margin: 0, color: '#999', fontSize: '0.875rem' }}>{fa ? 'یک حساب کاربری جدید بسازید' : 'Join the Steel Futures Institute'}</p>
      </div>

      <FField label={fa ? 'نام و نام خانوادگی' : 'Full Name'}>
        <FInput required value={name} onChange={e => setName(e.target.value)} placeholder={fa ? 'علی محمدی' : 'John Doe'} icon={<UserIcon />} />
      </FField>
      <FField label={fa ? 'ایمیل' : 'Email'}>
        <FInput type="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="example@email.com" dir="ltr" icon={<MailIcon />} />
      </FField>
      <FField label={fa ? 'شماره موبایل' : 'Phone'} required>
        <FInput type="tel" required value={phone} onChange={e => setPhone(e.target.value)} placeholder="09123456789" dir="ltr" icon={<PhoneIcon />} />
      </FField>
      <FField label={fa ? 'نام سازمان / شرکت (اختیاری)' : 'Organization (optional)'}>
        <FInput value={org} onChange={e => setOrg(e.target.value)} placeholder={fa ? 'شرکت فولاد...' : 'Your company...'} icon={<BldgIcon />} />
      </FField>
      <FField label={fa ? 'رمز عبور' : 'Password'}>
        <FInput type={showPass ? 'text' : 'password'} required minLength={6} value={password} onChange={e => setPassword(e.target.value)} dir="ltr" icon={<LockIcon />} suffix={<EyeToggle show={showPass} onToggle={() => setShowPass(s => !s)} />} />
        <p style={{ margin: '4px 0 0', color: '#bbb', fontSize: '0.73rem', textAlign: 'right' }}>{fa ? 'حداقل ۶ کاراکتر' : 'Min 6 characters'}</p>
      </FField>

      {error && <ErrBox>{error}</ErrBox>}

      <SubmitBtn loading={loading}>{fa ? 'ارسال کد تأیید' : 'Send Verification Code'}</SubmitBtn>
    </form>
  )
}

/* ─── Login keyword animation ─── */
const KW_FA = ['آینده', 'فناوری', 'بازار', 'رقابت', 'نوآوری', 'پایداری', 'فولاد']
const KW_EN = ['Future', 'Technology', 'Market', 'Competition', 'Innovation', 'Sustainability', 'Steel']

// scattered positions (center点 + base size) — a word-cloud layout
const KW_POS = [
  { t: '12%', l: '26%', s: 3.3 },  // آینده
  { t: '25%', l: '72%', s: 2.6 },  // فناوری
  { t: '45%', l: '15%', s: 3.0 },  // بازار
  { t: '40%', l: '83%', s: 2.4 },  // رقابت
  { t: '78%', l: '24%', s: 2.8 },  // نوآوری
  { t: '83%', l: '66%', s: 2.5 },  // پایداری
  { t: '58%', l: '50%', s: 4.0 },  // فولاد
]

function KeywordCycle({ lang }: { lang: 'fa' | 'en' }) {
  const words = lang === 'fa' ? KW_FA : KW_EN
  const [active, setActive] = useState(0)
  React.useEffect(() => {
    const t = setInterval(() => setActive(p => (p + 1) % words.length), 1700)
    return () => clearInterval(t)
  }, [words.length])
  // word cloud: all words scattered + dim; the selected one lights gold, scales and glows
  return (
    <div style={{ position: 'relative', zIndex: 1, width: '100%', height: 360 }}>
      {words.map((w, idx) => {
        const p = KW_POS[idx % KW_POS.length]
        const isActive = idx === active
        return (
          <span
            key={w}
            style={{
              position: 'absolute', top: p.t, left: p.l,
              transform: `translate(-50%, -50%) scale(${isActive ? 1.35 : 1})`,
              whiteSpace: 'nowrap',
              fontSize: `${p.s}rem`,
              fontWeight: isActive ? 900 : 700,
              color: isActive ? GOLD : 'rgba(255,255,255,0.16)',
              textShadow: isActive ? `0 0 26px ${GOLD}66` : 'none',
              transition: 'color .55s ease, transform .55s cubic-bezier(0.22,1,0.36,1), text-shadow .55s',
              zIndex: isActive ? 2 : 1,
              willChange: 'transform',
            }}
          >
            {w}
          </span>
        )
      })}
    </div>
  )
}

/* ─── Brand Panel ─── */
function BrandPanel({ mode, lang }: { mode: Mode; lang: 'fa' | 'en' }) {
  return (
    <div style={{
      flex: '0 0 46%', position: 'relative', overflow: 'hidden',
      background: `linear-gradient(145deg, ${NAVY} 0%, #043560 55%, #021828 100%)`,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      padding: '3rem',
    }}
      className="max-lg:hidden"
    >
      {/* grid */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.04 }} preserveAspectRatio="xMidYMid slice">
        <defs><pattern id="bg" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M 40 0 L 0 0 0 40" fill="none" stroke={GOLD} strokeWidth="0.8"/>
        </pattern></defs>
        <rect width="100%" height="100%" fill="url(#bg)" />
      </svg>
      {/* hex rings */}
      <svg style={{ position: 'absolute', bottom: -80, right: lang === 'fa' ? 'auto' : -80, left: lang === 'fa' ? -80 : 'auto', width: 440, height: 440, opacity: 0.07, pointerEvents: 'none' }} viewBox="0 0 440 440">
        {[0,1,2,3,4].map(i => (
          <polygon key={i} points="220,12 400,112 400,312 220,412 40,312 40,112"
            fill="none" stroke={GOLD} strokeWidth="1.5"
            transform={`translate(${220 * (1 - (0.35 + i*0.13))}, ${220 * (1 - (0.35 + i*0.13))}) scale(${0.35 + i*0.13})`}
          />
        ))}
      </svg>

      {/* Logo */}
      <div style={{ position: 'relative', zIndex: 1 }}>
        <Link to="/" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <img src="/Frame%202095585206%20(2).png" alt="" style={{ height: 44, filter: 'brightness(0) invert(1)' }} />
          <div>
            <div style={{ color: '#fff', fontWeight: 800, fontSize: '1.05rem', lineHeight: 1.3 }}>اندیشکده فولاد آینده</div>
            <div style={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.6rem', letterSpacing: '2px', textTransform: 'uppercase' }}>The Steel Futures Institute</div>
          </div>
        </Link>
      </div>

      {mode === 'login' ? (
        <>
          <KeywordCycle lang={lang} />
          <div />
        </>
      ) : (
      <>
      {/* Center copy */}
      <div style={{ position: 'relative', zIndex: 1, direction: 'rtl' }}>
        <h1 style={{ color: '#fff', fontSize: 'clamp(1.5rem, 2.3vw, 2.2rem)', fontWeight: 800, lineHeight: 1.45, margin: '0 0 1rem' }}>
          {lang === 'fa' ? 'بینشی نو برای ' : 'A New Vision for '}<span style={{ color: GOLD, whiteSpace: 'nowrap' }}>{lang === 'fa' ? 'توسعه صنعتی' : 'Industrial Growth'}</span>
        </h1>
        <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.9rem', lineHeight: 1.85, margin: 0 }}>
          {lang === 'fa'
            ? 'رصد آینده‌پژوهانه بازار، فناوری، رقابت و سیاست‌های صنعت فولاد برای مدیران و تصمیم‌سازان.'
            : 'Forward-looking monitoring of markets, technology, competition and steel-industry policy for managers and decision-makers.'}
        </p>
      </div>

      {/* Bottom stats / checklist */}
      <div style={{ position: 'relative', zIndex: 1, direction: 'rtl' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.85rem' }}>
          <div style={{ color: GOLD, fontSize: '0.95rem', fontWeight: 800 }}>{lang === 'fa' ? 'پژوهش‌های صنعت فولاد' : 'Steel Industry Research'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
            {[
              lang === 'fa' ? 'رصد فناوری‌های نوظهور' : 'Emerging technology monitoring',
              lang === 'fa' ? 'هوشمندی رقابتی' : 'Competitive intelligence',
              lang === 'fa' ? 'سناریونگاری آینده' : 'Future scenario planning',
              lang === 'fa' ? 'تحلیل‌های تخصصی بازار' : 'Expert market analysis',
              lang === 'fa' ? 'شبکه خبرگان صنعت' : 'Industry expert network',
            ].map(item => (
              <div key={item} style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'rgba(255,255,255,0.72)', fontSize: '0.875rem' }}>
                <span style={{ color: GOLD, fontSize: '0.7rem', flexShrink: 0, lineHeight: 1 }}>◉</span>
                {item}
              </div>
            ))}
          </div>
        </div>
      </div>
      </>
      )}
    </div>
  )
}

/* ─── Shared primitives ─── */
function FField({ label, children, required }: { label: string; children: React.ReactNode; required?: boolean }) {
  return (
    <div>
      <label style={{ display: 'block', color: '#444', fontSize: '0.8rem', fontWeight: 600, marginBottom: 6, direction: 'rtl' }}>
        {label}{required && <span style={{ color: '#e74c3c', marginRight: 2 }}>*</span>}
      </label>
      {children}
    </div>
  )
}

function FInput({ icon, suffix, ...props }: React.InputHTMLAttributes<HTMLInputElement> & { icon?: React.ReactNode; suffix?: React.ReactNode }) {
  const [focused, setFocused] = useState(false)
  return (
    <div style={{ position: 'relative' }}>
      <input
        {...props}
        onFocus={e => { setFocused(true); props.onFocus?.(e) }}
        onBlur={e => { setFocused(false); props.onBlur?.(e) }}
        style={{
          width: '100%',
          padding: `0.82rem ${suffix ? '2.75rem' : '1rem'} 0.82rem ${icon ? '2.75rem' : '1rem'}`,
          borderRadius: 10, border: `1.5px solid ${focused ? GOLD : '#e5e5e5'}`,
          background: props.disabled ? '#f7f7f7' : '#fff',
          color: '#1a1a1a', fontSize: '0.9rem', outline: 'none',
          boxSizing: 'border-box', transition: 'border-color 0.18s',
          fontFamily: 'inherit', ...props.style,
        }}
      />
      {icon && <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', opacity: 0.3, pointerEvents: 'none', display: 'flex' }}>{icon}</span>}
      {suffix && <span style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>{suffix}</span>}
    </div>
  )
}

function EyeToggle({ show, onToggle }: { show: boolean; onToggle: () => void }) {
  return (
    <button type="button" onClick={onToggle} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, opacity: 0.4, display: 'flex', alignItems: 'center' }}>
      {show
        ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
        : <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      }
    </button>
  )
}

function ErrBox({ children }: { children: React.ReactNode }) {
  return (
    <div style={{ background: '#fff0f0', border: '1px solid #ffcccc', borderRadius: 8, padding: '0.65rem 1rem', color: '#c0392b', fontSize: '0.83rem', direction: 'rtl' }}>
      {children}
    </div>
  )
}

function SubmitBtn({ loading, children }: { loading: boolean; children: React.ReactNode }) {
  return (
    <button type="submit" disabled={loading} style={{
      width: '100%', padding: '0.9rem', borderRadius: 10, border: 'none',
      background: loading ? '#e0c98a' : GOLD, color: NAVY,
      fontWeight: 800, fontSize: '0.95rem', cursor: loading ? 'not-allowed' : 'pointer',
      transition: 'all 0.2s', marginTop: '0.35rem',
      boxShadow: loading ? 'none' : `0 4px 20px ${GOLD}55`,
      fontFamily: 'inherit',
    }}
      onMouseEnter={e => { if (!loading) { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = `0 6px 24px ${GOLD}66` } }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = loading ? 'none' : `0 4px 20px ${GOLD}55` }}
    >
      {loading ? '...' : children}
    </button>
  )
}

/* ─── SVG Icons ─── */
const MailIcon = () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
const LockIcon = () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
const UserIcon = () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
const PhoneIcon = () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.61 3.4 2 2 0 0 1 3.6 1.22h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L7.91 9a16 16 0 0 0 6.07 6.07l1.16-1.16a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
const BldgIcon = () => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
