File size: 10,377 Bytes
4f163ba
 
05b5ece
a78af8b
4f163ba
 
 
 
 
 
 
 
 
 
 
29f8199
 
 
 
 
 
10c20ff
4f163ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f8199
 
 
 
 
 
 
 
 
 
 
 
4f163ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e0c85e
5a11b0a
 
6e0c85e
 
4f163ba
 
a78af8b
05b5ece
4f163ba
02f2d05
 
 
 
 
 
 
4f163ba
 
29f8199
 
 
 
 
 
4f163ba
29f8199
4f163ba
 
 
158a0ac
 
02f2d05
4f163ba
 
eb9db2e
 
 
 
 
 
 
 
 
 
 
 
 
 
4f163ba
d13e92b
6e0c85e
551780e
0f1cb81
b5253a7
afe7b28
ebb25a7
5a11b0a
158a0ac
5a11b0a
0f1cb81
4f163ba
0f1cb81
 
 
d2e180e
0b9633c
5a11b0a
 
 
 
 
 
71e432d
 
5a11b0a
 
eb9db2e
0f1cb81
5a11b0a
 
 
0f1cb81
0a6800d
7d6128a
551780e
7d6128a
 
5a11b0a
7d6128a
551780e
7d6128a
 
 
 
5a11b0a
0f1cb81
 
5a11b0a
ce60c41
5a11b0a
 
