(() => {
const { Button, Icon, Field, TextInput, Alert, Logo, Checkbox } = window.AmlakPlusDesignSystem_b3aa85;

const NOTES = [
  { id: 'n0', icon: 'Inbox', title: 'إثبات تحويل جديد من البوابة', body: 'ريم الشهري 2,500 · سعد الحارثي 2,000', when: '09:40', go: 'requests', unread: true },
  { id: 'n1', icon: 'ShieldCheck', title: 'دفعتان بانتظار التحقق', body: 'ريم الشهري 2,500 · منى الحربي 3,200', when: 'منذ ساعة', go: 'collection', unread: true },
  { id: 'n2', icon: 'Handshake', title: 'وعد سداد يستحق اليوم', body: 'خالد العتيبي — 4,000 ر.س', when: '08:00', go: 'today', unread: true },
  { id: 'n3', icon: 'Wrench', title: 'طلب صيانة عاجل', body: 'MR-0412 · تسريب مكيف — عمارة الندى 3 / 201', when: 'أمس', go: 'maintenance', unread: true },
  { id: 'n4', icon: 'CalendarClock', title: 'عقدان ينتهيان خلال 60 يومًا', body: 'ناصر القحطاني · ريم الشهري', when: 'أمس', go: 'leases' },
  { id: 'n5', icon: 'Download', title: 'النسخة الاحتياطية جاهزة', body: 'رابط التنزيل صالح حتى 24/09 10:00', when: 'الأحد', go: 'data' }
];

function usePop() {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => { if (!open) return; const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }; const k = (e) => e.key === 'Escape' && setOpen(false); document.addEventListener('mousedown', h); document.addEventListener('keydown', k); return () => { document.removeEventListener('mousedown', h); document.removeEventListener('keydown', k); }; }, [open]);
  return [open, setOpen, ref];
}

function Notifications({ go }) {
  const [open, setOpen, ref] = usePop();
  const [read, setRead] = React.useState({});
  const unread = NOTES.filter((n) => n.unread && !read[n.id]).length;
  return (
    <div className="kit-pop-wrap" ref={ref}>
      <button type="button" className="ap-btn ap-btn--ghost ap-btn--icon kit-bell" aria-label={'الإشعارات' + (unread ? '، ' + unread + ' غير مقروءة' : '')} aria-expanded={open} onClick={() => setOpen(!open)}><Icon name="Bell" size={18} />{unread > 0 && <span className="kit-bell__dot">{unread}</span>}</button>
      {open && <div className="kit-pop kit-pop--notes" role="dialog" aria-label="الإشعارات">
        <header><strong>الإشعارات</strong><button type="button" className="kit-src" onClick={() => setRead(Object.fromEntries(NOTES.map((n) => [n.id, 1])))}>تعليم الكل كمقروء</button></header>
        <ul>{NOTES.map((n) => <li key={n.id}><button type="button" className={n.unread && !read[n.id] ? 'is-unread' : ''} onClick={() => { setRead((r) => ({ ...r, [n.id]: 1 })); setOpen(false); go(n.go); }}>
          <span className="kit-card__icon" style={{ width: 34, height: 34 }}><Icon name={n.icon} size={16} /></span><span><b>{n.title}</b><small>{n.body}</small></span><time>{n.when}</time></button></li>)}</ul>
      </div>}
    </div>
  );
}

