Spaces:
Running

File size: 12,707 Bytes
cd61bf7
 
95db790
cd61bf7
 
526e04d
 
 
 
 
 
 
 
 
 
 
 
95db790
 
dde3672
f0e1c07
 
526e04d
cd61bf7
526e04d
 
95db790
 
a10d642
fc0d9c2
526e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480067e
a10d642
 
526e04d
 
 
a10d642
526e04d
 
 
a10d642
 
 
 
 
480067e
526e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50089a4
526e04d
 
 
cd61bf7
 
 
526e04d
a10d642
95db790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
ca13047
cd61bf7
 
 
526e04d
5e04bce
 
 
 
cd61bf7
a69f086
fc0d9c2
99e0d4e
 
fc0d9c2
 
 
ca13047
95db790
 
 
 
 
fc01c03
 
95db790
cd61bf7
ca13047
 
 
 
6439d6b
ca13047
305a6e6
 
6e3a1f6
e645f21
 
53443e8
dc9320a
 
53443e8
 
33256ac
cd61bf7
526e04d
82b1391
 
 
 
 
 
 
 
 
 
 
ca13047
82b1391
 
 
 
d7933ab
82b1391
99e0d4e
ca23984
82b1391
99e0d4e
 
82b1391
 
99e0d4e
82b1391
 
 
 
 
99e0d4e
82b1391
99e0d4e
82b1391
99e0d4e
 
 
 
a10d642
99e0d4e
 
 
 
 
526e04d
e727115
 
82b1391
 
 
 
 
 
cbc4965
82b1391
 
e727115
82b1391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95db790
82b1391
95db790
82b1391
 
95db790
82b1391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480067e
fc0d9c2
82b1391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95db790
82b1391
 
 
 
 
 
 
f1c284f
82b1391
 
 
 
 
 
 
 
 
 
480067e
82b1391
480067e
82b1391
 
 
480067e
82b1391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480067e
82b1391
 
 
 
 
cd61bf7
dc38b4e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import {
  LayoutDashboard,
  MessageSquare,
  Database,
  CreditCard,
  Brain,
  FileText,
  Plug,
  Zap,
  Users,
  Bell,
  Calendar,
  Shield,
  Clock,
  AlertTriangle,
  Volume2,
  Bot
} from 'lucide-react'
import { useAuth } from '@/contexts/AuthContext'
import { motion } from 'framer-motion'
import { NavItem } from './Sidebar/NavItem'
import { api } from '@/lib/api'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/lib/i18n'
import { isOwner } from '@/lib/permissions'

// ============================================================================
// Animation Variants
// ============================================================================

const sidebarVariants = {
  hidden: { x: -20, opacity: 0 },
  visible: {
    x: 0,
    opacity: 1,
    transition: { duration: 0.4, staggerChildren: 0.05 }
  }
}

const itemVariants = {
  hidden: { x: -10, opacity: 0 },
  visible: { x: 0, opacity: 1 }
}

// ============================================================================
// Navigation Configuration
// ============================================================================

const mainNavItems = [
  { href: '/dashboard', icon: LayoutDashboard, labelKey: 'nav.analytics', ownerOnly: true },
  { href: '/chats', icon: MessageSquare, labelKey: 'nav.chats', ownerOnly: false },
  { href: '/appointments', icon: Calendar, labelKey: 'nav.appointments', ownerOnly: false },
]

const integrationItems = [
  { href: '/channels', icon: Plug, labelKey: 'nav.channels', ownerOnly: true },
]

const settingsItems = [
  { href: '/settings/brain', icon: Brain, labelKey: 'nav.brain', ownerOnly: true },
  { href: '/settings/voice', icon: Volume2, labelKey: 'nav.voice', ownerOnly: true },
  { href: '/settings/playbook', icon: FileText, labelKey: 'nav.funnel', ownerOnly: true },
  { href: '/settings/team', icon: Users, labelKey: 'nav.team', ownerOnly: true },
  { href: '/settings/notifications', icon: Bell, labelKey: 'nav.notifications', ownerOnly: false },
  { href: '/settings/billing', icon: CreditCard, labelKey: 'nav.billing', ownerOnly: true },
]

// ============================================================================
// Helper Functions
// ============================================================================

function getInitials(name?: string | null, email?: string): string {
  if (name) {
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
  }
  if (email) {
    return email.slice(0, 2).toUpperCase()
  }
  return 'U'
}

