// ProMTK — Enterprise Payments: Hub, Add Subscription, Pay Detail, Debts, Notifications
// FIXED: absolute→sticky CTAs, disabled state, touch targets, input format, empty states,
// loading spinner, back nav logic, dynamic balance, bottom safe padding.

// ═════════════════════════════════════════════════════════════
// Ödənişlər Hub
// ═════════════════════════════════════════════════════════════
const ScreenPaymentsPro = ({ go }) => {
  const { apartments, currentAptId, setCurrentAptId, subs, categoryCfg } = usePM();
  const [scope, setScope] = React.useState('current');

  const scopedAparts = scope === 'current' ? apartments.filter(a => a.id === currentAptId) : apartments;
  const allScopedSubs = scopedAparts.flatMap(a => (pmAppData.subscriptions[a.id] || []).map(s => ({ ...s, apt: a })));
  const pending = allScopedSubs.filter(s => s.state !== 'paid');
  const overdue = allScopedSubs.filter(s => s.state === 'overdue');
  const total = pending.reduce((a, b) => a + b.balance, 0);
  const animated = useCount(total, 800);

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', paddingBottom: 24 }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('home')} aria-label="Geri"/>
        <h1 style={{ flex: 1, margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Ödənişlər</h1>
        <IconBtn name="chart" size={44} iconSize={16} bg="var(--pm-chipBg)" aria-label="Statistika"/>
        <IconBtn name="plus" size={44} iconSize={18} bg={pmBase.gradient} color="#fff" onClick={() => go('addSub')} aria-label="Kod əlavə et"/>
      </div>

      <div style={{ padding: '16px 20px 0' }}>
        <Segmented value={scope} onChange={setScope} tabs={[
          { id: 'current', label: 'Cari mənzil' },
          { id: 'all', label: `Bütün (${apartments.length})` },
        ]}/>
      </div>

      <div style={{ padding: '16px 20px 0' }}>
        <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 24, background: overdue.length > 0 ? 'linear-gradient(135deg, #7F1D1D, #450A0A)' : pmBase.gradientEnterprise, padding: 20, color: '#fff' }}>
          <div style={{ position: 'absolute', top: -40, right: -60, width: 180, height: 180, borderRadius: 90, background: 'rgba(255,255,255,0.08)', animation: 'pm-float-slow 10s ease-in-out infinite' }}/>
          <div style={{ position: 'relative' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>
              <div>
                <div style={{ fontSize: 11, opacity: .8, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase' }}>Ümumi ödəniləcək</div>
                <div style={{ fontSize: 42, fontWeight: 900, letterSpacing: -1.8, marginTop: 2, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{animated.toFixed(2)} <span style={{ fontSize: 20, opacity: .7 }}>₼</span></div>
              </div>
              {overdue.length > 0 && <Pill color="#fff" bg="rgba(255,255,255,0.2)" style={{ color: '#fff' }}>{overdue.length} gecikmiş</Pill>}
            </div>
            <div style={{ display: 'flex', gap: 16, marginTop: 16, fontSize: 12, opacity: .85 }}>
              <div><b style={{ fontSize: 14, opacity: 1 }}>{pending.length}</b> gözləyir</div>
              <div>·</div>
              <div><b style={{ fontSize: 14, opacity: 1 }}>{allScopedSubs.length}</b> aktiv kod</div>
            </div>
            <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
              <Btn variant="ghost" disabled={pending.length === 0} style={{ flex: 1, background: '#fff', color: pmBase.brandDeep, opacity: pending.length === 0 ? .5 : 1 }} icon="wallet" onClick={() => pending.length > 0 && go('payDetail')}>Hamısını ödə</Btn>
              <Btn variant="ghost" style={{ background: 'rgba(255,255,255,0.18)', color: '#fff' }} icon="filter">Filtr</Btn>
            </div>
          </div>
        </div>
      </div>

      {scope === 'all' && (
        <div style={{ padding: '20px 0 0' }}>
          <SectionHeader title="Mənzillər üzrə" subtitle={`${scopedAparts.length} obyekt`}/>
          <div style={{ padding: '0 20px', display: 'flex', gap: 10, overflowX: 'auto' }} className="pm-scroll">
            {apartments.map(a => {
              const aSubs = pmAppData.subscriptions[a.id] || [];
              const aPending = aSubs.filter(s => s.state !== 'paid').reduce((x, y) => x + y.balance, 0);
              const aOverdue = aSubs.some(s => s.state === 'overdue');
              return (
                <button key={a.id} onClick={() => setCurrentAptId(a.id)} className="pm-tap" style={{ minWidth: 220, padding: 14, background: 'var(--pm-bg3)', border: `2px solid ${a.id === currentAptId ? a.color : 'var(--pm-line)'}`, borderRadius: 16, cursor: 'pointer', textAlign: 'left', fontFamily: pmBase.font, position: 'relative', overflow: 'hidden' }}>
                  <div style={{ position: 'absolute', top: -20, right: -20, width: 80, height: 80, borderRadius: 40, background: `${a.color}1f`, filter: 'blur(8px)' }}/>
                  <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 32, height: 32, borderRadius: 9, background: `linear-gradient(135deg, ${a.color}, ${a.color}aa)`, color: '#fff', display: 'grid', placeItems: 'center' }}><Icon name="building" size={15}/></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--pm-fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</div>
                      <div style={{ fontSize: 10, color: 'var(--pm-fg3)' }}>Mənzil {a.unit}</div>
                    </div>
                    {aOverdue && <Icon name="alert" size={14} color={pmBase.danger}/>}
                  </div>
                  <div style={{ fontSize: 22, fontWeight: 900, color: aOverdue ? pmBase.danger : 'var(--pm-fg)', marginTop: 10, letterSpacing: -0.6, fontVariantNumeric: 'tabular-nums' }}>{aPending.toFixed(2)} ₼</div>
                  <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2 }}>{aSubs.filter(s => s.state !== 'paid').length} kateqoriya</div>
                </button>
              );
            })}
          </div>
        </div>
      )}

      <div style={{ padding: '20px 0 20px' }}>
        <SectionHeader title="Abunə kodları və borclar" action="Kod əlavə et" onAction={() => go('addSub')}/>
        <div style={{ padding: '0 20px' }}>
          {allScopedSubs.length === 0 && (
            <div style={{ padding: '32px 20px', textAlign: 'center', background: 'var(--pm-bg3)', borderRadius: 18, border: '1px dashed var(--pm-lineStrong)' }}>
              <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--pm-bg4)', color: 'var(--pm-fg3)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}><Icon name="key" size={24}/></div>
              <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--pm-fg)' }}>Hələ abunə kodu yoxdur</div>
              <div style={{ fontSize: 12, color: 'var(--pm-fg3)', marginTop: 4, lineHeight: 1.5 }}>Kommunal xidmət kodlarınızı əlavə edin və avtomatik borc bildirişi alın.</div>
              <Btn onClick={() => go('addSub')} icon="plus" style={{ marginTop: 14 }}>İlk kodu əlavə et</Btn>
            </div>
          )}

          {/* Group by category: kommunal (water/gas/power/internet/heat) vs bina (mtk/parking) */}
          {[
            { id: 'utility', title: 'Kommunal xidmətlər', sub: 'Su · Qaz · İşıq · İnternet', icon: 'drop', color: pmBase.water, types: ['water','gas','power','internet','heat'] },
            { id: 'building', title: 'Bina və xidmət haqqları', sub: 'MTK · Parkinq · Təmir', icon: 'building', color: pmBase.brand, types: ['mtk','parking'] },
          ].map(group => {
            const items = allScopedSubs.filter(s => group.types.includes(s.type));
            if (items.length === 0) return null;
            const groupTotal = items.filter(s => s.state !== 'paid').reduce((a, b) => a + b.balance, 0);
            return (
              <div key={group.id} style={{ marginBottom: 18 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 4px 10px' }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: `${group.color}22`, color: group.color, display: 'grid', placeItems: 'center' }}>
                    <Icon name={group.icon} size={14}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)' }}>{group.title}</div>
                    <div style={{ fontSize: 10, color: 'var(--pm-fg3)' }}>{group.sub}</div>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 800, color: groupTotal > 0 ? 'var(--pm-fg)' : pmBase.ok, fontVariantNumeric: 'tabular-nums' }}>{groupTotal.toFixed(2)} ₼</div>
                </div>
                <div className="pm-stagger">
                {items.map(s => {
                  const cat = categoryCfg[s.type];
                  const statusCfg = { due: { c: pmBase.warn, t: 'Gözləyir' }, overdue: { c: pmBase.danger, t: 'Gecikmiş' }, paid: { c: pmBase.ok, t: 'Ödənilib' } }[s.state];
                  return (
                    <div key={s.id} onClick={() => go('payDetail')} className="pm-tap-soft" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: 'var(--pm-bg3)', border: `1px solid ${s.state === 'overdue' ? pmBase.danger + '55' : 'var(--pm-line)'}`, borderRadius: 16, marginBottom: 8, cursor: 'pointer', position: 'relative', overflow: 'hidden' }}>
                      {s.state === 'overdue' && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: pmBase.danger, boxShadow: `0 0 14px ${pmBase.danger}` }}/>}
                      <div style={{ width: 44, height: 44, borderRadius: 13, background: `${cat.color}22`, color: cat.color, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                        <Icon name={cat.icon} size={20}/>
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cat.name}</div>
                          {scope === 'all' && <span style={{ fontSize: 9, padding: '2px 6px', background: `${s.apt.color}22`, color: s.apt.color, borderRadius: 5, fontWeight: 700, whiteSpace: 'nowrap' }}>{s.apt.name.split(' ')[0]}</span>}
                        </div>
                        <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2, fontFamily: pmBase.mono, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>№ {s.code}</div>
                        <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.provider}</div>
                      </div>
                      <div style={{ textAlign: 'right', flexShrink: 0 }}>
                        <div style={{ fontSize: 16, fontWeight: 800, color: s.state === 'overdue' ? pmBase.danger : 'var(--pm-fg)', fontVariantNumeric: 'tabular-nums' }}>{s.balance.toFixed(2)} ₼</div>
                        <div style={{ fontSize: 10, fontWeight: 700, color: statusCfg.c, marginTop: 2, display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'flex-end', whiteSpace: 'nowrap' }}>
                          <span style={{ width: 5, height: 5, borderRadius: 3, background: statusCfg.c }}/>{statusCfg.t}
                        </div>
                      </div>
                    </div>
                  );
                })}
                </div>
              </div>
            );
          })}

          {allScopedSubs.length > 0 && (
            <button onClick={() => go('addSub')} className="pm-tap" style={{ width: '100%', padding: 16, background: 'transparent', border: '1.5px dashed var(--pm-lineStrong)', borderRadius: 16, color: 'var(--pm-fg2)', fontSize: 13, fontWeight: 700, fontFamily: pmBase.font, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 4 }}>
              <Icon name="key" size={16}/> Yeni kommunal abunə kodu əlavə et
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

// ═════════════════════════════════════════════════════════════
// Abunə Kodu Əlavə Et — wizard (FIXED: sticky CTA, input format, disabled, spinner, dynamic balance)
// ═════════════════════════════════════════════════════════════
// Real Azərbaycan utility subscriber code formats
const PROVIDERS = { water: 'Azərsu ASC', gas: '"Azəriqaz" MMC', power: '"Azərişıq" ASC', internet: 'Baktelecom', mtk: 'Mənzil-Tikinti Kooperativi', parking: 'Bina parkinqi', heat: '"Azəristilik" ASC' };
const CODE_FORMAT = {
  water:    { len: 7,  sample: '7654321' },
  gas:      { len: 8,  sample: '88521208' },
  power:    { len: 10, sample: '2240301881' },
  internet: { len: 9,  sample: '442100408' },
  mtk:      { len: 7,  sample: 'B470120' },
  parking:  { len: 6,  sample: 'B2P047' },
  heat:     { len: 8,  sample: '15440201' },
};

const formatSubCode = (raw, type) => {
  const cfg = CODE_FORMAT[type] || CODE_FORMAT.water;
  const clean = (raw || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, cfg.len + 2);
  if (type === 'mtk' || type === 'parking') {
    return clean.replace(/^(.{1,2})(.{0,2})(.{0,4}).*/, (m, a, b, c) => [a, b, c].filter(Boolean).join('-'));
  }
  if (cfg.len === 10) return clean.replace(/^(.{0,3})(.{0,3})(.{0,4}).*/, (m, a, b, c) => [a, b, c].filter(Boolean).join(' '));
  if (cfg.len === 9)  return clean.replace(/^(.{0,3})(.{0,3})(.{0,3}).*/, (m, a, b, c) => [a, b, c].filter(Boolean).join(' '));
  if (cfg.len === 8)  return clean.replace(/^(.{0,4})(.{0,4}).*/,        (m, a, b)    => [a, b].filter(Boolean).join(' '));
  return clean.replace(/^(.{0,4})(.{0,3}).*/, (m, a, b) => [a, b].filter(Boolean).join(' '));
};

const ScreenAddSubscription = ({ go }) => {
  const { currentApt, categoryCfg } = usePM();
  const [step, setStep] = React.useState(0);
  const [type, setType] = React.useState(null);
  const [code, setCode] = React.useState('');
  const [verifying, setVerifying] = React.useState(false);
  const [resolved, setResolved] = React.useState(null); // { balance, due, provider }

  const types = Object.keys(categoryCfg);
  const codeMinLen = (CODE_FORMAT[type] || {}).len || 7;
  const codeValid = code.replace(/[^A-Z0-9]/g, '').length >= codeMinLen;

  const doVerify = () => {
    if (!codeValid || verifying) return;
    setVerifying(true);
    setTimeout(() => {
      setVerifying(false);
      // Simulate resolved data
      const mockBalance = (Math.random() * 60 + 10).toFixed(2);
      setResolved({
        balance: parseFloat(mockBalance),
        due: '30 Apr 2026',
        provider: PROVIDERS[type],
      });
      setStep(2);
    }, 1400);
  };

  const handleBack = () => {
    if (step === 2) { go('pay'); return; } // Success → back to hub (don't re-verify)
    if (step > 0) { setStep(step - 1); return; }
    go('pay');
  };

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={handleBack} aria-label="Geri"/>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Abunə kodu əlavə et</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>Addım {step + 1} / 3 · {currentApt.name}</div>
        </div>
      </div>

      {/* Progress */}
      <div style={{ padding: '14px 20px 0', flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 4 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: i <= step ? pmBase.gradient : 'var(--pm-bg4)', transition: 'background .4s' }}/>
          ))}
        </div>
      </div>

      {/* Scrollable body */}
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 100 }} className="pm-scroll">
        {step === 0 && (
          <div key="s0" style={{ padding: '24px 20px', animation: 'pm-slide-right .4s ease both' }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.5 }}>Xidməti seçin</div>
            <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 4, lineHeight: 1.5 }}>Hansı xidmət üçün abunə kodu əlavə edirsiniz?</div>
            <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }} className="pm-stagger">
              {types.map(t => {
                const cfg = categoryCfg[t];
                const active = type === t;
                return (
                  <button key={t} onClick={() => setType(t)} className="pm-tap" aria-pressed={active} style={{ padding: 16, background: 'var(--pm-bg3)', border: `2px solid ${active ? cfg.color : 'var(--pm-line)'}`, borderRadius: 16, cursor: 'pointer', textAlign: 'left', fontFamily: pmBase.font, position: 'relative', overflow: 'hidden', boxShadow: active ? `0 10px 24px -8px ${cfg.color}80` : 'none', minHeight: 112 }}>
                    {active && <div style={{ position: 'absolute', top: 8, right: 8, width: 22, height: 22, borderRadius: 11, background: cfg.color, color: '#fff', display: 'grid', placeItems: 'center', animation: 'pm-pop .25s ease' }}><Icon name="check" size={12}/></div>}
                    <div style={{ width: 40, height: 40, borderRadius: 12, background: `${cfg.color}22`, color: cfg.color, display: 'grid', placeItems: 'center' }}><Icon name={cfg.icon} size={20}/></div>
                    <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--pm-fg)', marginTop: 10 }}>{cfg.name}</div>
                    <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2 }}>Avto-borc izləmə</div>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {step === 1 && (
          <div key="s1" style={{ padding: '24px 20px', animation: 'pm-slide-right .4s ease both' }}>
            <div style={{ width: 64, height: 64, borderRadius: 18, background: `${categoryCfg[type].color}22`, color: categoryCfg[type].color, display: 'grid', placeItems: 'center', margin: '0 auto 16px', animation: 'pm-breathe 2s ease-in-out infinite' }}>
              <Icon name={categoryCfg[type].icon} size={28}/>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.5 }}>{categoryCfg[type].name} kodu</div>
              <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 4, lineHeight: 1.5, maxWidth: 280, margin: '4px auto 0' }}>Abonent kodunuzu qəbzdə tapa bilərsiniz</div>
            </div>

            <div style={{ marginTop: 24, padding: 20, background: 'var(--pm-bg3)', borderRadius: 18, border: `2px solid ${code ? categoryCfg[type].color + '66' : 'var(--pm-line)'}`, transition: 'border-color .2s' }}>
              <label htmlFor="pm-sub-code" style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Abunə kodu</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                <input
                  id="pm-sub-code"
                  value={code}
                  onChange={e => setCode(formatSubCode(e.target.value, type))}
                  placeholder={CODE_FORMAT[type].sample}
                  autoComplete="off"
                  inputMode={type === 'mtk' || type === 'parking' ? 'text' : 'numeric'}
                  maxLength={18}
                  style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', color: 'var(--pm-fg)', fontSize: 22, fontWeight: 700, outline: 'none', fontFamily: pmBase.mono, letterSpacing: 2, WebkitTextFillColor: 'var(--pm-fg)', caretColor: pmBase.brand }}
                />
                <button onClick={() => setCode(formatSubCode(CODE_FORMAT[type].sample, type))} aria-label="Kamera ilə tara" className="pm-tap" style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--pm-bg4)', border: 'none', color: 'var(--pm-fg2)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="camera" size={18}/></button>
                <button onClick={() => setCode(formatSubCode(CODE_FORMAT[type].sample, type))} aria-label="QR oxu" className="pm-tap" style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--pm-bg4)', border: 'none', color: 'var(--pm-fg2)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="qr" size={18}/></button>
              </div>
              {code && !codeValid && (
                <div style={{ fontSize: 11, color: pmBase.warn, marginTop: 6, display: 'flex', alignItems: 'center', gap: 4 }}>
                  <Icon name="alert" size={12}/> {CODE_FORMAT[type].len} simvol daxil edin (nümunə: {CODE_FORMAT[type].sample})
                </div>
              )}
              <div style={{ height: 1, background: 'var(--pm-line)', margin: '14px 0' }}/>
              <label style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Təchizatçı</label>
              <div style={{ fontSize: 15, color: 'var(--pm-fg)', fontWeight: 700, marginTop: 6 }}>{PROVIDERS[type]}</div>
            </div>

            <div style={{ marginTop: 14, padding: 14, background: pmBase.infoSoft, borderRadius: 14, display: 'flex', gap: 10 }}>
              <div style={{ color: pmBase.info, flexShrink: 0 }}><Icon name="sparkle" size={18}/></div>
              <div style={{ fontSize: 11, color: 'var(--pm-fg2)', lineHeight: 1.5 }}>Kod təsdiqləndikdən sonra <b style={{ color: 'var(--pm-fg)' }}>avtomatik borc bildirişi</b> aktivləşəcək. Yeni qəbz gələn kimi push bildiriş alacaqsınız.</div>
            </div>
          </div>
        )}

        {step === 2 && resolved && (
          <div key="s2" style={{ padding: '32px 20px', textAlign: 'center', animation: 'pm-slide-right .5s ease both' }}>
            <div style={{ position: 'relative', width: 120, height: 120, margin: '0 auto 24px' }}>
              {[0, 1, 2].map(i => <div key={i} style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: `2px solid ${pmBase.ok}`, animation: 'pm-pulse-ring 2.4s ease-out infinite', animationDelay: `${i * 0.6}s` }}/>)}
              <div style={{ position: 'absolute', inset: 16, borderRadius: '50%', background: `linear-gradient(135deg, ${pmBase.ok}, #059669)`, display: 'grid', placeItems: 'center', boxShadow: `0 20px 40px -12px ${pmBase.ok}80` }}>
                <Icon name="check" size={40} color="#fff"/>
              </div>
            </div>
            <div style={{ fontSize: 26, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.6 }}>Kod təsdiqləndi!</div>
            <div style={{ fontSize: 14, color: 'var(--pm-fg2)', marginTop: 8, maxWidth: 280, margin: '8px auto 0', lineHeight: 1.5 }}>Abonent məlumatı tapıldı. Artıq avtomatik borc bildirişləri alacaqsınız.</div>

            <div style={{ marginTop: 28, padding: 16, background: 'var(--pm-bg3)', border: `1px solid ${pmBase.ok}44`, borderRadius: 16, textAlign: 'left' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: `${categoryCfg[type].color}22`, color: categoryCfg[type].color, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={categoryCfg[type].icon} size={18}/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)' }}>{categoryCfg[type].name} · {resolved.provider}</div>
                  <div style={{ fontSize: 10, color: 'var(--pm-fg3)', fontFamily: pmBase.mono, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{code}</div>
                </div>
                <Pill color={pmBase.ok}>Aktiv</Pill>
              </div>
              <div style={{ marginTop: 14, padding: 12, background: 'var(--pm-bg)', borderRadius: 10 }}>
                <div style={{ fontSize: 11, color: 'var(--pm-fg3)' }}>Cari qalıq</div>
                <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pm-fg)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{resolved.balance.toFixed(2)} ₼</div>
                <div style={{ fontSize: 11, color: pmBase.warn, marginTop: 2 }}>Son tarix: {resolved.due}</div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Sticky CTA — stays above content */}
      <div style={{ position: 'sticky', bottom: 0, left: 0, right: 0, padding: '12px 20px 24px', background: 'linear-gradient(to top, var(--pm-bg) 70%, transparent)', flexShrink: 0 }}>
        {step === 0 && (
          <Btn full icon="arrowRight" disabled={!type} onClick={() => type && setStep(1)}>Davam et</Btn>
        )}
        {step === 1 && (
          <Btn full icon={verifying ? null : 'shieldCheck'} disabled={!codeValid || verifying} onClick={doVerify}>
            {verifying ? (<><span className="pm-spin" style={{ display: 'inline-block', width: 14, height: 14, border: '2px solid #fff', borderTopColor: 'transparent', borderRadius: 7, marginRight: 8, verticalAlign: -2 }}/> Yoxlanılır...</>) : 'Kodu təsdiq et'}
          </Btn>
        )}
        {step === 2 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Btn variant="secondary" onClick={() => go('pay')} full>Hazır</Btn>
            <Btn icon="wallet" onClick={() => go('payDetail')} full>İndi ödə</Btn>
          </div>
        )}
      </div>
    </div>
  );
};

