// ProMTK — Enterprise Home + Apartment Switcher + Komendant widget + Status panels

// Animated number + counter hook (instant on first render, animates on changes)
const useCount = (target, dur = 600) => {
  const [v, setV] = React.useState(target);
  const prev = React.useRef(target);
  React.useEffect(() => {
    if (prev.current === target) return;
    const from = prev.current;
    const start = performance.now();
    const run = (now) => {
      const t = Math.min(1, (now - start) / dur);
      setV(from + (target - from) * (1 - Math.pow(1 - t, 3)));
      if (t < 1) requestAnimationFrame(run);
    };
    requestAnimationFrame(run);
    prev.current = target;
  }, [target, dur]);
  return v;
};

// ─────────────────────────────────────────────────────────────
// Apartment Switcher — bottom sheet
// ─────────────────────────────────────────────────────────────
const AptSwitcher = ({ open, onClose, onPick, onAdd }) => {
  const { apartments, currentAptId } = usePM();
  if (!open) return null;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 100, background: 'rgba(0,0,0,0.55)', animation: 'pm-fade-in .25s ease' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'var(--pm-bg2)', borderRadius: '24px 24px 0 0', padding: 20, paddingBottom: 28, animation: 'pm-slide-up .35s cubic-bezier(.2,.7,.3,1) both', borderTop: '1px solid var(--pm-line)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 2, background: 'var(--pm-fg4)', margin: '0 auto 18px' }}/>
        <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Mənzillərim</div>
        <div style={{ fontSize: 12, color: 'var(--pm-fg3)', marginTop: 2 }}>{apartments.length} aktiv obyekt · 1 dəvət</div>

        <div className="pm-stagger" style={{ marginTop: 16 }}>
          {apartments.map(a => {
            const active = a.id === currentAptId;
            const statusCfg = { current: { c: pmBase.ok, t: 'Ödənişli' }, overdue: { c: pmBase.danger, t: 'Gecikmə' }, paid: { c: pmBase.ok, t: 'Tam ödənişli' } }[a.status];
            return (
              <div key={a.id} onClick={() => { onPick(a.id); onClose(); }} className="pm-tap" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: active ? 'var(--pm-bg4)' : 'var(--pm-bg3)', borderRadius: 16, marginBottom: 8, border: `2px solid ${active ? a.color : 'var(--pm-line)'}`, cursor: 'pointer', position: 'relative', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', top: 0, right: 0, width: 80, height: 80, background: `radial-gradient(circle at top right, ${a.color}22, transparent 60%)`, pointerEvents: 'none' }}/>
                <div style={{ width: 46, height: 46, borderRadius: 12, background: `linear-gradient(135deg, ${a.color}, ${a.color}aa)`, color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <Icon name="building" size={22}/>
                </div>
                <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--pm-fg)' }}>{a.name}</div>
                    {active && <Icon name="check" size={14} color={a.color}/>}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>Blok {a.block} · Mənzil {a.unit} · {a.area}m² · {a.role}</div>
                  <div style={{ marginTop: 6, display: 'flex', gap: 8, alignItems: 'center' }}>
                    <span style={{ fontSize: 10, fontWeight: 700, color: statusCfg.c, display: 'flex', alignItems: 'center', gap: 4 }}>
                      <span style={{ width: 6, height: 6, borderRadius: 3, background: statusCfg.c }}/>{statusCfg.t}
                    </span>
                    {a.balance > 0 && <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg)' }}>{a.balance.toFixed(2)} ₼</span>}
                  </div>
                </div>
              </div>
            );
          })}
          <button onClick={() => { onAdd && onAdd(); onClose(); }} className="pm-tap" style={{ width: '100%', padding: 14, 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 }}>
            <Icon name="plus" size={16}/> Yeni mənzil əlavə et
          </button>
        </div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// Home — enterprise
// ─────────────────────────────────────────────────────────────
const ScreenHomePro = ({ go }) => {
  const { user, currentApt, allNotifications, subs, setCurrentAptId } = usePM();
  const [switcher, setSwitcher] = React.useState(false);
  const unreadCount = allNotifications.filter(n => n.unread).length;
  const totalDebt = subs.filter(s => s.state !== 'paid').reduce((a, b) => a + b.balance, 0);
  const animatedDebt = useCount(totalDebt, 900);
  const hasOverdue = subs.some(s => s.state === 'overdue');

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%' }}>
      {/* Header */}
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Avatar name={user.name} size={42} status="online"/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 600 }}>Salam,</div>
          <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name.split(' ')[0]} bəy</div>
        </div>
        <IconBtn name="search" size={40} iconSize={18} bg="var(--pm-chipBg)"/>
        <IconBtn name="bell" size={40} iconSize={18} bg="var(--pm-chipBg)" badge={unreadCount} onClick={() => go('notifications')}/>
      </div>

      {/* Apartment switcher chip */}
      <div style={{ padding: '16px 20px 0' }}>
        <button onClick={() => setSwitcher(true)} className="pm-tap" style={{ width: '100%', padding: 14, background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 16, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', fontFamily: pmBase.font }}>
          <div style={{ width: 38, height: 38, borderRadius: 10, background: `linear-gradient(135deg, ${currentApt.color}, ${currentApt.color}aa)`, color: '#fff', display: 'grid', placeItems: 'center' }}><Icon name="building" size={18}/></div>
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--pm-fg)' }}>{currentApt.name}</div>
            <div style={{ fontSize: 11, color: 'var(--pm-fg3)' }}>Blok {currentApt.block} · Mənzil {currentApt.unit} · {currentApt.role}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: 'var(--pm-fg3)' }}>
            <span style={{ fontSize: 10, fontWeight: 700 }}>3</span>
            <Icon name="chevronDown" size={16}/>
          </div>
        </button>
      </div>

      {/* Balance hero */}
      <div style={{ padding: '16px 20px 0' }}>
        <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 24, background: hasOverdue ? 'linear-gradient(135deg, #B91C1C, #7F1D1D)' : pmBase.gradientEnterprise, padding: 20, color: '#fff' }}>
          <div style={{ position: 'absolute', top: -60, right: -60, width: 200, height: 200, borderRadius: '50%', background: 'rgba(255,255,255,0.08)', animation: 'pm-float-slow 8s ease-in-out infinite' }}/>
          <div style={{ position: 'absolute', bottom: -40, left: -30, width: 140, height: 140, borderRadius: '50%', background: 'rgba(255,255,255,0.05)' }}/>
          <div style={{ position: 'relative' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, opacity: .75, letterSpacing: 0.8, textTransform: 'uppercase' }}>{hasOverdue ? 'Gecikmiş borc' : 'Cari borc'}</div>
                <div style={{ fontSize: 38, fontWeight: 900, letterSpacing: -1.5, marginTop: 4, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                  {animatedDebt.toFixed(2)} <span style={{ fontSize: 20, fontWeight: 700, opacity: .75 }}>₼</span>
                </div>
                <div style={{ fontSize: 12, opacity: .85, marginTop: 4 }}>Son tarix: {currentApt.dueAt}</div>
              </div>
              <Ring value={hasOverdue ? 1 : 0.6} size={64} stroke={5} color="#fff" bg="rgba(255,255,255,0.2)">
                <Icon name={hasOverdue ? 'alert' : 'wallet'} size={22} color="#fff"/>
              </Ring>
            </div>
            <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
              <Btn variant="ghost" onClick={() => go('pay')} style={{ flex: 1, background: 'rgba(255,255,255,0.2)', color: '#fff', backdropFilter: 'blur(10px)' }} icon="arrowRight">İndi ödə</Btn>
              <IconBtn name="chart" size={48} iconSize={20} bg="rgba(255,255,255,0.2)" color="#fff" onClick={() => go('stats')} aria-label="Statistika"/>
            </div>
          </div>
        </div>
      </div>

      {/* Komendant widget */}
      <div style={{ padding: '16px 20px 0' }}>
        <Card style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--pm-bg3)' }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <Avatar name={currentApt.komendant.name} size={44}/>
            <div style={{ position: 'absolute', bottom: -2, right: -2, width: 14, height: 14, borderRadius: 7, background: currentApt.komendant.online ? pmBase.ok : pmBase.fg4, border: '2.5px solid var(--pm-bg3)' }}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{currentApt.komendant.name}</div>
              <Icon name="shieldCheck" size={12} color={pmBase.ok}/>
            </div>
            <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2, whiteSpace: 'nowrap' }}>Komendant · {currentApt.komendant.online ? 'Onlayn' : 'Oflayn'}</div>
            <div style={{ fontSize: 11, color: 'var(--pm-fg2)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}>
              <Icon name="clock" size={11}/> 09:00 – 20:00
            </div>
          </div>
          <IconBtn name="message" size={38} iconSize={16} bg={pmBase.brand} color="#fff" onClick={() => go('messages')}/>
          <IconBtn name="phone" size={38} iconSize={16} bg={pmBase.okSoft} color={pmBase.ok}/>
        </Card>
      </div>

      {/* Current status panels */}
      <div style={{ padding: '16px 20px 0', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }} className="pm-stagger">
        <StatTile icon="bolt" color={pmBase.power} label="Bu ay işıq" value="166 kWh" trend={-8}/>
        <StatTile icon="drop" color={pmBase.water} label="Bu ay su" value="25 m³" trend={4}/>
        <StatTile icon="flame" color={pmBase.gas} label="Bu ay qaz" value="49 m³" trend={-12}/>
      </div>

      {/* Cari vəziyyət */}
      <div style={{ padding: '20px 0 0' }}>
        <SectionHeader title="Cari vəziyyət" subtitle="Real-time sensor məlumatları" action="Smart bina" onAction={() => go('smart')}/>
        <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }} className="pm-stagger">
          {[
            { i: 'temperature', t: 'Mənzil', v: '21.4°C', s: 'Normal', c: pmBase.water },
            { i: 'doorOpen', t: 'Giriş qapısı', v: 'Bağlı', s: 'Təhlükəsiz', c: pmBase.ok },
            { i: 'elevator', t: 'Lift A', v: 'Mərtəbə 8', s: 'Yüksəlir', c: pmBase.info },
            { i: 'shieldCheck', t: 'Yanğın sis.', v: 'Aktiv', s: '24/7 işləyir', c: pmBase.ok },
          ].map((s, i) => (
            <div key={i} style={{ padding: 14, background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 16, position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', top: -20, right: -20, width: 60, height: 60, borderRadius: 30, background: `${s.c}18`, filter: 'blur(12px)' }}/>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: `${s.c}22`, color: s.c, display: 'grid', placeItems: 'center' }}><Icon name={s.i} size={14}/></div>
                <div style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 600 }}>{s.t}</div>
              </div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--pm-fg)', marginTop: 8, letterSpacing: -0.3 }}>{s.v}</div>
              <div style={{ fontSize: 10, color: s.c, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 5, height: 5, borderRadius: 3, background: s.c, animation: 'pm-breathe 1.6s ease-in-out infinite' }}/>{s.s}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Quick actions */}
      <div style={{ padding: '20px 0 0' }}>
        <SectionHeader title="Sürətli əməliyyatlar"/>
        <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }} className="pm-stagger">
          {[
            { i: 'qr', t: 'Qonaq', c: pmBase.info, g: 'guest' },
            { i: 'car', t: 'Parkinq', c: pmBase.parking, g: 'parking' },
            { i: 'tool', t: 'Təmir', c: pmBase.warn, g: 'repair' },
            { i: 'vote', t: 'Səsvermə', c: pmBase.brand2, g: 'vote' },
            { i: 'doc', t: 'Sənəd', c: pmBase.info, g: 'docs' },
            { i: 'megaphone', t: 'Şikayət', c: pmBase.danger, g: 'complaint' },
            { i: 'key', t: 'Kod', c: pmBase.ok, g: 'addSub' },
            { i: 'grid', t: 'Hamısı', c: pmBase.fg3, g: 'announcements' },
          ].map((a, i) => (
            <button key={i} onClick={() => go(a.g)} className="pm-tap" style={{ padding: '14px 4px', background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 16, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, fontFamily: pmBase.font }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: `${a.c}22`, color: a.c, display: 'grid', placeItems: 'center' }}><Icon name={a.i} size={18}/></div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--pm-fg2)' }}>{a.t}</div>
            </button>
          ))}
        </div>
      </div>

      {/* Latest alerts */}
      <div style={{ padding: '20px 0 20px' }}>
        <SectionHeader title="Son bildirişlər" action="Hamısı" onAction={() => go('notifications')}/>
        <div style={{ padding: '0 20px' }} className="pm-stagger">
          {allNotifications.slice(0, 3).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];
            return (
              <div key={n.id} onClick={() => go('notifications')} className="pm-tap-soft" style={{ display: 'flex', gap: 12, padding: 14, background: n.unread ? 'var(--pm-bg3)' : 'transparent', border: `1px solid ${n.unread ? sev + '33' : 'var(--pm-line)'}`, borderRadius: 14, marginBottom: 8, cursor: 'pointer', position: 'relative' }}>
                {n.unread && <span style={{ position: 'absolute', top: 12, right: 12, width: 7, height: 7, borderRadius: 4, background: sev, boxShadow: `0 0 10px ${sev}` }}/>}
                <div style={{ width: 36, height: 36, borderRadius: 10, background: `${sev}22`, color: sev, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={icon} size={16}/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--pm-fg)' }}>{n.title}</div>
                  <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{n.desc}</div>
                </div>
                {n.amount && <div style={{ fontSize: 14, fontWeight: 800, color: sev }}>{n.amount.toFixed(0)}₼</div>}
              </div>
            );
          })}
        </div>
      </div>

      <AptSwitcher open={switcher} onClose={() => setSwitcher(false)} onPick={setCurrentAptId} onAdd={() => go('addApartment')}/>
    </div>
  );
};

// Wrapper that wires the switcher's setCurrentAptId via context
const HomeWithSwitcher = ({ go }) => {
  const { setCurrentAptId } = usePM();
  const [switcher, setSwitcher] = React.useState(false);
  // Patch the switcher open state into ScreenHomePro through global bridge
  window.__pmOpenSwitcher = () => setSwitcher(true);
  return (
    <>
      <ScreenHomePro go={go}/>
      <AptSwitcherPortal open={switcher} onClose={() => setSwitcher(false)} onPick={setCurrentAptId} onAdd={() => go('addApt')}/>
    </>
  );
};

const AptSwitcherPortal = AptSwitcher;

Object.assign(window, { ScreenHomePro, AptSwitcher, HomeWithSwitcher });