// ============================================================================
// Main Component
// ============================================================================

export function Sidebar() {
  const pathname = usePathname()
  const { user, isLoading } = useAuth()
  const { t } = useTranslation()
  const [usageStats, setUsageStats] = useState<{
    plan: string
    conversations_used: number
    conversations_limit: number | null
    days_left: number
    is_expired: boolean
  } | null>(null)

  // Load usage stats for trial/subscription display
  useEffect(() => {
    const loadUsage = async () => {
      if (!user) return
      try {
        const res = await api.get('/api/v1/tenants/me/usage')
        setUsageStats(res.data.usage)
      } catch (e) {
        console.error('Failed to load usage stats')
      }
    }
    loadUsage()
  }, [user])

  // Don't show sidebar on auth pages
  if (pathname === '/login' || pathname === '/register' || pathname === '/') {
    return null
  }

  // Hide if not authenticated
  if (!isLoading && !user) {
    return null
  }

  const isActive = (path: string) => pathname === path || pathname.startsWith(path + '/')
  const isAdmin = user?.is_superuser || user?.role?.toUpperCase() === 'ADMIN'
  const isOwnerUser = isOwner(user?.role) || isAdmin

  // Filter items based on role
  const visibleMainItems = mainNavItems.filter(item => isOwnerUser || !item.ownerOnly)
  const visibleIntegrationItems = integrationItems.filter(item => isOwnerUser || !item.ownerOnly)
  const visibleSettingsItems = settingsItems.filter(item => isOwnerUser || !item.ownerOnly)

  // Trial banner logic
  const isTrial = usageStats?.plan === 'trial'
  const isExpired = usageStats?.is_expired
  const daysLeft = usageStats?.days_left || 0
  const usedDialogs = usageStats?.conversations_used || 0
  const limitDialogs = usageStats?.conversations_limit  // null = unlimited
  const isUnlimited = limitDialogs === null || limitDialogs === undefined

  return (
    <motion.aside
      initial="hidden"
      animate="visible"
      variants={sidebarVariants}
      className="w-72 flex flex-col relative shrink-0 h-screen sticky top-0 pb-14 lg:pb-0 border-r border-white/5 z-20 bg-[#050510]/80 backdrop-blur-xl backdrop-saturate-[1.8]"
    >
      {/* Logo Section - Hidden on mobile, already in MobileHeader */}
      <div className="p-6 relative z-50 hidden lg:block">
        <Link href="/settings/brain" className="flex items-center gap-3 group">
          <div className="w-8 h-8 flex items-center justify-center relative">
            <img src="/logo-v2.png" alt="MicroFunnel Logo" className="w-full h-full object-contain" />
          </div>
          <h1 className="text-lg font-bold tracking-[0.2em] uppercase text-white">
            MICROFUNNEL
          </h1>
        </Link>
      </div>

      {/* Loading State */}
      {
        isLoading ? (
          <nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
            {[1, 2, 3].map((i) => (
              <div key={i}>
                <div className="h-3 w-20 bg-md-surface-container-high rounded mb-3 animate-pulse" />
                <div className="space-y-2">
                  {[1, 2, 3].map((j) => (
                    <div key={j} className="h-10 w-full bg-md-surface-container rounded-lg animate-pulse" />
                  ))}
                </div>
              </div>
            ))}
          </nav>
        ) : (
          <nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-md-outline-variant scrollbar-track-transparent">

            {/* Main Navigation */}
            <motion.div initial="hidden" animate="visible" variants={itemVariants}>
              <p className="px-4 text-[10px] font-bold text-md-on-surface-variant uppercase tracking-widest mb-2 font-mono">
                / {t('sidebar.main').toUpperCase()}
              </p>
              <div className="space-y-1">
                {/* Admin Link */}
                {isAdmin && (
                  <NavItem
                    href="/admin"
                    icon={Shield}
                    label={t('nav.admin')}
                    isActive={isActive('/admin')}
                    variant="admin"
                  />
                )}

                {visibleMainItems.map((item) => (
                  <NavItem
                    key={item.href}
                    href={item.href}
                    icon={item.icon}
                    label={t(item.labelKey)}
                    isActive={isActive(item.href)}
                  />
                ))}
              </div>
            </motion.div>

            {/* Demo Chat Button - HIDDEN AS REQUESTED */}
            {/* {isOwner && (
              <motion.div initial="hidden" animate="visible" variants={itemVariants}>
                <Link
                  href="/demo-chat"
                  className="w-full flex items-center gap-3 px-4 py-3 text-sm font-medium text-purple-400 hover:text-purple-300 bg-purple-500/10 hover:bg-purple-500/20 rounded-xl border border-purple-500/20 transition-all group"
                >
                  <Bot className="w-5 h-5" />
                  <span>Корректировка</span>
                </Link>
              </motion.div>
            )} */}

            {/* Integrations - only show section if has visible items */}
            {visibleIntegrationItems.length > 0 && (
              <motion.div initial="hidden" animate="visible" variants={itemVariants}>
                <p className="px-4 text-[10px] font-bold text-md-on-surface-variant uppercase tracking-widest mb-2 font-mono">
                  / {t('sidebar.integrations').toUpperCase()}
                </p>
                <div className="space-y-1">
                  {visibleIntegrationItems.map((item) => (
                    <NavItem
                      key={item.href}
                      href={item.href}
                      icon={item.icon}
                      label={t(item.labelKey)}
                      isActive={isActive(item.href)}
                    />
                  ))}
                </div>
              </motion.div>
            )}

            {/* Settings - only show section if has visible items */}
            {visibleSettingsItems.length > 0 && (
              <motion.div initial="hidden" animate="visible" variants={itemVariants}>
                <p className="px-4 text-[10px] font-bold text-md-on-surface-variant uppercase tracking-widest mb-2 font-mono">
                  / {t('sidebar.settings').toUpperCase()}
                </p>
                <div className="space-y-1">
                  {visibleSettingsItems.map((item) => (
                    <NavItem
                      key={item.href}
                      href={item.href}
                      icon={item.icon}
                      label={t(item.labelKey)}
                      isActive={isActive(item.href)}
                    />
                  ))}
                </div>
              </motion.div>
            )}
            {/* Trial/Subscription Banner */}
            {usageStats && isOwnerUser && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className={cn(
                  "mx-2 p-4 rounded-xl border mt-4",
                  isExpired
                    ? "bg-red-500/10 border-red-500/30"
                    : isTrial
                      ? "bg-amber-500/10 border-amber-500/30"
                      : "bg-indigo-500/10 border-indigo-500/30"
                )}
              >
                <div className="flex items-center gap-2 mb-2">
                  {isExpired ? (
                    <AlertTriangle className="w-4 h-4 text-red-400" />
                  ) : (
                    <Clock className="w-4 h-4 text-amber-400" />
                  )}
                  <span className={cn(
                    "text-xs font-bold uppercase",
                    isExpired ? "text-red-400" : isTrial ? "text-amber-400" : "text-indigo-400"
                  )}>
                    {isExpired ? "Подписка истекла" : isTrial ? `Trial: ${daysLeft} дн.` : usageStats.plan.toUpperCase()}
                  </span>
                </div>

                {!isUnlimited && (
                  <div className="mb-2">
                    <div className="flex justify-between text-[10px] text-slate-500 mb-1">
                      <span>Диалоги</span>
                      <span>{usedDialogs} / {isUnlimited ? '∞' : limitDialogs}</span>
                    </div>
                    <div className="w-full bg-white/10 rounded-full h-1.5">
                      <div
                        className={cn(
                          "h-1.5 rounded-full transition-all",
                          usedDialogs >= (limitDialogs || 0)
                            ? "bg-red-500"
                            : usedDialogs >= (limitDialogs || 0) * 0.8
                              ? "bg-amber-500"
                              : "bg-indigo-500"
                        )}
                        style={{ width: `${Math.min((usedDialogs / (limitDialogs || 1)) * 100, 100)}%` }}
                      />
                    </div>
                  </div>
                )}

                {(isTrial || isExpired) && (
                  <Link
                    href="/settings/billing"
                    className={cn(
                      "block w-full py-2 text-center text-xs font-bold rounded-lg transition",
                      isExpired
                        ? "bg-red-600 hover:bg-red-500 text-white"
                        : "bg-amber-600 hover:bg-amber-500 text-white"
                    )}
                  >
                    {isExpired ? "Продлить подписку" : "Выбрать тариф"}
                  </Link>
                )}
              </motion.div>
            )}

          </nav>
        )
      }
    </motion.aside >
  )
}