// Main app shell
const { useState: useStateA, useEffect: useEffectA } = React;

function _parseToken(token) {
  try {
    const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
    return {
      role:        payload.role        || 'admin',
      name:        payload.name        || '',
      username:    payload.username    || '',
      id:          payload.id          || null,
      permissions: payload.permissions || null,  // null = همه، array = لیست مجاز
    };
  } catch { return { role: 'admin', name: '', username: '', id: null, permissions: null }; }
}

function _isTokenExpired(token) {
  try {
    const { exp } = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
    return exp && Date.now() / 1000 > exp;
  } catch { return true; }
}

const App = () => {
  const { Icon, ToastHost } = window.SB_UI;
  const { NAV } = window.SB_DATA;
  const [page, setPage] = window.useStickyState('nav_page', 'dashboard');
  const [user, setUser] = useState(() => {
    const token = localStorage.getItem(window.TOKEN_KEY);
    if (!token) return null;
    if (_isTokenExpired(token)) { localStorage.removeItem(window.TOKEN_KEY); return null; }
    return { token, ..._parseToken(token) };
  });

  const handleLogin = (userData) => setUser({ ...userData, ..._parseToken(userData.token || localStorage.getItem(window.TOKEN_KEY)) });
  const handleLogout = () => { localStorage.removeItem(window.TOKEN_KEY); setUser(null); };

  // expose global navigator so any page can switch tabs
  useEffectA(() => {
    window.SB_setPage = setPage;
  }, [setPage]);

  if (!user) {
    return <window.LoginPage onLogin={handleLogin} />;
  }

  if (user.role === 'seller') {
    return <window.SellerApp seller={user} onLogout={handleLogout} />;
  }

  // NAV فیلترشده بر اساس permissions کاربر
  // null = همه ماژول‌ها (superadmin یا admin بدون محدودیت)
  const perms = user.permissions;
  const visibleNav = NAV.filter(n => perms === null || perms.includes(n.id));

  // اگه صفحه‌ی فعلی برای این نقش مجاز نیست، برو به داشبورد
  const safePage = visibleNav.find(n => n.id === page) ? page : 'dashboard';
  const current = visibleNav.find(n => n.id === safePage);

  const PAGE = {
    dashboard:     window.Dashboard,
    leadpool:      window.LeadPool,
    sellers:       window.Sellers,
    products:      window.Products,
    rules:         window.Rules,
    campaigns:     window.Campaigns,
    orchestra:     window.OrchestraBoard,
    library:       window.Library,
    lab:           window.Lab,
    scenario_map:  window.ScenarioMap,
    meta:          window.Meta,
    api_monitor:   window.ApiMonitor,
    crm_module:    window.CrmModule,
    settings:      window.Settings,
    users:         window.Users,
    ceo_dashboard: window.CeoDashboard,
  }[safePage];

  return (
    <ToastHost>
      <div className="app">
        <Sidebar page={safePage} setPage={setPage} nav={visibleNav} user={user} onLogout={handleLogout} />
        <main className="main">
          <Topbar page={current} />
          <div className="content">
            {PAGE ? <PAGE /> : <div className="empty"><div className="empty-icon"><Icon name="hammer" size={28} /></div><div>صفحه در دست ساخت</div></div>}
          </div>
        </main>
        <BottomNav page={safePage} setPage={setPage} nav={visibleNav} />
      </div>
    </ToastHost>
  );
};