4f163ba
5a11b0a
4f163ba
 
 
551780e
 
 
4f163ba
 
 
e67efa2
4f163ba
 
 
 
 
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
import React, { useState, useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
// We keep heroicons for fallback, but nav uses custom SVGs from /public/icons
import { PowerIcon, HomeIcon, AcademicCapIcon, BookOpenIcon, HandThumbUpIcon, WrenchScrewdriverIcon, ChatBubbleLeftRightIcon, Cog6ToothIcon } from '@heroicons/react/24/outline';
import HitokotoBar from './HitokotoBar';
import { api } from '../services/api';

interface User {
  name: string;
  email: string;
  role: string;
}

const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const location = useLocation();
  const [viewMode, setViewMode] = useState<'admin' | 'student' | 'auto'>(() => {
    try {
      const saved = localStorage.getItem('viewMode') as any;
      return saved === 'admin' || saved === 'student' ? saved : 'auto';
    } catch { return 'auto'; }
  });
  const [isTransitioning] = useState(false);
  const userData = localStorage.getItem('user');
  const user: User | null = userData ? JSON.parse(userData) : null;
  const [unreadCount, setUnreadCount] = useState<number>(0);

  // Lightweight online presence: send heartbeat periodically
  useEffect(() => {
    let timer: any;
    const sendHeartbeat = async () => {
      try {
        if (!user?.email) return;
        const token = localStorage.getItem('token') || '';
        const base = (((api.defaults as any)?.baseURL as string) || '').replace(/\/$/, '');
        await fetch(`${base}/api/auth/online/heartbeat`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'user-role': user.role || 'visitor',
            'user-info': userData || ''
          },
          body: JSON.stringify({ email: user.email, path: location.pathname })
        });
      } catch {}
    };
    sendHeartbeat();
    timer = setInterval(sendHeartbeat, 60000);
    return () => { if (timer) clearInterval(timer); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.email]);

  // Send a heartbeat on route changes for fresher session tracking
  useEffect(() => {
    const run = async () => {
      try {
        if (!user?.email) return;
        const token = localStorage.getItem('token') || '';
        const base = (((api.defaults as any)?.baseURL as string) || '').replace(/\/$/, '');
        await fetch(`${base}/api/auth/online/heartbeat`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'user-role': user.role || 'visitor',
            'user-info': userData || ''
          },
          body: JSON.stringify({ email: user.email, path: location.pathname })
        });
      } catch {}
    };
    run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  // React to external view mode changes (from Manage toggle)
  useEffect(() => {
    const handler = (e: any) => {
      const mode = e?.detail;
      if (mode === 'admin' || mode === 'student') {
        setViewMode(mode);
      }
    };
    window.addEventListener('view-mode-change', handler as any);
    return () => window.removeEventListener('view-mode-change', handler as any);
  }, []);

  // Admin unread message badge (non-invasive)
  useEffect(() => {
    let timer: any;
    const run = async () => {
      try {
        if (user?.role !== 'admin') return;
        const token = localStorage.getItem('token') || '';
        const base = (((api.defaults as any)?.baseURL as string) || '').replace(/\/$/, '');
        const resp = await fetch(`${base}/api/messages/unread-count`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'user-role': 'admin',
            'user-info': userData || ''
          }
        });
        if (resp.ok) {
          const data = await resp.json();
          if (typeof data?.count === 'number') setUnreadCount(data.count);
        }
      } catch {}
    };
    run();
    if (user?.role === 'admin') {
      timer = setInterval(run, 60000);
    }
    return () => { if (timer) clearInterval(timer); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.role]);

  // Admin unread message badge (non-invasive)
  useEffect(() => {
    let timer: any;
    const run = async () => {
      try {
        if (user?.role !== 'admin') return;
        const token = localStorage.getItem('token') || '';
        const base = (((api.defaults as any)?.baseURL as string) || '').replace(/\/$/, '');
        const resp = await fetch(`${base}/api/messages/unread-count`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'user-role': 'admin',
            'user-info': userData || ''
          }
        });
        if (resp.ok) {
          const data = await resp.json();
          if (typeof data?.count === 'number') setUnreadCount(data.count);
        }
      } catch {}
    };
    run();
    if (user?.role === 'admin') {
      timer = setInterval(run, 60000);
    }
    return () => { if (timer) clearInterval(timer); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.role]);

  const handleLogout = () => {
    try {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    } catch {}
    window.location.href = '/login';
  };

  // heroicons already imported at top

  let navigation = [
    { name: 'Home', href: '/dashboard', icon: HomeIcon },
    { name: 'Tutorial Tasks', href: '/tutorial-tasks', icon: AcademicCapIcon },
    { name: 'Weekly Practice', href: '/weekly-practice', icon: BookOpenIcon },
    { name: 'Votes', href: '/votes', icon: HandThumbUpIcon },
    { name: 'Toolkit', href: '/toolkit', icon: WrenchScrewdriverIcon },
    { name: 'Slides', href: '/slides', icon: BookOpenIcon },
    { name: 'Feedback', href: '/feedback', icon: ChatBubbleLeftRightIcon },
  ];

  // Effective role based on viewMode
  const effectiveRole = (() => {
    if (viewMode === 'auto') return user?.role;
    return viewMode === 'student' ? 'student' : 'admin';
  })();

  // Hide Slides for visitors
  if (!user || effectiveRole === 'visitor') {
    navigation = navigation.filter(item => item.name !== 'Slides');
  }

  // Add Manage link for admin users (always keep in nav)
  if (user?.role === 'admin') {
    navigation.push({ name: 'Manage', href: '/manage', icon: Cog6ToothIcon });
  }

  const iconSrcFor = (name: string): string => {
    switch (name) {
      case 'Home': return '/icons/home.svg';
      case 'Tutorial Tasks': return '/icons/tutorial tasks.svg';
      case 'Weekly Practice': return '/icons/weekly practice.svg';
      case 'Votes': return '/icons/votes.svg';
      case 'Toolkit': return '/icons/toolkit.svg';
      case 'Slides': return '/icons/slides.svg';
      case 'Feedback': return '/icons/feedback.svg';
      case 'Manage': return '/icons/manage.svg';
      default: return '/icons/home.svg';
    }
  };

  return (
    <div className="min-h-[calc(100vh+25vh)] text-ui-text bg-white app-shell" style={{ backgroundImage: 'url(/background/background.png)', backgroundSize: '100% auto', backgroundPosition: 'bottom', backgroundRepeat: 'no-repeat', paddingBottom: '25vh' }}>
      {/* Top Bar */}
      <header className="sticky top-0 z-40 bg-ui-panel/80 backdrop-blur border-b border-ui-border">
        <div className="px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between">
          <Link to="/dashboard" className="text-[1.6rem] font-bold text-ui-text flex items-center -ml-4 hover:text-ui-text" style={{ fontFamily: 'Lobster, Inter, system-ui, sans-serif' }}>
            <img src="/favicon-512x512.png" alt="logo" className="h-8 w-8 mr-2" />
            TransHub
                </Link>
          <div />
              </div>
      </header>

      {/* Shell: Sidebar + Content */}
      <div className="flex">
        {/* Sidebar */}
        <aside className="hidden md:flex md:flex-col w-60 fixed top-14 left-0 bottom-0 border-r border-ui-border bg-ui-panel/80 backdrop-blur z-30 sidebar-shell">
          <nav className="p-4 space-y-2 flex-1 sidebar-nav">
                {navigation.map((item) => {
                  const isActive = location.pathname === item.href;
                  return (
                    <Link
                      key={item.name}
                      to={item.href}
                  className={`flex items-center px-3 py-2 rounded-lg text-[0.95rem] font-medium transition-colors ${
                    isActive ? 'text-ui-text' : 'text-ui-text/80 hover:text-ui-text'
                      }`}
                    >
                  <img src={iconSrcFor(item.name)} alt="" className="h-6 w-6 mr-3" />
                  <span>{item.name}</span>
                    </Link>
                  );
                })}
          </nav>
          <div className="p-3 border-t border-ui-border mt-auto sidebar-footer">
            {user ? (
              <button onClick={handleLogout} className="w-full flex items-center justify-start px-3 py-2 rounded-md text-sm font-medium text-ui-text/80 hover:bg-ui-panel/60">
                <PowerIcon className="h-4 w-4 mr-2" />
                Log Out
                  </button>
            ) : (
              <Link to="/login" className="w-full flex items-center justify-start px-3 py-2 rounded-md text-sm font-medium text-ui-text/80 hover:bg-ui-panel/60">
                <PowerIcon className="h-4 w-4 mr-2" />
                Log In
              </Link>
            )}
        </div>
        </aside>

                        {/* Main Content */}
        <main className="flex-1 p-4 sm:p-6 lg:p-8 md:ml-60">
                    {!isTransitioning && children}
                  </main>
      </div>
      
      {/* Transition Loading Indicator */}
      {isTransitioning && (
        <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50">
          <div className="bg-ui-panel rounded-lg shadow-lg p-4 flex items-center space-x-3 border border-ui-border">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-ui-neonCyan"></div>
            <span className="text-ui-text font-medium">Loading...</span>
          </div>
        </div>
      )}
      {/* <HitokotoBar /> */}
    </div>
  );
};

export default Layout;