// ProMTK — Enterprise Onboarding + Login flow
// 3 welcome slides → phone → OTP → PIN → KYC complete

const ScreenOnboardingPro = ({ go }) => {
  const [step, setStep] = React.useState(0);
  const slides = [
    { badge: 'SAKİN ÜÇÜN', title: 'Bütün bina,\nbir cibinizdə.', sub: 'Ödəniş, qonaq, təmir, smart bina — hamısı bir yerdə.', icon: 'building' },
    { badge: 'BİRLƏŞDİR', title: 'Çoxsaylı mənzil\nbir hesabda.', sub: 'Ailə mənzilləri və kirayə evlər — tək interfeys.', icon: 'grid' },
    { badge: 'AVTOMATLAŞDIR', title: 'Abunə kodu ilə\nborclar avtomatik.', sub: 'Su, qaz, işıq kodu əlavə et — bildiriş özü gələcək.', icon: 'sparkle' },
  ];
  const s = slides[step];
  const bg = ['rgba(124,92,255,0.35)', 'rgba(16,185,129,0.3)', 'rgba(245,158,11,0.3)'][step];
  return (
    <div className="pm-fade pm-themed" style={{ position: 'relative', height: '100%', minHeight: 820, background: 'var(--pm-bg)' }}>
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(circle at 30% 20%, ${bg}, transparent 55%), radial-gradient(circle at 80% 80%, rgba(178,75,255,0.2), transparent 55%)`, transition: 'background .6s' }}/>
      {[...Array(8)].map((_, i) => (
        <span key={i} style={{ position: 'absolute', width: 6, height: 6, borderRadius: 3, background: ['#7C5CFF','#B24BFF','#06B6D4','#10B981'][i%4], top: 120 + (i*70)%500, left: 40 + (i*53)%300, boxShadow: '0 0 18px currentColor', opacity: .7, animation: `pm-float ${3+i*0.3}s ease-in-out infinite`, animationDelay: `${i*0.15}s` }}/>
      ))}

      <div style={{ position: 'relative', padding: '80px 28px 0', zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 44, height: 44, borderRadius: 13, background: pmBase.gradient, display: 'grid', placeItems: 'center', color: '#fff', boxShadow: '0 10px 30px -8px rgba(124,92,255,0.6)' }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M4 20V10l8-6 8 6v10h-5v-6H9v6H4Z" fill="#fff"/><circle cx="12" cy="11" r="1.6" fill="#7C5CFF"/></svg>
          </div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.3 }}>ProMTK</div>
            <div style={{ fontSize: 10, color: 'var(--pm-fg3)', fontWeight: 600 }}>Enterprise yaşayış platforması</div>
          </div>
          <button onClick={() => go('phone')} style={{ marginLeft: 'auto', background: 'transparent', border: 'none', color: 'var(--pm-fg3)', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Keç</button>
        </div>

        <div key={step} style={{ marginTop: 64, animation: 'pm-slide-up .5s ease both' }}>
          <Pill color={pmBase.brand} style={{ fontSize: 10 }}>{s.badge}</Pill>
          <div style={{ fontSize: 40, fontWeight: 800, lineHeight: 1.05, letterSpacing: -1.4, marginTop: 14, color: 'var(--pm-fg)', whiteSpace: 'pre-line' }}>
            {s.title.split('\n').map((l, i) => i === 1 ? <span key={i} style={{ background: pmBase.gradient, WebkitBackgroundClip: 'text', color: 'transparent' }}>{l}</span> : <span key={i}>{l}<br/></span>)}
          </div>
          <div style={{ fontSize: 15, color: 'var(--pm-fg2)', marginTop: 18, lineHeight: 1.5, maxWidth: 320 }}>{s.sub}</div>
        </div>

        {step === 2 && (
          <div className="pm-stagger" style={{ marginTop: 28, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[{i:'drop',t:'Su',c:'#06B6D4'},{i:'flame',t:'Qaz',c:'#F97316'},{i:'bolt',t:'İşıq',c:'#EAB308'},{i:'wifi',t:'İnternet',c:'#A855F7'}].map((f,i) => (
              <div key={i} style={{ background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 14, padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: 10, background: `${f.c}22`, color: f.c, display: 'grid', placeItems: 'center' }}><Icon name={f.i} size={16}/></div>
                <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--pm-fg)' }}>{f.t}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div style={{ position: 'absolute', bottom: 44, left: 28, right: 28, zIndex: 2 }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 20, justifyContent: 'center' }}>
          {slides.map((_, i) => <span key={i} style={{ width: i === step ? 24 : 6, height: 6, borderRadius: 3, background: i === step ? pmBase.brand : 'var(--pm-fg4)', transition: 'all .3s' }}/>)}
        </div>
        <Btn full icon={step === 2 ? 'arrowRight' : 'chevronRight'} onClick={() => step < 2 ? setStep(step+1) : go('phone')}>
          {step === 2 ? 'Başlayaq' : 'Növbəti'}
        </Btn>
        {step === 0 && <div style={{ marginTop: 14, textAlign: 'center', fontSize: 12, color: 'var(--pm-fg3)' }}>Hesabın var? <span onClick={() => go('phone')} style={{ color: pmBase.brandSoft, fontWeight: 700, cursor: 'pointer' }}>Daxil ol</span></div>}
      </div>
    </div>
  );
};

const ScreenLoginPhone = ({ go }) => {
  const [raw, setRaw] = React.useState('');
  const inputRef = React.useRef(null);

  // Format AZ phone: "55 123 45 67" (2-3-2-2)
  const formatAZ = (digits) => {
    const d = digits.slice(0, 9);
    let out = '';
    if (d.length > 0) out += d.slice(0, 2);
    if (d.length > 2) out += ' ' + d.slice(2, 5);
    if (d.length > 5) out += ' ' + d.slice(5, 7);
    if (d.length > 7) out += ' ' + d.slice(7, 9);
    return out;
  };

  const handleChange = (e) => {
    const digits = e.target.value.replace(/\D/g, '').slice(0, 9);
    setRaw(digits);
  };

  const isValid = raw.length === 9;
  const formatted = formatAZ(raw);

  return (
    <div className="pm-fade pm-themed" style={{ padding: '72px 28px 0', background: 'var(--pm-bg)', minHeight: '100%' }}>
      <IconBtn name="chevronLeft" size={40} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('onboarding')}/>
      <div style={{ marginTop: 40 }}>
        <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: -0.8, color: 'var(--pm-fg)' }}>Telefon nömrəniz</div>
        <div style={{ fontSize: 14, color: 'var(--pm-fg2)', marginTop: 8 }}>Təsdiq kodu SMS ilə göndəriləcək</div>
      </div>
      <div onClick={() => inputRef.current?.focus()} style={{ marginTop: 32, padding: 18, background: 'var(--pm-bg3)', borderRadius: 16, border: `2px solid ${isValid ? pmBase.brand + '88' : 'var(--pm-line)'}`, display: 'flex', alignItems: 'center', gap: 12, transition: 'border-color .2s', cursor: 'text' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingRight: 12, borderRight: '1px solid var(--pm-line)' }}>
          <span style={{ fontSize: 22, lineHeight: 1 }}>🇦🇿</span>
          <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--pm-fg)', fontFamily: pmBase.mono }}>+994</span>
        </div>
        <input
          ref={inputRef}
          value={formatted}
          onChange={handleChange}
          type="tel"
          inputMode="numeric"
          autoComplete="tel-national"
          placeholder="55 123 45 67"
          maxLength={12}
          style={{
            flex: 1, minWidth: 0,
            background: 'transparent', border: 'none', outline: 'none',
            color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)',
            caretColor: pmBase.brand,
            fontSize: 18, fontWeight: 700, fontFamily: pmBase.font,
            letterSpacing: 0.5,
          }}
        />
        {raw.length > 0 && (
          <button
            onClick={(e) => { e.stopPropagation(); setRaw(''); inputRef.current?.focus(); }}
            aria-label="Təmizlə"
            style={{ width: 28, height: 28, borderRadius: 14, border: 'none', background: 'var(--pm-bg4)', color: 'var(--pm-fg2)', cursor: 'pointer', display: 'grid', placeItems: 'center' }}
          >
            <Icon name="close" size={12}/>
          </button>
        )}
      </div>

      <div style={{ marginTop: 12, fontSize: 11, color: isValid ? pmBase.ok : 'var(--pm-fg3)', display: 'flex', alignItems: 'center', gap: 6, paddingLeft: 4, whiteSpace: 'nowrap' }}>
        {isValid ? <><Icon name="check" size={12}/> Nömrə doğrudur</> : <>9 rəqqəm daxil edin</>}
      </div>

      <div style={{ marginTop: 20, padding: 14, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)', display: 'flex', gap: 12, alignItems: 'start' }}>
        <div style={{ width: 32, height: 32, borderRadius: 10, background: pmBase.infoSoft, color: pmBase.info, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="info" size={16}/></div>
        <div style={{ fontSize: 12, color: 'var(--pm-fg2)', lineHeight: 1.5 }}>Davam etməklə <span style={{ color: pmBase.brandSoft, fontWeight: 700 }}>İstifadə şərtləri</span> və <span style={{ color: pmBase.brandSoft, fontWeight: 700 }}>Məxfilik siyasəti</span> ilə razılaşırsınız.</div>
      </div>

      <div style={{ position: 'absolute', bottom: 44, left: 28, right: 28 }}>
        <Btn full icon="arrowRight" disabled={!isValid} onClick={() => isValid && go('otp')}>Kod göndər</Btn>
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ flex: 1, height: 1, background: 'var(--pm-line)' }}/>
          <span style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 600, letterSpacing: 0.5 }}>Və YA</span>
          <div style={{ flex: 1, height: 1, background: 'var(--pm-line)' }}/>
        </div>
        <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Btn variant="secondary" icon="badge" onClick={() => go('otp')} full>ASAN İmza</Btn>
          <Btn variant="secondary" icon="fingerprint" onClick={() => go('pin')} full>Biometrik</Btn>
        </div>
      </div>
    </div>
  );
};

const ScreenOTP = ({ go }) => {
  const [code, setCode] = React.useState(['', '', '', '', '', '']);
  const [timer, setTimer] = React.useState(59);
  React.useEffect(() => { const t = setInterval(() => setTimer(x => x > 0 ? x - 1 : 0), 1000); return () => clearInterval(t); }, []);
  const setDigit = (i, v) => {
    const digit = v.replace(/\D/g, '').slice(-1);
    const n = [...code]; n[i] = digit; setCode(n);
    if (digit && i < 5) document.getElementById(`pm-otp-${i+1}`)?.focus();
    if (n.every(x => x)) setTimeout(() => go('pin'), 300);
  };
  const handleKey = (i, e) => {
    if (e.key === 'Backspace' && !code[i] && i > 0) {
      const n = [...code]; n[i-1] = ''; setCode(n);
      document.getElementById(`pm-otp-${i-1}`)?.focus();
    }
  };
  return (
    <div className="pm-fade pm-themed" style={{ padding: '72px 28px 0', background: 'var(--pm-bg)', minHeight: '100%' }}>
      <IconBtn name="chevronLeft" size={40} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('phone')}/>
      <div style={{ marginTop: 40 }}>
        <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: -0.8, color: 'var(--pm-fg)' }}>Kodu daxil edin</div>
        <div style={{ fontSize: 14, color: 'var(--pm-fg2)', marginTop: 8 }}>+994 55 ••• 42 17 nömrəsinə 6-rəqəmli kod göndərildi</div>
      </div>

      <div style={{ marginTop: 40, display: 'flex', gap: 8, justifyContent: 'center' }}>
        {[0,1,2,3,4,5].map(i => (
          <input key={i} id={`pm-otp-${i}`} maxLength={1} value={code[i]}
            onChange={e => setDigit(i, e.target.value)}
            onKeyDown={e => handleKey(i, e)}
            type="tel" inputMode="numeric"
            style={{ width: 46, height: 60, borderRadius: 14, background: 'var(--pm-bg3)', border: `2px solid ${code[i] ? pmBase.brand : 'var(--pm-line)'}`, color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', caretColor: pmBase.brand, fontSize: 24, fontWeight: 800, textAlign: 'center', outline: 'none', fontFamily: pmBase.font, transition: 'border-color .2s', boxShadow: code[i] ? '0 6px 16px -6px rgba(124,92,255,0.5)' : 'none' }}/>
        ))}
      </div>

      <div style={{ marginTop: 28, textAlign: 'center', fontSize: 13, color: 'var(--pm-fg3)' }}>
        {timer > 0 ? <>Yenidən göndər: <span style={{ color: 'var(--pm-fg)', fontWeight: 700 }}>00:{timer.toString().padStart(2, '0')}</span></> : <span onClick={() => setTimer(59)} style={{ color: pmBase.brandSoft, fontWeight: 700, cursor: 'pointer' }}>Kodu yenidən göndər</span>}
      </div>

      {/* Fake keypad preview */}
      <div style={{ position: 'absolute', bottom: 44, left: 28, right: 28 }}>
        <div style={{ padding: 12, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 10, background: pmBase.okSoft, color: pmBase.ok, display: 'grid', placeItems: 'center' }}><Icon name="shieldCheck" size={16}/></div>
          <div style={{ fontSize: 12, color: 'var(--pm-fg2)', flex: 1 }}>Avtomatik SMS oxuma aktiv</div>
          <div style={{ width: 14, height: 14, borderRadius: 7, border: '2px solid var(--pm-fg3)', borderTopColor: pmBase.brand, animation: 'pm-spin 0.8s linear infinite' }}/>
        </div>
      </div>
    </div>
  );
};

const ScreenPIN = ({ go }) => {
  const [pin, setPin] = React.useState('');
  const tap = (d) => {
    if (d === 'x') return setPin(p => p.slice(0, -1));
    if (d === 'face') {
      // Simulate Face ID / Touch ID
      setTimeout(() => go('kyc'), 250);
      return;
    }
    if (pin.length < 4) {
      const n = pin + d;
      setPin(n);
      if (n.length === 4) setTimeout(() => go('kyc'), 300);
    }
  };
  return (
    <div className="pm-fade pm-themed" style={{ padding: '72px 28px 0', background: 'var(--pm-bg)', minHeight: '100%', position: 'relative' }}>
      <div style={{ textAlign: 'center', marginTop: 20 }}>
        <div style={{ width: 72, height: 72, borderRadius: 22, background: pmBase.gradient, margin: '0 auto 20px', display: 'grid', placeItems: 'center', color: '#fff', boxShadow: '0 20px 40px -12px rgba(124,92,255,0.6)' }}>
          <Icon name="lock" size={32}/>
        </div>
        <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: -0.6, color: 'var(--pm-fg)' }}>PIN kod yaradın</div>
        <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 6 }}>4 rəqəmli kod · sonra Face ID</div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 18, margin: '40px 0 32px' }}>
        {[0,1,2,3].map(i => (
          <div key={i} style={{ width: 18, height: 18, borderRadius: 9, background: pin.length > i ? pmBase.brand : 'var(--pm-bg4)', border: '1px solid var(--pm-line)', transition: 'all .2s', transform: pin.length === i + 1 ? 'scale(1.2)' : 'scale(1)', boxShadow: pin.length > i ? '0 4px 12px rgba(124,92,255,0.5)' : 'none' }}/>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, maxWidth: 280, margin: '0 auto' }}>
        {[1,2,3,4,5,6,7,8,9,'face',0,'x'].map((d, i) => (
          <button key={i} onClick={() => tap(d)} className="pm-tap" aria-label={d === 'face' ? 'Face ID ilə daxil ol' : d === 'x' ? 'Sil' : `Rəqəm ${d}`} style={{ height: 64, borderRadius: 32, border: 'none', background: 'var(--pm-bg3)', color: 'var(--pm-fg)', fontSize: 24, fontWeight: 600, cursor: 'pointer', fontFamily: pmBase.font, display: 'grid', placeItems: 'center' }}>
            {d === 'x' ? <Icon name="chevronLeft" size={20}/> : d === 'face' ? <Icon name="fingerprint" size={24} color={pmBase.brand}/> : d}
          </button>
        ))}
      </div>

      <div style={{ textAlign: 'center', marginTop: 18, fontSize: 11, color: 'var(--pm-fg3)' }}>
        PIN kodunuzu unutdunuz? <span style={{ color: pmBase.brandSoft, fontWeight: 700, cursor: 'pointer' }}>Bərpa et</span>
      </div>
    </div>
  );
};

const ScreenKYC = ({ go }) => {
  const [doneStep, setDone] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setDone(x => x < 4 ? x + 1 : x), 700); return () => clearInterval(t); }, []);
  const steps = [
    { t: 'Şəxsiyyət təsdiq', s: 'FİN: 6A•••••• · Artur Mirqələbəyli' },
    { t: 'Mənzil əlaqələndirilir', s: 'Park Residence · Blok B · Mənzil 47' },
    { t: 'Komendant təsdiqi', s: 'Eldar Həsənov sizi təsdiqlədi' },
    { t: 'Abunə kodları sinxronlaşdırıldı', s: '6 xidmət kodu əlavə edildi' },
  ];
  return (
    <div className="pm-fade pm-themed" style={{ padding: '72px 28px 0', background: 'var(--pm-bg)', minHeight: '100%' }}>
      <div style={{ textAlign: 'center', marginBottom: 36 }}>
        <div style={{ position: 'relative', width: 100, height: 100, margin: '0 auto' }}>
          <Ring value={doneStep / 4} size={100} stroke={6} color={pmBase.ok}>
            <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--pm-fg)' }}>{Math.round(doneStep / 4 * 100)}%</div>
          </Ring>
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: -0.5, color: 'var(--pm-fg)', marginTop: 20 }}>Hesabınız hazırlanır</div>
        <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 4 }}>Bir neçə saniyə...</div>
      </div>
      <div className="pm-stagger">
        {steps.map((s, i) => {
          const d = i < doneStep;
          return (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, marginBottom: 8, background: 'var(--pm-bg3)', borderRadius: 14, border: `1px solid ${d ? 'rgba(16,185,129,0.3)' : 'var(--pm-line)'}`, opacity: i <= doneStep ? 1 : 0.5 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: d ? pmBase.okSoft : 'var(--pm-bg4)', color: d ? pmBase.ok : 'var(--pm-fg3)', display: 'grid', placeItems: 'center' }}>
                {d ? <Icon name="check" size={18}/> : i === doneStep ? <div style={{ width: 14, height: 14, borderRadius: 7, border: '2px solid currentColor', borderTopColor: 'transparent', animation: 'pm-spin 0.8s linear infinite' }}/> : i+1}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--pm-fg)' }}>{s.t}</div>
                <div style={{ fontSize: 11, color: 'var(--pm-fg3)' }}>{s.s}</div>
              </div>
            </div>
          );
        })}
      </div>
      {doneStep === 4 && (
        <div style={{ position: 'absolute', bottom: 44, left: 28, right: 28, animation: 'pm-slide-up .5s ease both' }}>
          <Btn full icon="home" onClick={() => go('home')}>ProMTK-ya daxil ol</Btn>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { ScreenOnboardingPro, ScreenLoginPhone, ScreenOTP, ScreenPIN, ScreenKYC });