function CommandSearch({ go, openTenant, openUnit, openProperty, openOwner, openLease }) {
  const D = window.AP_DATA;
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const [i, setI] = React.useState(0);
  const inp = React.useRef();
  React.useEffect(() => { const k = (e) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); setOpen(true); } }; document.addEventListener('keydown', k); return () => document.removeEventListener('keydown', k); }, []);
  React.useEffect(() => { if (open) setTimeout(() => inp.current && inp.current.focus(), 30); else { setQ(''); setI(0); } }, [open]);
  const s = q.trim();
  const all = [
    ...D.tenants.map((t) => ({ g: 'المستأجرون', icon: 'User', label: t.name, sub: t.property, run: () => openTenant(t.id) })),
    ...D.leases.map((l) => ({ g: 'العقود', icon: 'FileText', label: 'عقد ' + l.tenant, sub: l.property + ' / ' + l.unit, run: () => openLease(l.id) })),
    ...D.allUnits.map((u) => ({ g: 'الوحدات', icon: 'DoorOpen', label: 'وحدة ' + u.u, sub: u.property, run: () => openUnit(u.id) })),
    ...D.properties.map((p) => ({ g: 'العقارات', icon: 'Building2', label: p.name, sub: p.city + ' · ' + p.district, run: () => openProperty(p.id) })),
    ...D.owners.map((o) => ({ g: 'الملاك', icon: 'Landmark', label: o.name, sub: o.phone, run: () => openOwner(o.id) })),
    ...D.payments.filter((p) => p.receipt).map((p) => ({ g: 'السندات', icon: 'ReceiptText', label: 'سند ' + p.receipt, sub: p.tenant + ' · ' + p.amount.toLocaleString('en-US') + ' ر.س', run: () => go('collection') }))
  ];
  const quick = [{ g: 'إجراءات سريعة', icon: 'Banknote', label: 'تسجيل دفعة', run: () => window.apPay() }, { g: 'إجراءات سريعة', icon: 'Plus', label: 'إنشاء عقد', run: () => window.apOpen('lease') }, { g: 'إجراءات سريعة', icon: 'Wallet', label: 'تسجيل مصروف', run: () => window.apOpen('expense') }, { g: 'إجراءات سريعة', icon: 'Wrench', label: 'طلب صيانة', run: () => window.apOpen('maintenance') }];
  const res = s ? all.filter((r) => (r.label + ' ' + (r.sub || '')).includes(s)).slice(0, 12) : quick;
  const pick = (r) => { setOpen(false); setTimeout(r.run, 20); };
  const key = (e) => { if (e.key === 'ArrowDown') { e.preventDefault(); setI((x) => Math.min(res.length - 1, x + 1)); } else if (e.key === 'ArrowUp') { e.preventDefault(); setI((x) => Math.max(0, x - 1)); } else if (e.key === 'Enter' && res[i]) pick(res[i]); else if (e.key === 'Escape') setOpen(false); };
  let lastG = '';
  return (
    <>
      <button type="button" className="kit-cmd-trigger" onClick={() => setOpen(true)}><Icon name="Search" size={15} /><span>بحث في المستأجرين، العقود، الوحدات، السندات</span><kbd>Ctrl K</kbd></button>
      <button type="button" className="ap-btn ap-btn--ghost ap-btn--icon kit-cmd-icon" aria-label="بحث" onClick={() => setOpen(true)}><Icon name="Search" size={18} /></button>
      {open && <div className="kit-cmd-scrim" onMouseDown={(e) => e.target === e.currentTarget && setOpen(false)}>
        <div className="kit-cmd" role="dialog" aria-label="بحث شامل">
          <label className="kit-cmd__input"><Icon name="Search" size={18} /><input ref={inp} value={q} onChange={(e) => { setQ(e.target.value); setI(0); }} onKeyDown={key} placeholder="اسم، رقم وحدة، رقم سند، جوال…" aria-label="بحث شامل" /><kbd>Esc</kbd></label>
          <ul role="listbox">{res.map((r, n) => { const head = r.g !== lastG; lastG = r.g; return <React.Fragment key={r.g + r.label + n}>{head && <li className="kit-cmd__g" role="presentation">{r.g}</li>}
            <li role="option" aria-selected={n === i}><button type="button" onMouseEnter={() => setI(n)} onClick={() => pick(r)}><Icon name={r.icon} size={16} /><span>{r.label}</span>{r.sub && <small>{r.sub}</small>}</button></li></React.Fragment>; })}
            {!res.length && <li className="kit-cmd__empty">لا نتائج لـ «{s}». جرّب رقم الجوال أو رقم الوحدة.</li>}</ul>
        </div>
      </div>}
    </>
  );
}

