File size: 9,441 Bytes
141c062
9ff626c
 
 
 
 
 
f9fbac8
9ff626c
 
 
a6b76d5
ea7ab01
9ff626c
 
 
 
 
 
 
 
 
263a752
141c062
9ff626c
 
ea7ab01
9ff626c
4fd7cee
263a752
4fd7cee
 
 
 
 
 
 
 
 
 
 
 
 
 
3b9fa19
4fd7cee
 
 
 
 
 
 
 
 
3b9fa19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fd7cee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e9c7d
4fd7cee
 
 
 
 
263a752
4fd7cee
 
 
263a752
ea7ab01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff626c
 
 
 
 
 
558bec8
9ff626c
 
 
 
f9fbac8
c2a0fab
 
9ff626c
 
558bec8
 
 
 
 
9ff626c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263a752
9ff626c
 
 
 
 
 
 
ea7ab01
 
 
9ff626c
 
 
 
 
 
 
891cb72
9ff626c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263a752
9ff626c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564c253
 
904f4d0
564c253
263a752
 
 
 
 
 
 
 
 
 
a6b76d5
9ff626c
 
 
 
 
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
import React, { useState, useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { 
  HomeIcon, 
  AcademicCapIcon,
  BookOpenIcon,
  HandThumbUpIcon,
  WrenchScrewdriverIcon,
  UserIcon,
  ArrowRightOnRectangleIcon
} 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 [isTransitioning, setIsTransitioning] = useState(false);
  const previousPathRef = useRef(location.pathname);
  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]);

  // 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 = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    window.location.href = '/';
  };

  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: UserIcon },
  ];

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

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

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Navigation */}
      <nav className="bg-white shadow-sm border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex">
              <div className="flex-shrink-0 flex items-center">
                <Link to="/dashboard" className="text-xl font-bold text-indigo-600">
                  Transcreation
                </Link>
              </div>
              <div className="hidden sm:ml-6 sm:flex sm:space-x-8">
                {navigation.map((item) => {
                  const isActive = location.pathname === item.href;
                  return (
                    <Link
                      key={item.name}
                      to={item.href}
                      className={`inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium transition-all duration-200 ease-in-out ${
                        isActive
                          ? 'border-indigo-500 text-gray-900'
                          : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
                      }`}
                    >
                      <item.icon className="h-4 w-4 mr-1" />
                      {item.name}
                      {item.name === 'Feedback' && user?.role === 'admin' && unreadCount > 0 && (
                        <span className="ml-2 inline-flex items-center justify-center min-w-[16px] h-4 px-1 rounded-full bg-red-600 text-white text-[10px] leading-none">{unreadCount > 99 ? '99+' : unreadCount}</span>
                      )}
                    </Link>
                  );
                })}
              </div>
            </div>
            <div className="flex items-center">
              {user && (
                <div className="flex items-center">
                  <button
                    onClick={handleLogout}
                    className="text-gray-500 hover:text-gray-700 flex items-center"
                  >
                    <ArrowRightOnRectangleIcon className="h-4 w-4 mr-1" />
                    Logout
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile Navigation */}
      <div className="sm:hidden">
        <div className="pt-2 pb-3 space-y-1">
          {navigation.map((item) => {
            const isActive = location.pathname === item.href;
            return (
              <Link
                key={item.name}
                to={item.href}
                className={`block pl-3 pr-4 py-2 border-l-4 text-base font-medium transition-all duration-200 ease-in-out ${
                  isActive
                    ? 'bg-indigo-50 border-indigo-500 text-indigo-700'
                    : 'border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800'
                }`}
              >
                <div className="flex items-center">
                  <item.icon className="h-4 w-4 mr-2" />
                  {item.name}
                </div>
              </Link>
            );
          })}
        </div>
      </div>

                        {/* Main Content */}
                  <main>
                    {!isTransitioning && children}
                  </main>
      
      {/* 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-white rounded-lg shadow-lg p-4 flex items-center space-x-3">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-indigo-600"></div>
            <span className="text-gray-700 font-medium">Loading...</span>
          </div>
        </div>
      )}
      <HitokotoBar />
    </div>
  );
};

export default Layout;