const Sidebar = ({ page, setPage, nav, user, onLogout }) => {
  const { Icon } = window.SB_UI;
  const { ROLE_LABELS } = window.SB_DATA;
  const roleInfo = ROLE_LABELS[user?.role] || { label: 'کاربر', color: '#94a3b8' };
  const displayName = user?.name || user?.username || 'کاربر';
  const initials = displayName.length > 1 ? displayName.slice(0, 2) : displayName;

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M3 7 L12 3 L21 7 L21 17 L12 21 L3 17 Z" stroke="white" strokeWidth="1.7" strokeLinejoin="round" />
            <circle cx="12" cy="12" r="3" fill="white" />
          </svg>
        </div>
        <div>
          <div className="brand-name">SalesBot</div>
          <div className="brand-sub mono">v2.4.0 — Pro</div>
        </div>
      </div>

      {nav.map(n => (
        <div key={n.id}
          className={`nav-item ${page === n.id ? 'active' : ''}`}
          onClick={() => setPage(n.id)}>
          <span className="num">{n.num}</span>
          <Icon name={n.icon} size={16} />
          <span className="lab">{n.name}</span>
          {n.dot && <span className="badge-dot" />}
        </div>
      ))}

      <div className="sidebar-footer">
        <div className="avatar" style={{ background: roleInfo.color + '33', color: roleInfo.color, border: `1px solid ${roleInfo.color}55`, fontSize: 11 }}>{initials}</div>
        <div className="user-meta" style={{ flex: 1, minWidth: 0 }}>
          <div className="nm">{displayName}</div>
          <div className="rl" style={{ color: roleInfo.color }}>{roleInfo.label}</div>
        </div>
        <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={onLogout} title="خروج"><Icon name="log-out" size={13} /></button>
      </div>
    </aside>
  );
};