function AccountMenu({ onLogout }) {
  const D = window.AP_DATA;
  const [open, setOpen, ref] = usePop();
  return (
    <div className="kit-pop-wrap kit-account-wrap" ref={ref}>
      {open && <div className="kit-pop kit-pop--account" role="menu">
        <button type="button" role="menuitem" onClick={() => { setOpen(false); window.apOpen('profile'); }}><Icon name="User" size={16} />الملف الشخصي</button>
        <button type="button" role="menuitem" onClick={() => { setOpen(false); window.apOpen('password'); }}><Icon name="Lock" size={16} />تغيير كلمة المرور</button>
        <button type="button" role="menuitem" onClick={() => { setOpen(false); window.apOpen('notifPrefs'); }}><Icon name="Bell" size={16} />تفضيلات الإشعارات</button>
        <hr />
        <button type="button" role="menuitem" className="is-danger" onClick={() => { setOpen(false); onLogout(); }}><Icon name="LogOut" size={16} />تسجيل الخروج</button>
      </div>}
      <button type="button" className="kit-account" aria-expanded={open} aria-haspopup="menu" onClick={() => setOpen(!open)}>
        <span className="kit-avatar" aria-hidden="true">س</span>
        <span style={{ minWidth: 0, flex: 1, textAlign: 'start' }}><strong style={{ display: 'block', fontSize: 13 }}>{D.user.name}</strong><span style={{ fontSize: 12, color: 'var(--text-3)' }}>{D.user.role} · {D.org}</span></span>
        <Icon name="ChevronUp" size={15} />
      </button>
    </div>
  );
}

function LoginScreen({ onLogin }) {
  const [step, setStep] = React.useState('phone');
  const [phone, setPhone] = React.useState('0551110001');
  const [code, setCode] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const next = () => { setErr(''); if (step === 'phone' && phone.replace(/\D/g, '').length !== 10) { setErr('أدخل رقم جوال من 10 أرقام يبدأ بـ 05'); return; } if (step === 'otp' && code.length !== 4) { setErr('الرمز من 4 أرقام'); return; } setBusy(true); setTimeout(() => { setBusy(false); step === 'phone' ? setStep('otp') : step === 'otp' ? setStep('org') : onLogin(); }, 700); };
  return (
    <div className="kit-login">
      <section className="kit-login__card">
        <Logo base="../../" width={150} tagline />
        {step === 'phone' && <><h1>تسجيل الدخول</h1><p>أدخل جوالك المسجل لدى المكتب؛ يصلك رمز تحقق.</p>
          <Field label="رقم الجوال" error={err}><TextInput ltr inputMode="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="05XXXXXXXX" /></Field></>}
        {step === 'otp' && <><h1>رمز التحقق</h1><p>أُرسل إلى <bdi className="ap-num">{phone}</bdi> · <button type="button" className="kit-src" onClick={() => setStep('phone')}>تغيير الرقم</button></p>
          <Field label="الرمز" hint="للتجربة: أي 4 أرقام" error={err}><TextInput ltr inputMode="numeric" maxLength={4} value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))} placeholder="••••" style={{ letterSpacing: 8, fontSize: 20, textAlign: 'center' }} /></Field>
          <button type="button" className="kit-src" style={{ justifySelf: 'start' }}>إعادة الإرسال بعد 0:42</button></>}
        {step === 'org' && <><h1>اختر المنشأة</h1><p>حسابك مرتبط بأكثر من منشأة. يمكنك التبديل لاحقًا من الشريط العلوي.</p>
          <div style={{ display: 'grid', gap: 8 }}>{window.AP_DATA.orgs.map((o, n) => <button key={o} type="button" className="kit-choice is-on" style={n ? { background: '#fff', borderColor: 'var(--border-2)' } : null} onClick={onLogin}><Icon name="Building" size={18} /><span><b>{o}</b><small>{n ? 'مالك · إدارة ذاتية' : 'محصلة · الرياض — الرئيسي'}</small></span></button>)}</div></>}
        {step !== 'org' && <Button size="lg" block loading={busy} onClick={next}>{step === 'phone' ? 'إرسال الرمز' : 'دخول'}</Button>}
        <p className="kit-login__foot">منشأة جديدة؟ <button type="button" className="kit-src" onClick={() => window.apOpen('signup', { onSaved: () => setTimeout(() => window.apGo && window.apGo('welcome'), 1200) })}>سجّل مكتبك</button> · وصلك رابط دعوة؟ <button type="button" className="kit-src" onClick={() => window.apGo && window.apGo('join')}>افتح الدعوة</button></p>
      </section>
    </div>
  );
}