// ═════════════════════════════════════════════════════════════
// Bildirişlər
// ═════════════════════════════════════════════════════════════
const ScreenNotificationsPro = ({ go }) => {
  const { allNotifications, markNotifRead, apartments } = usePM();
  const [filter, setFilter] = React.useState('all');

  const counts = {
    all: allNotifications.length,
    debt: allNotifications.filter(n => n.kind === 'debt').length,
    unread: allNotifications.filter(n => n.unread).length,
  };
  const filtered = filter === 'all' ? allNotifications : filter === 'debt' ? allNotifications.filter(n => n.kind === 'debt') : allNotifications.filter(n => n.unread);
  const debts = allNotifications.filter(n => n.kind === 'debt');
  const totalDebt = debts.reduce((a, b) => a + (b.amount || 0), 0);
  const animated = useCount(totalDebt, 800);

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', paddingBottom: 24 }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('home')} aria-label="Geri"/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Bildirişlər</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>{counts.unread} yeni · {apartments.length} mənzil</div>
        </div>
        <IconBtn name="settings" size={44} iconSize={16} bg="var(--pm-chipBg)" aria-label="Ayarlar"/>
        <IconBtn name="check2" size={44} iconSize={16} bg="var(--pm-chipBg)" onClick={() => allNotifications.forEach(n => markNotifRead(n.id))} aria-label="Hamısını oxu"/>
      </div>

      {debts.length > 0 && (
        <div style={{ padding: '18px 20px 0' }}>
          <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 22, padding: 18, background: 'linear-gradient(135deg, #7F1D1D, #450A0A)', color: '#fff' }}>
            <div style={{ position: 'absolute', top: -30, right: -30, width: 140, height: 140, borderRadius: 70, background: 'rgba(255,255,255,0.06)', animation: 'pm-float-slow 9s ease-in-out infinite' }}/>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(255,255,255,0.15)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="alert" size={18} color="#fff"/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 11, opacity: .8, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Borc xəbərdarlıqları</div>
                  <div style={{ fontSize: 13, fontWeight: 700, opacity: .9, marginTop: 2 }}>{debts.length} aktiv bildiriş</div>
                </div>
              </div>
              <div style={{ fontSize: 34, fontWeight: 900, letterSpacing: -1.2, marginTop: 14, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{animated.toFixed(2)} <span style={{ fontSize: 18, opacity: .7 }}>₼</span></div>
              <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                <Btn variant="ghost" style={{ flex: 1, background: '#fff', color: '#7F1D1D' }} icon="wallet" onClick={() => go('pay')}>Hamısını ödə</Btn>
                <Btn variant="ghost" style={{ background: 'rgba(255,255,255,0.18)', color: '#fff' }}>Plan qur</Btn>
              </div>
            </div>
          </div>
        </div>
      )}

      <div style={{ padding: '16px 20px 0', display: 'flex', gap: 6, overflowX: 'auto' }} className="pm-scroll">
        {[{i:'all',t:`Hamısı · ${counts.all}`},{i:'unread',t:`Yeni · ${counts.unread}`},{i:'debt',t:`Borc · ${counts.debt}`}].map(f => (
          <Chip key={f.i} active={filter === f.i} onClick={() => setFilter(f.i)}>{f.t}</Chip>
        ))}
      </div>

      <div style={{ padding: '16px 20px 20px' }} className="pm-stagger">
        {filtered.length === 0 && (
          <div style={{ padding: '40px 20px', textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--pm-bg3)', color: 'var(--pm-fg3)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}><Icon name="check2" size={24}/></div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--pm-fg)' }}>Bu filterdə bildiriş yoxdur</div>
          </div>
        )}
        {filtered.map(n => {
          const sev = { critical: pmBase.danger, high: pmBase.warn, warn: pmBase.warn, info: pmBase.info, low: pmBase.fg3 }[n.sev] || pmBase.info;
          const icon = { debt: 'wallet', maintenance: 'drop', komendant: 'message', guest: 'qr', vote: 'vote', info: 'info' }[n.kind];
          const apt = apartments.find(a => a.id === n.apt);
          return (
            <div key={n.id} onClick={() => markNotifRead(n.id)} className="pm-tap-soft" style={{ display: 'flex', gap: 12, padding: 14, background: 'var(--pm-bg3)', border: `1px solid ${n.unread ? sev + '44' : 'var(--pm-line)'}`, borderRadius: 16, marginBottom: 8, cursor: 'pointer', position: 'relative', overflow: 'hidden' }}>
              {n.unread && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: sev, boxShadow: `0 0 12px ${sev}` }}/>}
              <div style={{ width: 42, height: 42, borderRadius: 12, background: `${sev}22`, color: sev, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={icon} size={18}/></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{n.title}</div>
                  {n.amount != null && <div style={{ fontSize: 14, fontWeight: 800, color: sev, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{n.amount.toFixed(2)} ₼</div>}
                </div>
                <div style={{ fontSize: 11, color: 'var(--pm-fg2)', marginTop: 4, lineHeight: 1.4 }}>{n.desc}</div>
                <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  {apt && <span style={{ fontSize: 10, padding: '3px 8px', background: `${apt.color}22`, color: apt.color, borderRadius: 6, fontWeight: 700, whiteSpace: 'nowrap' }}>{apt.name}</span>}
                  <span style={{ fontSize: 10, color: 'var(--pm-fg3)', whiteSpace: 'nowrap' }}>{n.date}</span>
                  {n.unread && <span style={{ fontSize: 10, color: sev, fontWeight: 700, whiteSpace: 'nowrap' }}>• Yeni</span>}
                </div>
                {n.action === 'pay' && (
                  <div style={{ marginTop: 10, display: 'flex', gap: 6 }}>
                    <Btn variant="primary" onClick={e => { e.stopPropagation(); go('payDetail'); }} style={{ padding: '9px 14px', fontSize: 12, flex: 1, minHeight: 0 }} icon="wallet">İndi ödə</Btn>
                    <Btn variant="secondary" onClick={e => e.stopPropagation()} style={{ padding: '9px 14px', fontSize: 12, minHeight: 0 }}>Sonra</Btn>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { ScreenPaymentsPro, ScreenAddSubscription, ScreenNotificationsPro });