const Topbar = ({ page }) => {
  const { Icon } = window.SB_UI;
  const [reminders, setReminders] = useState([]);
  const [showReminders, setShowReminders] = useState(false);
  const token = localStorage.getItem(window.TOKEN_KEY);
  const bellRef = useRef(null);

  const loadReminders = () => {
    fetch('/api/leads/reminders/pending', {
      headers: { Authorization: `Bearer ${token}` }
    }).then(r => r.json()).then(d => {
      if (d.success) setReminders(d.data.reminders || []);
    }).catch(() => {});
  };

  useEffectA(() => {
    loadReminders();
    const t = setInterval(loadReminders, 60000); // هر ۱ دقیقه
    return () => clearInterval(t);
  }, []);

  const [dropPos, setDropPos] = useState({ top: 58, left: 80 });

  // موقع باز شدن، position دکمه رو بگیر
  const openReminders = () => {
    if (!showReminders && bellRef.current) {
      const rect = bellRef.current.getBoundingClientRect();
      setDropPos({ top: rect.bottom + 6, left: rect.left });
    }
    setShowReminders(p => !p);
  };

  // بستن dropdown با کلیک خارج
  useEffectA(() => {
    if (!showReminders) return;
    const handler = (e) => {
      if (bellRef.current && !bellRef.current.contains(e.target)) setShowReminders(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [showReminders]);

  const now = new Date().toISOString().slice(0, 16);       // UTC YYYY-MM-DDTHH:MM
  const todayUtcEnd = new Date(new Date().toISOString().slice(0,10) + 'T23:59:59Z').toISOString().slice(0, 16);
  const overdue   = reminders.filter(r => r.follow_up_at <  now);
  const todayItems = reminders.filter(r => r.follow_up_at >= now && r.follow_up_at <= todayUtcEnd);
  const upcoming  = reminders.filter(r => r.follow_up_at >  todayUtcEnd);
  const badgeCount = overdue.length + todayItems.length;

  const formatDue = (dt) => {
    try {
      const d = new Date(dt);
      const today = new Date();
      const diff = Math.round((d - today) / 60000); // دقیقه
      if (diff < -60) return `${Math.round(-diff/60)} ساعت پیش`;
      if (diff < 0) return `${-diff} دقیقه پیش`;
      if (diff < 60) return `${diff} دقیقه دیگه`;
      if (diff < 1440) return `${Math.round(diff/60)} ساعت دیگه`;
      return d.toLocaleDateString('fa-IR');
    } catch { return dt; }
  };

  const ReminderItem = ({ r, color }) => (
    <div
      onClick={() => { window.SB_setPage?.('leads'); setShowReminders(false); }}
      style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 16px', cursor: 'pointer', transition: 'background 0.1s' }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.04)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ width: 6, height: 6, borderRadius: '50%', background: color, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.lead_name}</div>
        {r.phone && <div style={{ fontSize: 10, color: '#64748b', marginTop: 1, fontFamily: 'JetBrains Mono' }}>{r.phone}</div>}
      </div>
      <div style={{ fontSize: 10, color, fontWeight: 700, whiteSpace: 'nowrap', flexShrink: 0 }}>{formatDue(r.follow_up_at)}</div>
    </div>
  );

  const ReminderSection = ({ items, color, label }) => (
    <>
      <div style={{ padding: '8px 16px 4px', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.06)' }} />
        <span style={{ fontSize: 10, fontWeight: 700, color, letterSpacing: 0.6, whiteSpace: 'nowrap' }}>{label}</span>
        <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.06)' }} />
      </div>
      {items.map(r => <ReminderItem key={r.id} r={r} color={color} />)}
    </>
  );

  return (
    <header className="topbar">
      <div>
        <div className="page-title">{page?.name}</div>
        <div className="page-crumb mono">SalesBot &nbsp;/&nbsp; {page?.name}</div>
      </div>
      <div className="topbar-tools">
        <div className="search">
          <Icon name="search" size={14} color="var(--text-3)" />
          <input placeholder="جستجو در همه چیز..." />
          <span className="kbd">⌘K</span>
        </div>
        <button className="icon-btn"><Icon name="moon" size={15} /></button>

        {/* ناقوس اعلان */}
        <div ref={bellRef} style={{ position: 'relative' }}>
          <button className="icon-btn" onClick={openReminders} style={{ position: 'relative' }}>
            <Icon name="bell" size={15} />
            {badgeCount > 0 && (
              <span style={{
                position: 'absolute', top: 2, left: 2,
                minWidth: 14, height: 14, borderRadius: 7,
                background: overdue.length > 0 ? '#F87171' : '#FB923C',
                color: '#fff', fontSize: 9, fontFamily: 'JetBrains Mono',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: '0 3px', fontWeight: 700, lineHeight: 1,
              }}>
                {badgeCount}
              </span>
            )}
          </button>

          {showReminders && (
            <div style={{
              position: 'fixed', top: dropPos.top, left: dropPos.left,
              width: 280, background: '#111118', border: '1px solid rgba(255,255,255,0.08)',
              borderRadius: 10, boxShadow: '0 8px 32px rgba(0,0,0,0.6)', zIndex: 2147483647,
              overflow: 'hidden',
            }}>
              {/* هدر */}
              <div style={{ padding: '10px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: '#e2e8f0' }}>یادآور تماس</span>
                  {badgeCount > 0 && (
                    <span style={{
                      fontSize: 10, padding: '1px 7px', borderRadius: 20, fontWeight: 700,
                      background: overdue.length > 0 ? 'rgba(248,113,113,0.18)' : 'rgba(251,146,60,0.18)',
                      color: overdue.length > 0 ? '#F87171' : '#FB923C',
                    }}>{badgeCount}</span>
                  )}
                </div>
                <button onClick={loadReminders} title="رفرش"
                  style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#475569', fontSize: 14, lineHeight: 1, padding: '2px 4px', borderRadius: 4, transition: 'color 0.1s' }}
                  onMouseEnter={e => e.currentTarget.style.color = '#94a3b8'}
                  onMouseLeave={e => e.currentTarget.style.color = '#475569'}
                >↻</button>
              </div>

              {/* محتوا */}
              <div style={{ maxHeight: 340, overflowY: 'auto', paddingBottom: 8 }}>
                {reminders.length === 0 ? (
                  <div style={{ padding: '28px 16px', textAlign: 'center', color: '#475569', fontSize: 12 }}>
                    <div style={{ fontSize: 20, marginBottom: 6 }}>✅</div>
                    هیچ یادآوری در انتظار نیست
                  </div>
                ) : (
                  <>
                    {overdue.length > 0    && <ReminderSection items={overdue}    color="#F87171" label="سررسید گذشته" />}
                    {todayItems.length > 0 && <ReminderSection items={todayItems} color="#FB923C" label="امروز" />}
                    {upcoming.length > 0   && <ReminderSection items={upcoming}   color="#60A5FA" label="آینده" />}
                  </>
                )}
              </div>
            </div>
          )}
        </div>

        <button className="icon-btn"><Icon name="help-circle" size={15} /></button>
      </div>
    </header>
  );
};

const BottomNav = ({ page, setPage, nav }) => {
  const { Icon } = window.SB_UI;
  return (
    <nav className="bottom-nav">
      {nav.map(n => (
        <button key={n.id} className={`bn-item ${page === n.id ? 'active' : ''}`} onClick={() => setPage(n.id)}>
          <Icon name={n.icon} size={18} />
          <span>{n.name}</span>
        </button>
      ))}
    </nav>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