Object.assign(window.AP_FORMS, {
  profile: { title: 'الملف الشخصي', width: 520, fields: [
    { k: 'name', l: 'الاسم', def: 'سارة الغامدي', req: true }, { k: 'phone', l: 'الجوال', t: 'ltr', def: '0551110001', half: true, hint: 'تغييره يتطلب رمز تحقق.' }, { k: 'email', l: 'البريد', t: 'ltr', half: true, opt: true },
    { t: 'summary', rows: () => [['الدور', 'محصلة'], ['الفرع', 'الرياض — الرئيسي'], ['يحدد الدور', 'مديرة المكتب']] }
  ], submit: 'حفظ', done: { title: 'حُفظ ملفك', text: 'تظهر البيانات الجديدة في السندات التي تصدرها لاحقًا.' } },
  password: { title: 'تغيير كلمة المرور', width: 460, fields: [
    { k: 'old', l: 'كلمة المرور الحالية', t: 'ltr', req: true }, { k: 'new', l: 'الجديدة', t: 'ltr', req: true, hint: '8 أحرف على الأقل.' }, { k: 'rep', l: 'تأكيد الجديدة', t: 'ltr', req: true },
    { t: 'note', tone: 'danger', text: 'كلمتا المرور غير متطابقتين.', when: (v) => v.rep && v.new !== v.rep }, { k: 'others', l: 'تسجيل الخروج من الأجهزة الأخرى', t: 'check', def: true }
  ], submit: 'تغيير', done: { title: 'تغيرت كلمة المرور', text: 'استخدمها في الدخول القادم.' } },
  notifPrefs: { title: 'تفضيلات الإشعارات', width: 520, fields: [
    { k: 'promise', l: 'وعود السداد المستحقة اليوم', t: 'check', def: true }, { k: 'verify', l: 'دفعات بانتظار تحققي', t: 'check', def: true }, { k: 'maint', l: 'طلبات الصيانة العاجلة', t: 'check', def: true }, { k: 'ending', l: 'عقود تنتهي خلال 60 يومًا', t: 'check' },
    { k: 'channel', l: 'القناة', t: 'seg', o: ['داخل التطبيق', 'رسالة نصية', 'الاثنان'], def: 'داخل التطبيق' }, { k: 'time', l: 'ملخص يومي الساعة', t: 'select', o: ['07:00', '08:00', '09:00'], def: '08:00' }
  ], submit: 'حفظ', done: { title: 'حُفظت التفضيلات', text: 'تسري من الغد.' } },
  signup: { title: 'تسجيل منشأة جديدة', width: 640, fields: [
    { k: 'type', l: 'نوع المنشأة', t: 'radio', def: 'office', o: [{ value: 'office', label: 'مكتب إدارة أملاك', hint: 'يدير عقارات لصالح ملاك.' }, { value: 'self', label: 'مالك يدير أملاكه بنفسه' }] },
    { k: 'name', l: 'اسم المنشأة', req: true }, { k: 'cr', l: 'السجل التجاري', t: 'ltr', half: true, opt: true, when: (v) => v.type === 'office' }, { k: 'fal', l: 'رخصة فال', t: 'ltr', half: true, opt: true, when: (v) => v.type === 'office' },
    { k: 'city', l: 'المدينة', t: 'select', o: ['الرياض', 'جدة', 'الدمام', 'مكة المكرمة'], def: 'الرياض', half: true }, { k: 'phone', l: 'جوال المدير', t: 'ltr', req: true, half: true },
    { k: 'terms', l: 'أوافق على الشروط وسياسة الخصوصية', t: 'check', req: true }
  ], submit: 'إنشاء المنشأة', done: { title: 'أُنشئت المنشأة', text: 'أرسلنا رمز التحقق لجوال المدير. الخطوة التالية: استيراد العقارات أو إضافتها يدويًا.' } }
});

Object.assign(window, { Notifications, CommandSearch, AccountMenu, LoginScreen });
})();
