File size: 110,539 Bytes
be45da0
 
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
2b28252
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
0ed2dda
13a60f9
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
69fd63f
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
69fd63f
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
69fd63f
 
5bac8b7
 
69fd63f
13a60f9
 
0ed2dda
13a60f9
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
0ed2dda
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
e9dd82b
0ed2dda
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
d78d53a
0ed2dda
 
5bac8b7
 
0ed2dda
77460a5
0ed2dda
77460a5
0ed2dda
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
77460a5
0ed2dda
 
 
 
5bac8b7
 
0ed2dda
77460a5
0ed2dda
 
 
 
5bac8b7
 
69fd63f
13a60f9
 
 
 
69fd63f
 
 
77460a5
4ca8559
 
 
77460a5
4ca8559
 
 
 
 
 
 
 
 
 
 
77460a5
69fd63f
 
4ca8559
 
 
 
69fd63f
4ca8559
69fd63f
 
4ca8559
69fd63f
4ca8559
69fd63f
 
 
4ca8559
69fd63f
4ca8559
69fd63f
 
 
4ca8559
 
 
69fd63f
 
 
 
 
 
 
4ca8559
 
69fd63f
 
 
 
4ca8559
 
 
 
 
 
 
 
3307d91
 
 
 
77460a5
3307d91
 
 
 
 
 
 
4ca8559
3307d91
 
 
 
4ca8559
3307d91
4ca8559
3307d91
 
77460a5
3307d91
 
 
 
 
 
4ca8559
3307d91
 
77460a5
3307d91
 
 
 
4ca8559
3307d91
4ca8559
3307d91
 
77460a5
3307d91
 
 
 
4ca8559
3307d91
4ca8559
3307d91
 
77460a5
3307d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11e1d8b
 
 
607f62e
 
 
77460a5
607f62e
 
 
77460a5
607f62e
 
 
 
 
 
 
 
 
 
 
77460a5
607f62e
 
 
 
 
 
 
 
 
77460a5
607f62e
 
77460a5
4ca8559
607f62e
4ca8559
 
 
607f62e
 
 
 
 
 
11e1d8b
 
 
 
 
 
 
 
 
77460a5
 
 
11e1d8b
 
 
 
 
 
 
 
 
 
 
 
77460a5
 
 
11e1d8b
 
 
 
 
 
 
13a60f9
 
 
 
 
11e1d8b
13a60f9
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
77460a5
13a60f9
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
2f87802
13a60f9
2f87802
 
77460a5
2f87802
13a60f9
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
 
77460a5
2f87802
13a60f9
2f87802
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
2f87802
 
 
 
 
 
77460a5
2f87802
 
 
77460a5
2f87802
 
 
 
 
77460a5
2f87802
 
 
 
 
77460a5
2f87802
 
 
 
77460a5
2f87802
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
77460a5
2f87802
 
 
77460a5
2f87802
 
 
 
 
 
77460a5
2f87802
 
 
 
77460a5
2f87802
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
13a60f9
 
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
 
 
 
 
 
77460a5
13a60f9
7dbbc86
13a60f9
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
77460a5
3307d91
 
77460a5
13a60f9
 
 
 
 
 
 
 
77460a5
13a60f9
2f87802
 
77460a5
13a60f9
2f87802
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
 
 
 
 
 
 
 
77460a5
2f87802
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
2f87802
 
13a60f9
77460a5
2f87802
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
77460a5
13a60f9
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
c46f13e
 
 
 
 
 
13a60f9
 
77460a5
13a60f9
 
 
c46f13e
77460a5
c46f13e
 
 
 
 
 
 
 
 
 
 
 
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
c46f13e
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
77460a5
69fd63f
 
0ed2dda
69fd63f
 
0ed2dda
 
 
 
 
 
 
 
 
 
 
69fd63f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
2c5c492
 
 
 
77460a5
60e09cb
4de3fcd
 
 
77460a5
4de3fcd
 
77460a5
13a60f9
 
 
4de3fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a60f9
4de3fcd
 
 
 
13a60f9
4de3fcd
 
 
 
 
 
13a60f9
 
 
 
 
 
 
 
 
 
 
2c5c492
 
 
 
13a60f9
 
 
 
 
 
660e460
13a60f9
 
 
 
 
 
 
 
 
69fd63f
13a60f9
 
 
77460a5
13a60f9
 
 
 
5acaeb8
 
77460a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5acaeb8
 
e3029b1
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
77460a5
e3029b1
 
 
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
77460a5
13a60f9
 
7dbbc86
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
 
 
 
 
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
7dbbc86
13a60f9
 
 
 
 
77460a5
13a60f9
 
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
2f87802
13a60f9
 
 
 
77460a5
13a60f9
 
 
 
 
77460a5
13a60f9
77460a5
13a60f9
 
 
77460a5
13a60f9
 
 
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
93bd2f4
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
 
 
93bd2f4
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
93bd2f4
 
 
 
 
 
 
 
 
 
 
 
e3029b1
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
77460a5
e3029b1
 
77460a5
e3029b1
 
77460a5
e3029b1
 
77460a5
e3029b1
 
77460a5
e3029b1
 
77460a5
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
77460a5
e3029b1
 
 
 
 
 
 
 
 
 
 
 
77460a5
e3029b1
 
 
77460a5
e3029b1
 
77460a5
e3029b1
 
 
77460a5
e3029b1
 
 
77460a5
e3029b1
 
 
77460a5
e3029b1
 
77460a5
e3029b1
 
 
 
 
77460a5
e3029b1
 
 
 
 
 
93bd2f4
 
 
 
 
 
 
 
 
 
77460a5
 
 
 
 
 
93bd2f4
 
 
77460a5
93bd2f4
 
77460a5
93bd2f4
77460a5
93bd2f4
 
 
 
 
 
77460a5
93bd2f4
 
 
13a60f9
 
 
 
 
 
 
 
77460a5
67c1005
 
77460a5
93bd2f4
 
77460a5
e3029b1
 
77460a5
e3029b1
 
67c1005
 
e3029b1
 
67c1005
4de3fcd
 
 
77460a5
4de3fcd
 
 
 
 
77460a5
4de3fcd
 
 
 
77460a5
4de3fcd
 
 
 
 
 
 
 
77460a5
4de3fcd
 
 
 
 
 
 
77460a5
4de3fcd
 
77460a5
4de3fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77460a5
4de3fcd
 
 
 
 
 
 
 
 
 
77460a5
4de3fcd
 
 
 
 
 
 
77460a5
4de3fcd
 
 
 
 
 
67c1005
 
 
 
 
 
 
 
 
 
 
77460a5
 
 
 
 
 
67c1005
 
98c2ddd
 
67c1005
 
 
 
 
 
 
 
 
 
 
 
98c2ddd
 
 
 
67c1005
 
 
98c2ddd
 
67c1005
 
 
 
 
98c2ddd
 
 
 
67c1005
98c2ddd
 
 
 
 
 
 
 
67c1005
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
// Exercise Database - Comprehensive with detailed exercise information
const exerciseDB = {
    chest: {
        easy: [
            {
                name: "靠牆伏地挺身 Wall Push-up",
                description: "靠牆進行伏地挺身,減輕手腕與肩膀負荷,適合初學者。",
                precautions: "手肘不要張太開,避免肩膀壓力",
                targetMuscles: "胸大肌、三頭肌",
                keyPoints: "核心收緊,背部保持直線",
                videoUrl: "https://www.youtube.com/watch?v=Eh00_rniF8E"
            },
            {
                name: "跪姿伏地挺身 Knee Push-up",
                description: "膝蓋著地降低難度,使胸部和手臂肌群能穩定發力。",
                precautions: "膝蓋墊軟墊",
                targetMuscles: "胸大肌、三頭肌",
                keyPoints: "下降時胸口接近地面,手肘約45度",
                videoUrl: "https://www.youtube.com/watch?v=65kH0J8qES0"
            },
            {
                name: "椅子伏地挺身 Incline Push-up",
                description: "手放在椅子或穩固平台上,降低負荷,提高胸大肌上部訓練。",
                precautions: "選擇穩固平台",
                targetMuscles: "胸大肌上方、三頭肌",
                keyPoints: "背部直線,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=3jRPr5n4n2I"
            },
            {
                name: "窄距離跪姿伏地挺身 Close-Knee Push-up",
                description: "雙手靠近身體,使胸大肌內側及三頭肌更集中發力。",
                precautions: "手距過窄易肩不適",
                targetMuscles: "胸大肌內側、三頭肌",
                keyPoints: "肘靠近身體下降",
                videoUrl: "https://www.youtube.com/watch?v=0W_fhLk_Cq4"
            }
        ],
        normal: [
            {
                name: "標準伏地挺身 Push-up",
                description: "基本伏地挺身,全面訓練胸大肌、三頭肌與前鋸肌。",
                precautions: "腰背勿下垂",
                targetMuscles: "胸大肌、三頭肌、前鋸肌",
                keyPoints: "胸口下降至手肘彎90度",
                videoUrl: "https://www.youtube.com/watch?v=5dF4QBx2fFc"
            },
            {
                name: "寬距伏地挺身 Wide Push-up",
                description: "手比肩寬,主要訓練胸大肌外側,增加胸部厚度。",
                precautions: "手距過寬肩膀受力大",
                targetMuscles: "胸大肌外側",
                keyPoints: "肩膀穩定,不聳肩",
                videoUrl: "https://www.youtube.com/watch?v=0B5FxyZSP84"
            },
            {
                name: "鑽石伏地挺身 Diamond Push-up",
                description: "雙手成鑽石形,增加胸內側與三頭肌負荷。",
                precautions: "手指呈鑽石形",
                targetMuscles: "胸大肌內側、三頭肌",
                keyPoints: "核心收緊,胸口靠近手指",
                videoUrl: "https://www.youtube.com/watch?v=S5K5CjyQCXk"
            },
            {
                name: "上斜伏地挺身 Incline Push-up",
                description: "雙手放高平台,強化胸大肌上部。",
                precautions: "穩固平台",
                targetMuscles: "胸大肌上部",
                keyPoints: "身體直線,控制下降",
                videoUrl: "https://www.youtube.com/watch?v=3jRPr5n4n2I"
            },
            {
                name: "下斜伏地挺身 Decline Push-up",
                description: "雙腳放高平台,訓練胸大肌下部及肩前束。",
                precautions: "腳置高平台",
                targetMuscles: "胸大肌下部、肩前束",
                keyPoints: "核心收緊,胸口下降",
                videoUrl: "https://www.youtube.com/watch?v=OZO9QH4dO6U"
            }
        ],
        hard: [
            {
                name: "單手伏地挺身 One Arm Push-up",
                description: "單手支撐,強化胸大肌、三頭肌與核心穩定性。",
                precautions: "肩膀與手腕承受高壓",
                targetMuscles: "胸大肌、三頭肌、核心",
                keyPoints: "核心穩定,避免身體旋轉",
                videoUrl: "https://www.youtube.com/watch?v=TLn3GYbWqL0"
            },
            {
                name: "爆發伏地挺身 Plyometric Push-up",
                description: "快速向上爆發,增加胸、肩、核心爆發力。",
                precautions: "地面防滑",
                targetMuscles: "胸大肌、肩膀、核心",
                keyPoints: "爆發力向上推,落地膝微屈",
                videoUrl: "https://www.youtube.com/watch?v=QhKJi1LqE2A"
            },
            {
                name: "拍手伏地挺身 Clap Push-up",
                description: "在上推時拍手,增強上肢爆發力及手眼協調。",
                precautions: "控制落地",
                targetMuscles: "胸大肌、肩膀、三頭肌",
                keyPoints: "手離地瞬間拍手",
                videoUrl: "https://www.youtube.com/watch?v=2rGhq0t8qps"
            },
            {
                name: "弓箭式伏地挺身 Archer Push-up",
                description: "一側手臂伸直,另一側彎曲,單側發力,提升胸大肌單側控制力。",
                precautions: "單側支撐",
                targetMuscles: "胸大肌單側、肩膀、核心",
                keyPoints: "保持平衡",
                videoUrl: "https://www.youtube.com/watch?v=Gq6t0bY0I2U"
            },
            {
                name: "偽俄式伏地挺身 Pseudo Push-up",
                description: "類似單手伏地挺身,但雙手寬距,身體略向前傾,增加肩膀與胸肌負荷,同時提升核心穩定。",
                precautions: "雙手寬距控制平衡",
                targetMuscles: "胸大肌、肩膀、核心",
                keyPoints: "控制下放速度",
                videoUrl: "https://www.youtube.com/watch?v=G_r_E5r3ePE"
            }
        ]
    },
    back: {
        easy: [
            {
                name: "超人式 Superman Hold",
                description: "俯臥地面,手腳同時抬起,訓練背伸肌與臀肌。",
                precautions: "不要過度抬頭",
                targetMuscles: "背部伸肌、臀大肌",
                keyPoints: "手腳同步抬起",
                videoUrl: "https://www.youtube.com/watch?v=J42d4J9nJ0w"
            },
            {
                name: "俯臥抬手抬腳 Prone Arm & Leg Raise",
                description: "保持腰背自然曲線,手腳慢慢抬起並控制下降。",
                precautions: "腰背自然曲線",
                targetMuscles: "下背、臀部",
                keyPoints: "動作緩慢,避免甩動",
                videoUrl: "https://www.youtube.com/watch?v=J42d4J9nJ0w"
            },
            {
                name: "毛巾划船 Towel Row",
                description: "利用毛巾固定在門把或支撐物,模擬划船動作訓練背肌。",
                precautions: "毛巾或門把穩固",
                targetMuscles: "背闊肌、菱形肌、二頭肌",
                keyPoints: "肩胛骨夾緊,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=QFqSLJq5KOs"
            }
        ],
        normal: [
            {
                name: "反向划船 Inverted Row",
                description: "懸吊在低桿下拉身體,訓練背肌及手臂。",
                precautions: "手握穩固",
                targetMuscles: "背闊肌、菱形肌、二頭肌",
                keyPoints: "肩胛骨下沉,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=hS1jyNsYOxE"
            },
            {
                name: "寬距反向划船 Wide Inverted Row",
                description: "手握寬距,增加背闊肌外側訓練。",
                precautions: "手距過寬易肩緊繃",
                targetMuscles: "背闊肌、肩後束",
                keyPoints: "身體直線,肩胛骨夾緊",
                videoUrl: "https://www.youtube.com/watch?v=Hlv0x2H8bAQ"
            },
            {
                name: "窄距反向划船 Close Inverted Row",
                description: "手握窄距,強化背闊肌中段與二頭肌。",
                precautions: "手臂過靠近手腕不適",
                targetMuscles: "背闊肌中段、二頭肌",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=HKxXCNXn6rw"
            },
            {
                name: "T字背部抬手 T-Arm Raise",
                description: "俯身或躺地抬手呈T字,訓練後肩與菱形肌。",
                precautions: "肩關節不要過度旋轉",
                targetMuscles: "後肩、菱形肌",
                keyPoints: "慢慢抬高,動作控制",
                videoUrl: "https://www.youtube.com/watch?v=O9v6C8lWwf8"
            }
        ],
        hard: [
            {
                name: "單手反向划船 One Arm Inverted Row",
                description: "單手拉動,訓練單側背闊肌與核心控制力。",
                precautions: "核心穩定",
                targetMuscles: "背闊肌、菱形肌",
                keyPoints: "控制下放",
                videoUrl: "https://www.youtube.com/watch?v=3dZ5y5lM6wQ"
            },
            {
                name: "L坐引體向上 L-sit Pull-up",
                description: "懸垂雙腿前舉成L形,增加核心負荷。",
                precautions: "核心需先練好",
                targetMuscles: "背闊肌、核心",
                keyPoints: "雙腿前舉成L形",
                videoUrl: "https://www.youtube.com/watch?v=K2HR5Xz9tHc"
            },
            {
                name: "引體向上 Pull-up",
                description: "標準引體向上,肩胛骨下沉,核心收緊。",
                precautions: "勿借力擺動",
                targetMuscles: "背闊肌、二頭肌",
                keyPoints: "肩胛骨下沉,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=aDjcqrlKQYI"
            },
            {
                name: "寬握引體向上 Wide Grip Pull-up",
                description: "手握比肩寬,訓練背闊肌外側。",
                precautions: "手握過寬易肩緊",
                targetMuscles: "背闊肌外側",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=8nG6T79hWaE"
            }
        ]
    },
    shoulders: {
        easy: [
            {
                name: "肩部繞圈 Arm Circles",
                description: "雙臂平舉,做小幅度圓周旋轉,熱身肩關節。",
                precautions: "幅度不要過大",
                targetMuscles: "三角肌前束/中束/後束",
                keyPoints: "肩膀保持放鬆",
                videoUrl: "https://www.youtube.com/watch?v=Gzyr8x4FhrE"
            },
            {
                name: "牆面滑動 Wall Slides",
                description: "背靠牆,手臂向上滑動模仿推舉,增加肩關節活動度。",
                precautions: "背部貼牆",
                targetMuscles: "三角肌、肩胛肌群",
                keyPoints: "慢速控制",
                videoUrl: "https://www.youtube.com/watch?v=Jke8R7Z5N4E"
            },
            {
                name: "啞鈴側平舉 Dumbbell Lateral Raise",
                description: "雙手握輕重量啞鈴,抬至肩高。",
                precautions: "重量輕,控制上升",
                targetMuscles: "三角肌中束",
                keyPoints: "核心收緊,肩膀下沉",
                videoUrl: "https://www.youtube.com/watch?v=JIvbcs1cWNw"
            }
        ],
        normal: [
            {
                name: "啞鈴前平舉 Dumbbell Front Raise",
                description: "雙手持啞鈴向前抬至肩高,訓練三角肌前束。",
                precautions: "手肘微彎,控制下降",
                targetMuscles: "三角肌前束",
                keyPoints: "背部保持直線",
                videoUrl: "https://www.youtube.com/watch?v=3F4HjJ8y8rQ"
            },
            {
                name: "啞鈴後平舉 Dumbbell Reverse Fly",
                description: "俯身或躺於斜板,雙手啞鈴往兩側抬起,訓練後肩。",
                precautions: "避免背部拱起",
                targetMuscles: "三角肌後束、菱形肌",
                keyPoints: "慢速控制",
                videoUrl: "https://www.youtube.com/watch?v=EA7u9d6vE0E"
            },
            {
                name: "阿諾德推舉 Arnold Press",
                description: "坐姿或站姿,啞鈴由胸前旋轉向上推起,結合前、中束訓練。",
                precautions: "肩膀穩定",
                targetMuscles: "三角肌前/中束",
                keyPoints: "動作控制,避免借力",
                videoUrl: "https://www.youtube.com/watch?v=6xPE4K4r15s"
            }
        ],
        hard: [
            {
                name: "手推俯臥撐 Pike Push-up",
                description: "臀部抬高呈倒V,手臂支撐下壓,訓練肩部。",
                precautions: "手腕不要過度承壓",
                targetMuscles: "肩膀、三頭肌",
                keyPoints: "控制下放,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=9h1jC6yCj6I"
            },
            {
                name: "爆發手推俯臥撐 Plyo Pike Push-up",
                description: "下放後快速推起,增加肩膀爆發力。",
                precautions: "地面防滑",
                targetMuscles: "肩膀、胸、核心",
                keyPoints: "爆發力向上,控制落地",
                videoUrl: "https://www.youtube.com/watch?v=2QqkjS1b4xE"
            },
            {
                name: "倒立牆壁推舉 Handstand Wall Press",
                description: "雙手倒立靠牆,進行推舉,訓練全肩與核心。",
                precautions: "初學者需有人協助",
                targetMuscles: "肩膀、三頭肌、核心",
                keyPoints: "肩膀穩定,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=6eHkE1WbH5Q"
            }
        ]
    },
    arms: {
        easy: [
            {
                name: "二頭肌彎舉 Dumbbell Bicep Curl",
                description: "雙手握啞鈴,手肘靠近身體做彎舉。",
                precautions: "手肘不前後移動",
                targetMuscles: "二頭肌",
                keyPoints: "控制下放",
                videoUrl: "https://www.youtube.com/watch?v=XKwNUWRgP6c"
            },
            {
                name: "三頭肌伸展 Tricep Kickback",
                description: "俯身手肘固定,手腕向後伸展。",
                precautions: "手肘固定",
                targetMuscles: "三頭肌",
                keyPoints: "動作緩慢",
                videoUrl: "https://www.youtube.com/watch?v=6NXRrMx1j4E"
            }
        ],
        normal: [
            {
                name: "啞鈴交替彎舉 Alternating Dumbbell Curl",
                description: "單手交替彎舉啞鈴,提高二頭肌控制力。",
                precautions: "避免身體晃動",
                targetMuscles: "二頭肌",
                keyPoints: "手肘固定",
                videoUrl: "https://www.youtube.com/watch?v=WkJNslo7d0Q"
            },
            {
                name: "仰臥三頭肌伸展 Lying Tricep Extension",
                description: "平躺,雙手握啞鈴從額頭上方伸直。",
                precautions: "重量適中",
                targetMuscles: "三頭肌",
                keyPoints: "肘關節固定",
                videoUrl: "https://www.youtube.com/watch?v=ns-R2Xo0SrA"
            }
        ],
        hard: [
            {
                name: "單手啞鈴交替彎舉 One Arm Dumbbell Curl",
                description: "單手彎舉,提高單側控制力。",
                precautions: "核心收緊",
                targetMuscles: "二頭肌",
                keyPoints: "控制下放",
                videoUrl: "https://www.youtube.com/watch?v=0tS3kX9l5nE"
            },
            {
                name: "爆發式二頭肌彎舉 Plyometric Bicep Curl",
                description: "快速彎舉,提高手臂爆發力。",
                precautions: "注意手肘受力",
                targetMuscles: "二頭肌",
                keyPoints: "動作爆發,控制落下",
                videoUrl: "https://www.youtube.com/watch?v=Z8H4I1i8W7E"
            },
            {
                name: "三頭肌鑽石伏地挺身 Tricep Diamond Push-up",
                description: "雙手成鑽石形做伏地挺身,專注三頭肌。",
                precautions: "手肘靠近身體",
                targetMuscles: "三頭肌",
                keyPoints: "核心收緊,控制下降",
                videoUrl: "https://www.youtube.com/watch?v=S5K5CjyQCXk"
            }
        ]
    },
    legs: {
        easy: [
            {
                name: "椅子深蹲 Chair Squat",
                description: "背靠椅子,臀部慢慢下坐至接觸椅子,再站起。",
                precautions: "膝蓋不超腳尖",
                targetMuscles: "大腿前側、臀部",
                keyPoints: "背直,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=Yf2Czzk3vXc"
            },
            {
                name: "半蹲 Half Squat",
                description: "膝蓋微屈,下蹲至大腿與地面平行以上。",
                precautions: "膝蓋與腳尖同向",
                targetMuscles: "大腿前側、臀部",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=QeW6C5Y4YtY"
            },
            {
                name: "台階踩踏 Step Up",
                description: "單腳踏穩台階,另一腳跟上,再下來。",
                precautions: "踏板穩固",
                targetMuscles: "臀大肌、大腿後側",
                keyPoints: "全腳踩實,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=WC8R9V0k5oE"
            },
            {
                name: "靠牆深蹲 Wall Squat",
                description: "背靠牆下蹲至大腿平行,保持姿勢。",
                precautions: "背靠牆,膝蓋不超腳尖",
                targetMuscles: "大腿、臀部",
                keyPoints: "保持穩定",
                videoUrl: "https://www.youtube.com/watch?v=-tE6kBk0EYw"
            }
        ],
        normal: [
            {
                name: "深蹲 Squat",
                description: "雙腳與肩同寬,下蹲至大腿平行地面,再起身。",
                precautions: "膝蓋與腳尖同向",
                targetMuscles: "大腿前後側、臀部",
                keyPoints: "背直,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=mGvzVjuY8SY"
            },
            {
                name: "跳深蹲 Jump Squat",
                description: "深蹲後用力跳起,落地再蹲。",
                precautions: "落地膝微屈",
                targetMuscles: "大腿、臀部",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=Azl5tkCzDcc"
            },
            {
                name: "弓箭步 Lunge",
                description: "單腿前跨下蹲,後膝接近地面,再回來。",
                precautions: "膝蓋不超腳尖",
                targetMuscles: "大腿前側、臀部",
                keyPoints: "上身直立,核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=K6K2Nqx5hXo"
            },
            {
                name: "交替弓箭步 Alternating Lunge",
                description: "左右腿交替前跨下蹲,保持節奏。",
                precautions: "控制平衡",
                targetMuscles: "大腿、臀部",
                keyPoints: "膝蓋不碰地",
                videoUrl: "https://www.youtube.com/watch?v=3XDjB00Q5rE"
            },
            {
                name: "側弓箭步 Side Lunge",
                description: "單腿側跨下蹲,另一腿伸直,回來再換側。",
                precautions: "膝蓋與腳尖同向",
                targetMuscles: "大腿內外側、臀部",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=MVkJWXyE2mE"
            }
        ],
        hard: [
            {
                name: "單腳深蹲 Pistol Squat",
                description: "單腳下蹲,另一腿伸直前方,慢慢回站立。",
                precautions: "需平衡與柔軟度",
                targetMuscles: "大腿前側、臀部",
                keyPoints: "膝與腳尖同向",
                videoUrl: "https://www.youtube.com/watch?v=uH7xqgQ5abU"
            },
            {
                name: "跳躍弓箭步 Jump Lunge",
                description: "弓箭步跳起換腿落地,再蹲。",
                precautions: "落地膝微彎",
                targetMuscles: "大腿、臀部",
                keyPoints: "雙腿交替跳",
                videoUrl: "https://www.youtube.com/watch?v=K6K2Nqx5hXo"
            },
            {
                name: "保加利亞蹲 Bulgarian Split Squat",
                description: "後腳放在凳上,前腳下蹲,再起身。",
                precautions: "後腳穩定",
                targetMuscles: "大腿前側、臀部",
                keyPoints: "膝不超腳尖",
                videoUrl: "https://www.youtube.com/watch?v=6w7IqJ1N-_U"
            },
            {
                name: "蝦式蹲 Shrimp Squat",
                description: "單腳支撐,另一腳屈膝抓腳踝,慢慢下蹲再起。",
                precautions: "需平衡",
                targetMuscles: "大腿、臀部",
                keyPoints: "慢控制下降與上升",
                videoUrl: "https://www.youtube.com/watch?v=4H0yN6tZ1vY"
            }
        ]
    },
    glutes: {
        easy: [
            {
                name: "臀橋 Glute Bridge",
                description: "仰躺,膝蓋彎曲,臀部向上抬起至頂點收緊。",
                precautions: "腰背自然曲線",
                targetMuscles: "臀大肌、腿後側",
                keyPoints: "頂點收緊",
                videoUrl: "https://www.youtube.com/watch?v=wPM8icPu6H8"
            },
            {
                name: "側躺抬腿 Side Lying Leg Raise",
                description: "側躺單腿抬高至最高點,慢慢下降。",
                precautions: "動作緩慢",
                targetMuscles: "臀中肌",
                keyPoints: "腿慢慢抬高",
                videoUrl: "https://www.youtube.com/watch?v=jG5w2Yd8W3k"
            },
            {
                name: "驢踢 Donkey Kick",
                description: "四足跪姿,單腿膝90度向上抬。",
                precautions: "膝90度彎",
                targetMuscles: "臀大肌",
                keyPoints: "臀部用力抬腿",
                videoUrl: "https://www.youtube.com/watch?v=ZxFAvE5wI7A"
            }
        ],
        normal: [
            {
                name: "單腳臀橋 Single Leg Glute Bridge",
                description: "單腳支撐,另一腳抬起,臀橋頂點收緊。",
                precautions: "腰背穩定",
                targetMuscles: "臀大肌、腿後側",
                keyPoints: "頂點收緊",
                videoUrl: "https://www.youtube.com/watch?v=KFx-9t-Q2bE"
            },
            {
                name: "蛙式臀橋 Frog Pump",
                description: "仰躺,雙腳腳底合攏,臀部抬起停留頂點。",
                precautions: "腳底接觸穩固",
                targetMuscles: "臀大肌",
                keyPoints: "頂點停留",
                videoUrl: "https://www.youtube.com/watch?v=KfHq3n5x8Uc"
            },
            {
                name: "臀推 Hip Thrust",
                description: "背靠凳子,膝彎曲,臀部抬起至頂點收緊。",
                precautions: "肩膀靠凳",
                targetMuscles: "臀大肌",
                keyPoints: "頂點收緊,腰背自然",
                videoUrl: "https://www.youtube.com/watch?v=LM8XHjBnO8o"
            }
        ],
        hard: [
            {
                name: "北歐腿彎曲 Nordic Curl",
                description: "膝蓋跪地,雙腳固定,慢慢控制前傾。",
                precautions: "膝保護",
                targetMuscles: "臀大肌、腿後肌",
                keyPoints: "控制下降",
                videoUrl: "https://www.youtube.com/watch?v=qLgbqmX4WFw"
            },
            {
                name: "單腳臀推 Single Leg Hip Thrust",
                description: "單腳支撐,另一腳抬起,臀部頂點收緊。",
                precautions: "單腳支撐",
                targetMuscles: "臀大肌",
                keyPoints: "頂點收緊",
                videoUrl: "https://www.youtube.com/watch?v=uY4A5E6W8gA"
            },
            {
                name: "跳臀橋 Jump Glute Bridge",
                description: "臀橋頂點爆發跳起,落地膝微屈再抬起。",
                precautions: "落地膝微屈",
                targetMuscles: "臀大肌、腿後肌",
                keyPoints: "頂點收緊",
                videoUrl: "https://www.youtube.com/watch?v=KxE9v8c3yV4"
            }
        ]
    },
    core: {
        easy: [
            {
                name: "棒式 Plank",
                description: "前臂撐地,身體呈一直線,維持姿勢。",
                precautions: "腰不要下塌",
                targetMuscles: "核心(腹直肌、腹橫肌)",
                keyPoints: "核心收緊,臀部不過高",
                videoUrl: "https://www.youtube.com/watch?v=pvIjsG5Svck"
            },
            {
                name: "仰臥捲腹 Crunch",
                description: "仰躺,肩膀微抬離地,收縮腹部。",
                precautions: "避免拉脖子",
                targetMuscles: "腹直肌",
                keyPoints: "用腹部發力",
                videoUrl: "https://www.youtube.com/watch?v=8N4q3a9mXkU"
            },
            {
                name: "抬腿 Leg Raise",
                description: "仰躺,雙腿伸直抬起再慢慢放下。",
                precautions: "腰貼地",
                targetMuscles: "下腹部",
                keyPoints: "控制下降",
                videoUrl: "https://www.youtube.com/watch?v=7FwNYPxQ5qE"
            }
        ],
        normal: [
            {
                name: "側棒式 Side Plank",
                description: "側身撐地,身體呈一直線維持。",
                precautions: "肩膀穩定",
                targetMuscles: "腹斜肌",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=K2U8J8K6Q3I"
            },
            {
                name: "登山者 Mountain Climber",
                description: "撐地姿勢,雙腿交替往胸口收。",
                precautions: "速度可控",
                targetMuscles: "核心、下腹",
                keyPoints: "保持穩定",
                videoUrl: "https://www.youtube.com/watch?v=nmwgirgXLYM"
            },
            {
                name: "俄羅斯轉體 Russian Twist",
                description: "坐姿身體後傾,左右旋轉軀幹。",
                precautions: "背部打直",
                targetMuscles: "腹斜肌",
                keyPoints: "控制轉動",
                videoUrl: "https://www.youtube.com/watch?v=wkD8rJK7UI8"
            }
        ],
        hard: [
            {
                name: "懸垂抬腿 Hanging Leg Raise",
                description: "懸吊單槓,雙腿抬至水平或更高。",
                precautions: "避免擺動",
                targetMuscles: "下腹、核心",
                keyPoints: "慢慢抬起",
                videoUrl: "https://www.youtube.com/watch?v=7FwNYPxQ5qE"
            },
            {
                name: "L坐 L-sit",
                description: "雙手撐地,雙腿伸直抬起呈L型。",
                precautions: "手腕壓力大",
                targetMuscles: "核心、髖屈肌",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=IYZI6eA4k_o"
            },
            {
                name: "V字捲腹 V-up",
                description: "手腳同時抬起,在空中接觸。",
                precautions: "控制速度",
                targetMuscles: "腹直肌",
                keyPoints: "核心發力",
                videoUrl: "https://www.youtube.com/watch?v=Z8H4I1i8W7E"
            }
        ]
    },
    fullbody: {
        easy: [
            {
                name: "開合跳 Jumping Jack",
                description: "雙腳跳開合併,雙手同步上舉。",
                precautions: "節奏穩定",
                targetMuscles: "全身、有氧系統",
                keyPoints: "輕鬆節奏",
                videoUrl: "https://www.youtube.com/watch?v=iSSAk4XJWG0"
            },
            {
                name: "原地高抬腿 High Knees",
                description: "原地跑步,膝蓋抬高至腰部。",
                precautions: "核心穩定",
                targetMuscles: "核心、腿部",
                keyPoints: "節奏控制",
                videoUrl: "https://www.youtube.com/watch?v=ZC9e8J8b5nE"
            },
            {
                name: "波比分解 Burpee Step",
                description: "分解動作進行波比,降低強度。",
                precautions: "動作分段",
                targetMuscles: "全身",
                keyPoints: "穩定完成",
                videoUrl: "https://www.youtube.com/watch?v=58TfjRnxXzk"
            }
        ],
        normal: [
            {
                name: "波比跳 Burpee",
                description: "深蹲→撐地→跳回→起跳,完整動作。",
                precautions: "動作流暢",
                targetMuscles: "全身",
                keyPoints: "節奏穩定",
                videoUrl: "https://www.youtube.com/watch?v=dZg3zYvTg1E"
            },
            {
                name: "登山者跳 Mountain Climber Jump",
                description: "快速登山者動作結合跳躍。",
                precautions: "核心穩定",
                targetMuscles: "核心、腿部",
                keyPoints: "速度控制",
                videoUrl: "https://www.youtube.com/watch?v=nmwgirgXLYM"
            },
            {
                name: "深蹲推舉 Thruster",
                description: "深蹲後接肩推,一次完成。",
                precautions: "動作連貫",
                targetMuscles: "腿、肩、核心",
                keyPoints: "核心收緊",
                videoUrl: "https://www.youtube.com/watch?v=5G5E5G5a5LQ"
            }
        ],
        hard: [
            {
                name: "波比跳加伏地挺身 Burpee Push-up",
                description: "波比過程加入伏地挺身。",
                precautions: "控制節奏",
                targetMuscles: "全身",
                keyPoints: "穩定動作",
                videoUrl: "https://www.youtube.com/watch?v=806hY7VfJyU"
            },
            {
                name: "單腳波比 One Leg Burpee",
                description: "單腳進行波比動作,提高難度。",
                precautions: "平衡控制",
                targetMuscles: "全身、核心",
                keyPoints: "核心穩定",
                videoUrl: "https://www.youtube.com/watch?v=K9N5Q9q9Q3I"
            },
            {
                name: "波比跳接高跳 Burpee Tuck Jump",
                description: "波比後接抱膝跳,提高爆發力。",
                precautions: "落地穩定",
                targetMuscles: "全身、爆發力",
                keyPoints: "膝蓋保護",
                videoUrl: "https://www.youtube.com/watch?v=pkN2xLQQx4Q"
            }
        ]
    }
};

// Nutrition Calculator Functions
function calculateNutrition(weight) {
    if (!weight || weight <= 0) return null;

    // Calculate protein servings (weight × 0.25–0.35 servings, each serving ~20-25g protein)
    const proteinMin = Math.round(weight * 0.25 * 10) / 10;
    const proteinMax = Math.round(weight * 0.35 * 10) / 10;

    // Calculate Vitamin C and B based on weight ranges
    let vitaminAmount = 1;
    if (weight <= 50) {
        vitaminAmount = 1;
    } else if (weight <= 70) {
        vitaminAmount = 2;
    } else if (weight <= 90) {
        vitaminAmount = 3;
    } else {
        vitaminAmount = 4;
    }

    return {
        protein: {
            min: proteinMin,
            max: proteinMax,
            unit: '份',
            perServing: '每份約20-25g蛋白質',
            timing: '運動後30分鐘內',
            description: '訓練後建議攝取,用於肌肉修復與增長,不代表一天總量'
        },
        vitaminC: {
            amount: vitaminAmount,
            unit: '顆',
            weightRange: getWeightRangeText(weight),
            description: '抗氧化、幫助恢復'
        },
        vitaminB: {
            amount: vitaminAmount,
            unit: '顆',
            weightRange: getWeightRangeText(weight),
            description: '幫助能量代謝、肌肉恢復'
        },
        doubleX: {
            amount: 1,
            unit: '套',
            details: '共3顆(維生素、礦物質、植物精華各1顆)',
            description: '補充多種植物營養素、維生素、礦物質'
        },
        water: {
            min: Math.round(weight * 5),
            max: Math.round(weight * 7),
            unit: 'ml',
            timing: '運動後30分鐘內',
            description: '每公斤體重5-7ml',
            example: `體重 ${weight}kg → 約 ${Math.round(weight * 5)}–${Math.round(weight * 7)} ml`
        }
    };
}

// Helper function to get weight range text
function getWeightRangeText(weight) {
    if (weight <= 50) return '≤50kg:1顆';
    if (weight <= 70) return '51–70kg:2顆';
    if (weight <= 90) return '71–90kg:3顆';
    return '≥91kg:4顆';
}

// Update nutrition display on the results page
function updateNutritionDisplay() {
    const weight = personalInfo.weight;
    const nutrition = calculateNutrition(weight);

    // Update protein card
    const proteinCardAmount = document.getElementById('proteinCardAmount');
    const proteinResult = document.getElementById('proteinResult');
    if (proteinCardAmount) {
        if (nutrition && nutrition.protein) {
            proteinCardAmount.textContent = `${nutrition.protein.min}-${nutrition.protein.max} ${nutrition.protein.unit}`;
        } else {
            proteinCardAmount.textContent = '輸入體重計算份數';
        }
    }
    if (proteinResult) {
        if (nutrition && nutrition.protein) {
            proteinResult.textContent = `${nutrition.protein.min}-${nutrition.protein.max} ${nutrition.protein.unit} (${nutrition.protein.perServing})`;
        } else {
            proteinResult.textContent = '體重×0.25-0.35份';
        }
    }

    // Update Vitamin C card
    const vitaminCCardAmount = document.getElementById('vitaminCCardAmount');
    if (vitaminCCardAmount) {
        if (nutrition && nutrition.vitaminC) {
            vitaminCCardAmount.textContent = `${nutrition.vitaminC.amount} ${nutrition.vitaminC.unit}`;
        } else {
            vitaminCCardAmount.textContent = '輸入體重計算顆數';
        }
    }

    // Update Vitamin B card
    const vitaminBCardAmount = document.getElementById('vitaminBCardAmount');
    if (vitaminBCardAmount) {
        if (nutrition && nutrition.vitaminB) {
            vitaminBCardAmount.textContent = `${nutrition.vitaminB.amount} ${nutrition.vitaminB.unit}`;
        } else {
            vitaminBCardAmount.textContent = '輸入體重計算顆數';
        }
    }

    // Update Double X card
    const doubleXCardAmount = document.getElementById('doubleXCardAmount');
    if (doubleXCardAmount) {
        if (nutrition && nutrition.doubleX) {
            doubleXCardAmount.textContent = `${nutrition.doubleX.amount} ${nutrition.doubleX.unit}`;
        } else {
            doubleXCardAmount.textContent = '建議1套';
        }
    }

    // Update personal info summary
    const personalInfoSummary = document.getElementById('personalInfoSummary');
    const personalInfoText = document.getElementById('personalInfoText');
    if (personalInfoSummary && personalInfoText) {
        if (weight || personalInfo.height || personalInfo.gender) {
            personalInfoSummary.classList.remove('hidden');
            const genderText = personalInfo.gender === 'male' ? '男性' : (personalInfo.gender === 'female' ? '女性' : '');
            const heightText = personalInfo.height ? `${personalInfo.height}cm` : '';
            const weightText = weight ? `${weight}kg` : '';
            const parts = [genderText, heightText, weightText].filter(p => p);
            personalInfoText.textContent = parts.length > 0 ? parts.join(' / ') : '資料未提供';
        } else {
            personalInfoSummary.classList.add('hidden');
        }
    }
}

// Personal Info State
let personalInfo = { gender: null, height: null, weight: null };

// Gender Selection
function selectGender(gender) {
    personalInfo.gender = gender;

    // Update UI
    const maleBtn = document.getElementById('genderMale');
    const femaleBtn = document.getElementById('genderFemale');

    if (gender === 'male') {
        maleBtn.classList.add('border-blue-500', 'bg-blue-500/20');
        maleBtn.classList.remove('border-transparent');
        femaleBtn.classList.remove('border-pink-500', 'bg-pink-500/20');
        femaleBtn.classList.add('border-transparent');
    } else {
        femaleBtn.classList.add('border-pink-500', 'bg-pink-500/20');
        femaleBtn.classList.remove('border-transparent');
        maleBtn.classList.remove('border-blue-500', 'bg-blue-500/20');
        maleBtn.classList.add('border-transparent');
    }

    updatePersonalInfo();
}

// Update Personal Info and Calculate Protein
function updatePersonalInfo() {
    const heightInput = document.getElementById('heightInput');
    const weightInput = document.getElementById('weightInput');
    const proteinPreview = document.getElementById('proteinPreview');
    const proteinAmount = document.getElementById('proteinAmount');

    personalInfo.height = heightInput.value ? parseFloat(heightInput.value) : null;
    personalInfo.weight = weightInput.value ? parseFloat(weightInput.value) : null;

    // Calculate protein servings if weight is available (0.25-0.35 servings per kg)
    if (personalInfo.weight) {
        const minProtein = Math.round(personalInfo.weight * 0.25 * 10) / 10;
        const maxProtein = Math.round(personalInfo.weight * 0.35 * 10) / 10;
        proteinAmount.textContent = `${minProtein}-${maxProtein} 份 (每份約20-25g蛋白質)`;
        proteinPreview.classList.remove('hidden');
    } else {
        proteinPreview.classList.add('hidden');
    }
}

// Helper function to get exercise details based on muscle and difficulty
function getExerciseDetails(muscle, difficulty) {
    // Core and Full Body use time-based format
    if (muscle === 'core' || muscle === 'fullbody') {
        const timeMap = {
            easy: '1分鐘動作,休息40秒,共3組',
            normal: '1分半動作,休息40秒,共3組',
            hard: '2分鐘動作,休息40秒,共3組'
        };
        return {
            sets: '3',
            reps: timeMap[difficulty],
            isTimeBased: true,
            displaySets: '3組',
            displayReps: timeMap[difficulty]
        };
    } else {
        // Rep-based for chest, back, shoulders, legs, glutes, arms
        const repMap = {
            easy: '12下 × 3組',
            normal: '15下 × 3組',
            hard: '12下 × 4組'
        };
        const setMap = { easy: '3', normal: '3', hard: '4' };
        return {
            sets: setMap[difficulty],
            reps: repMap[difficulty],
            isTimeBased: false,
            displaySets: setMap[difficulty] + '組',
            displayReps: (difficulty === 'hard' ? '12下' : (difficulty === 'normal' ? '15下' : '12下'))
        };
    }
}

// State Management
let selectedMuscles = [];
let selectedDifficulty = null;
let currentStep = 1;
let particleAnimationId = null;
let generatedExercises = []; // Store generated exercises for reuse

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    initParticles();
    initRippleEffect();
    initKeyboardShortcuts();

    // Add vibration support for mobile
    if ('vibrate' in navigator) {
        document.body.classList.add('vibration-supported');
    }
});

// Particle System
function initParticles() {
    const canvas = document.getElementById('particles-canvas');
    const ctx = canvas.getContext('2d');

    function resize() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
    resize();
    window.addEventListener('resize', resize);

    const particles = [];
    const particleCount = 50;

    class Particle {
        constructor() {
            this.reset();
        }

        reset() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.size = Math.random() * 2 + 1;
            this.speedX = (Math.random() - 0.5) * 0.5;
            this.speedY = (Math.random() - 0.5) * 0.5;
            this.opacity = Math.random() * 0.5 + 0.2;
            this.color = Math.random() > 0.5 ? '#f59e0b' : '#10b981';
        }

        update() {
            this.x += this.speedX;
            this.y += this.speedY;

            if (this.x < 0 || this.x > canvas.width) this.speedX *= -1;
            if (this.y < 0 || this.y > canvas.height) this.speedY *= -1;
        }

        draw() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.globalAlpha = this.opacity;
            ctx.fill();
            ctx.globalAlpha = 1;
        }
    }

    for (let i = 0; i < particleCount; i++) {
        particles.push(new Particle());
    }

    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        particles.forEach((particle, index) => {
            particle.update();
            particle.draw();

            // Connect nearby particles
            particles.slice(index + 1).forEach(other => {
                const dx = particle.x - other.x;
                const dy = particle.y - other.y;
                const distance = Math.sqrt(dx * dx + dy * dy);

                if (distance < 100) {
                    ctx.beginPath();
                    ctx.strokeStyle = '#f59e0b';
                    ctx.globalAlpha = (1 - distance / 100) * 0.2;
                    ctx.lineWidth = 1;
                    ctx.moveTo(particle.x, particle.y);
                    ctx.lineTo(other.x, other.y);
                    ctx.stroke();
                    ctx.globalAlpha = 1;
                }
            });
        });

        particleAnimationId = requestAnimationFrame(animate);
    }
    animate();
}

// Ripple Effect
function initRippleEffect() {
    document.addEventListener('click', (e) => {
        if (e.target.closest('.energy-btn') || e.target.closest('.muscle-card') || e.target.closest('.difficulty-card')) {
            createRipple(e);
        }
    });
}

function createRipple(e) {
    const button = e.target.closest('.energy-btn') || e.target.closest('.muscle-card') || e.target.closest('.difficulty-card');
    if (!button) return;

    const rect = button.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    const x = e.clientX - rect.left - size / 2;
    const y = e.clientY - rect.top - size / 2;

    const ripple = document.createElement('span');
    ripple.classList.add('ripple');
    ripple.style.width = ripple.style.height = size + 'px';
    ripple.style.left = x + 'px';
    ripple.style.top = y + 'px';

    button.appendChild(ripple);

    setTimeout(() => ripple.remove(), 600);
}

// Confetti System
function fireConfetti() {
    const canvas = document.getElementById('confetti-canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const pieces = [];
    const colors = ['#f59e0b', '#10b981', '#3b82f6', '#ec4899', '#8b5cf6'];

    for (let i = 0; i < 100; i++) {
        pieces.push({
            x: canvas.width / 2,
            y: canvas.height / 2,
            w: Math.random() * 10 + 5,
            h: Math.random() * 10 + 5,
            color: colors[Math.floor(Math.random() * colors.length)],
            vx: (Math.random() - 0.5) * 20,
            vy: (Math.random() - 0.5) * 20,
            gravity: 0.5,
            rotation: Math.random() * 360,
            rotationSpeed: (Math.random() - 0.5) * 10
        });
    }

    let animationId;
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        pieces.forEach((piece, index) => {
            piece.x += piece.vx;
            piece.y += piece.vy;
            piece.vy += piece.gravity;
            piece.rotation += piece.rotationSpeed;

            ctx.save();
            ctx.translate(piece.x, piece.y);
            ctx.rotate((piece.rotation * Math.PI) / 180);
            ctx.fillStyle = piece.color;
            ctx.fillRect(-piece.w / 2, -piece.h / 2, piece.w, piece.h);
            ctx.restore();

            if (piece.y > canvas.height) {
                pieces.splice(index, 1);
            }
        });

        if (pieces.length > 0) {
            animationId = requestAnimationFrame(animate);
        } else {
            cancelAnimationFrame(animationId);
        }
    }
    animate();

    // Vibrate on mobile
    if (navigator.vibrate) {
        navigator.vibrate([100, 50, 100, 50, 200]);
    }
}

// Toast Notification
function showToast(message, duration = 3000) {
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toast-message');
    toastMessage.textContent = message;
    toast.classList.add('show');

    if (navigator.vibrate) {
        navigator.vibrate(50);
    }

    setTimeout(() => {
        toast.classList.remove('show');
    }, duration);
}

// Keyboard Shortcuts
function initKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            if (currentStep === 1 && selectedMuscles.length > 0) {
                goToStep2();
            } else if (currentStep === 2 && selectedDifficulty) {
                generateWorkout();
            }
        } else if (e.key === 'Escape') {
            if (currentStep === 2) backToStep1();
            else if (currentStep === 3) resetWorkout();
        } else if (e.key === 'r' || e.key === 'R') {
            if (currentStep === 1) selectRandom();
        }
    });
}

// Share Workout
function shareWorkout() {
    const muscleNames = {
        chest: '胸部', back: '背部', shoulders: '肩部', core: '核心',
        legs: '腿部', glutes: '臀部', arms: '手臂', fullbody: '全身'
    };
    const difficultyNames = { easy: '簡單', normal: '普通', hard: '困難' };
    const muscleText = selectedMuscles.map(m => muscleNames[m]).join('、');

    const shareText = `我在 EliteFit Pro 生成了一個針對${muscleText}的${difficultyNames[selectedDifficulty]}強度訓練計畫!一起來運動吧!💪 #EliteFit #智能訓練`;

    if (navigator.share) {
        navigator.share({
            title: 'EliteFit Pro 訓練計畫',
            text: shareText
        });
    } else {
        navigator.clipboard.writeText(shareText).then(() => {
            showToast('已複製分享文字到剪貼簿!');
        });
    }
}

// Step 1: Muscle Selection
function toggleMuscle(element) {
    const muscle = element.dataset.muscle;

    // Add click animation
    element.style.transform = 'scale(0.95)';
    setTimeout(() => {
        element.style.transform = '';
    }, 100);

    if (muscle === 'random') {
        selectRandom();
        return;
    }

    if (element.classList.contains('selected')) {
        element.classList.remove('selected');
        selectedMuscles = selectedMuscles.filter(m => m !== muscle);
        showToast(`已取消選擇 ${getMuscleName(muscle)}`, 1500);
    } else {
        // If fullbody is selected, deselect others
        if (muscle === 'fullbody') {
            document.querySelectorAll('.muscle-card.selected').forEach(card => {
                if (card.dataset.muscle !== 'fullbody') {
                    card.classList.remove('selected');
                }
            });
            selectedMuscles = selectedMuscles.filter(m => m === 'fullbody');
        } else {
            // If selecting other muscle, deselect fullbody
            const fullbodyCard = document.querySelector('[data-muscle="fullbody"]');
            if (fullbodyCard.classList.contains('selected')) {
                fullbodyCard.classList.remove('selected');
                selectedMuscles = selectedMuscles.filter(m => m !== 'fullbody');
            }
        }

        element.classList.add('selected');
        selectedMuscles.push(muscle);
        showToast(`已選擇 ${getMuscleName(muscle)}!`, 1500);
    }

    updateStep1Button();
}

function getMuscleName(muscle) {
    const names = {
        chest: '胸部', back: '背部', shoulders: '肩部', core: '核心',
        legs: '腿部', glutes: '臀部', arms: '手臂', fullbody: '全身'
    };
    return names[muscle] || muscle;
}

function selectRandom() {
    // Shake animation
    const randomCard = document.querySelector('[data-muscle="random"]');
    randomCard.classList.add('shake');
    setTimeout(() => randomCard.classList.remove('shake'), 500);

    // Clear all selections with animation
    document.querySelectorAll('.muscle-card.selected').forEach(card => {
        card.classList.remove('selected');
        card.style.transform = 'rotate(360deg) scale(0.8)';
        setTimeout(() => card.style.transform = '', 300);
    });

    // Randomly select 1-2 muscles
    const muscles = ['chest', 'back', 'shoulders', 'core', 'legs', 'glutes', 'arms'];
    const numMuscles = Math.random() > 0.5 ? 2 : 1;
    const shuffled = muscles.sort(() => 0.5 - Math.random());
    selectedMuscles = shuffled.slice(0, numMuscles);

    // Highlight selected with delay for drama
    selectedMuscles.forEach((muscle, index) => {
        setTimeout(() => {
            const card = document.querySelector(`[data-muscle="${muscle}"]`);
            if (card) {
                card.classList.add('selected');
                card.classList.add('bounce-in');
                setTimeout(() => card.classList.remove('bounce-in'), 600);
            }
        }, index * 200);
    });

    // Flash random button
    randomCard.classList.add('selected');
    setTimeout(() => randomCard.classList.remove('selected'), 500);

    // Show toast with suspense
    setTimeout(() => {
        const muscleNames = selectedMuscles.map(m => getMuscleName(m)).join(' + ');
        showToast(`🎲 隨機選擇:${muscleNames}!`, 2500);

        if (navigator.vibrate) {
            navigator.vibrate([50, 100, 50]);
        }
    }, 400);

    updateStep1Button();
}

function updateStep1Button() {
    const btn = document.getElementById('step1Btn');
    btn.disabled = selectedMuscles.length === 0;
}

function goToStep2() {
    if (selectedMuscles.length === 0) {
        // Shake the button to indicate error
        const btn = document.getElementById('step1Btn');
        btn.classList.add('shake');
        setTimeout(() => btn.classList.remove('shake'), 500);
        showToast('請先選擇至少一個訓練部位!', 2000);
        return;
    }

    // Transition animation
    document.getElementById('step1').style.opacity = '0';
    document.getElementById('step1').style.transform = 'translateX(-50px)';

    setTimeout(() => {
        document.getElementById('step1').classList.add('hidden');
        document.getElementById('step2').classList.remove('hidden');
        document.getElementById('step2').style.opacity = '0';
        document.getElementById('step2').style.transform = 'translateX(50px)';

        setTimeout(() => {
            document.getElementById('step2').style.transition = 'all 0.5s ease';
            document.getElementById('step2').style.opacity = '1';
            document.getElementById('step2').style.transform = 'translateX(0)';
        }, 50);

        // Update progress bar to 50%
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = '50%';
        document.getElementById('progressPercent').textContent = '50%';

        // Update connecting line to 50%
        document.getElementById('connectingLine').style.width = '50%';

        // Update step 1 to completed state (checkmark)
        document.getElementById('step1Number').classList.add('hidden');
        document.getElementById('step1Check').classList.remove('hidden');
        document.getElementById('step1Indicator').classList.remove('from-amber-400', 'to-orange-600', 'shadow-orange-500/50');
        document.getElementById('step1Indicator').classList.add('bg-gray-700', 'border-gray-600', 'shadow-gray-500/30');
        document.getElementById('step1Pulse').classList.add('hidden');
        document.getElementById('step1Glow').classList.remove('opacity-0');
        document.getElementById('step1Glow').classList.add('opacity-100');
        document.getElementById('step1Label').classList.remove('text-amber-400', 'bg-amber-500/10', 'border-amber-500/30');
        document.getElementById('step1Label').classList.add('text-gray-400', 'bg-gray-800/30', 'border-gray-600/30');
        document.getElementById('step1LabelGlow').classList.remove('opacity-100');
        document.getElementById('step1LabelGlow').classList.add('opacity-0');

        // Update step 2 to active state
        const step2Ind = document.getElementById('step2Indicator');
        step2Ind.classList.remove('bg-gray-800', 'border-gray-600', 'text-gray-400');
        step2Ind.classList.add('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'text-black', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110');
        document.getElementById('step2OuterGlow').classList.remove('opacity-0');
        document.getElementById('step2OuterGlow').classList.add('opacity-100', 'animate-pulse-slow');
        document.getElementById('step2Pulse').classList.remove('opacity-0');
        document.getElementById('step2Pulse').classList.add('opacity-75');
        document.getElementById('step2Ring').classList.add('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
        document.getElementById('step2Loading').classList.remove('hidden');
        document.getElementById('step2Number').classList.add('hidden');

        // Update step 2 text styling
        const step2Text = document.getElementById('step2Text');
        step2Text.classList.remove('text-gray-500', 'bg-gray-800/50', 'border-gray-700');
        step2Text.classList.add('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10');

        currentStep = 2;
        showToast('很好!現在選擇你的難度等級 💪', 2000);
    }, 300);

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function backToStep1() {
    document.getElementById('step2').classList.add('hidden');
    document.getElementById('step1').classList.remove('hidden');

    // Reset progress bar to 25%
    const progressBar = document.getElementById('progressBar');
    progressBar.style.width = '25%';
    document.getElementById('progressPercent').textContent = '25%';

    // Reset connecting line
    document.getElementById('connectingLine').style.width = '0%';

    // Reset step 1 to active state
    document.getElementById('step1Number').classList.remove('hidden');
    document.getElementById('step1Check').classList.add('hidden');
    document.getElementById('step1Indicator').classList.add('from-amber-400', 'to-orange-600', 'shadow-orange-500/50');
    document.getElementById('step1Indicator').classList.remove('bg-gray-700', 'border-gray-600', 'shadow-gray-500/30');
    document.getElementById('step1Pulse').classList.remove('hidden');
    document.getElementById('step1Glow').classList.add('opacity-0');
    document.getElementById('step1Glow').classList.remove('opacity-100');
    document.getElementById('step1Label').classList.add('text-amber-400', 'bg-amber-500/10', 'border-amber-500/30');
    document.getElementById('step1Label').classList.remove('text-gray-400', 'bg-gray-800/30', 'border-gray-600/30');
    document.getElementById('step1LabelGlow').classList.add('opacity-100');
    document.getElementById('step1LabelGlow').classList.remove('opacity-0');

    // Reset step 2 to inactive state
    const step2Ind = document.getElementById('step2Indicator');
    step2Ind.classList.add('bg-gray-800', 'border-gray-600', 'text-gray-400', 'scale-100');
    step2Ind.classList.remove('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'text-black', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110');
    document.getElementById('step2OuterGlow').classList.add('opacity-0');
    document.getElementById('step2OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
    document.getElementById('step2Pulse').classList.add('opacity-0');
    document.getElementById('step2Pulse').classList.remove('opacity-75');
    document.getElementById('step2Ring').classList.remove('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
    document.getElementById('step2Loading').classList.add('hidden');
    document.getElementById('step2Number').classList.remove('hidden');

    // Reset step 2 text styling
    const step2Text = document.getElementById('step2Text');
    step2Text.classList.add('text-gray-500', 'bg-gray-800/50', 'border-gray-700');
    step2Text.classList.remove('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10');

    currentStep = 1;
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Step 2 -> Step 3 Navigation
function goToStep3() {
    if (!selectedDifficulty) {
        showToast('請選擇難度等級!', 2000);
        return;
    }

    // Transition animation
    document.getElementById('step2').style.opacity = '0';
    document.getElementById('step2').style.transform = 'translateX(-50px)';

    setTimeout(() => {
        document.getElementById('step2').classList.add('hidden');
        document.getElementById('step3').classList.remove('hidden');
        document.getElementById('step3').style.opacity = '0';
        document.getElementById('step3').style.transform = 'translateX(50px)';

        setTimeout(() => {
            document.getElementById('step3').style.transition = 'all 0.5s ease';
            document.getElementById('step3').style.opacity = '1';
            document.getElementById('step3').style.transform = 'translateX(0)';
        }, 50);

        // Update progress bar to 75%
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = '75%';
        document.getElementById('progressPercent').textContent = '75%';

        // Update connecting line to 75%
        document.getElementById('connectingLine').style.width = '75%';

        // Update step 2 to completed state
        document.getElementById('step2Loading').classList.add('hidden');
        document.getElementById('step2Number').classList.remove('hidden');
        document.getElementById('step2Number').textContent = '✓';
        document.getElementById('step2Number').classList.add('text-green-400', 'font-bold');
        document.getElementById('step2Indicator').classList.remove('scale-110');
        document.getElementById('step2Indicator').classList.add('scale-100', 'bg-gray-700', 'border-gray-600');
        document.getElementById('step2Indicator').classList.remove('from-amber-400', 'to-orange-600', 'border-amber-500', 'shadow-orange-500/50');
        document.getElementById('step2OuterGlow').classList.add('opacity-0');
        document.getElementById('step2OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
        document.getElementById('step2Pulse').classList.add('opacity-0');
        document.getElementById('step2Pulse').classList.remove('opacity-75');
        document.getElementById('step2Ring').classList.remove('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
        document.getElementById('step2Text').classList.remove('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'shadow-lg', 'shadow-amber-500/10');
        document.getElementById('step2Text').classList.add('text-green-400', 'bg-green-500/10', 'border-green-500/20');

        // Update step 3 to active state
        const step3Ind = document.getElementById('step3Indicator');
        step3Ind.classList.remove('bg-gray-800', 'border-gray-600', 'text-gray-400');
        step3Ind.classList.add('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'text-black', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110');
        document.getElementById('step3OuterGlow').classList.remove('opacity-0');
        document.getElementById('step3OuterGlow').classList.add('opacity-100', 'animate-pulse-slow');
        document.getElementById('step3Pulse').classList.remove('opacity-0');
        document.getElementById('step3Pulse').classList.add('opacity-75');
        document.getElementById('step3Ring').classList.add('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
        document.getElementById('step3Number').classList.add('hidden');
        document.getElementById('step3Icon').classList.remove('hidden');

        // Update step 3 text styling
        const step3Text = document.getElementById('step3Text');
        step3Text.classList.remove('text-gray-500', 'bg-gray-800/50', 'border-gray-700');
        step3Text.classList.add('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10');

        currentStep = 3;
        showToast('請輸入您的個人資料(選填)', 2000);
    }, 300);

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function backToStep2() {
    document.getElementById('step3').classList.add('hidden');
    document.getElementById('step2').classList.remove('hidden');

    // Reset progress bar to 50%
    const progressBar = document.getElementById('progressBar');
    progressBar.style.width = '50%';
    document.getElementById('progressPercent').textContent = '50%';

    // Reset connecting line to 50%
    document.getElementById('connectingLine').style.width = '50%';

    // Reset step 2 to active state (undo completed state)
    document.getElementById('step2Number').textContent = '2';
    document.getElementById('step2Number').classList.remove('text-green-400', 'font-bold');
    document.getElementById('step2Indicator').classList.remove('bg-gray-700', 'border-gray-600', 'scale-100');
    document.getElementById('step2Indicator').classList.add('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110', 'text-black');
    document.getElementById('step2OuterGlow').classList.remove('opacity-0');
    document.getElementById('step2OuterGlow').classList.add('opacity-100', 'animate-pulse-slow');
    document.getElementById('step2Pulse').classList.remove('opacity-0');
    document.getElementById('step2Pulse').classList.add('opacity-75');
    document.getElementById('step2Ring').classList.add('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
    document.getElementById('step2Text').classList.remove('text-green-400', 'bg-green-500/10', 'border-green-500/20');
    document.getElementById('step2Text').classList.add('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10');
    document.getElementById('step2Loading').classList.remove('hidden');
    document.getElementById('step2Number').classList.add('hidden');

    // Reset step 3 to inactive state
    const step3Ind = document.getElementById('step3Indicator');
    step3Ind.classList.add('bg-gray-800', 'border-gray-600', 'text-gray-400', 'scale-100');
    step3Ind.classList.remove('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'text-black', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110');
    document.getElementById('step3OuterGlow').classList.add('opacity-0');
    document.getElementById('step3OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
    document.getElementById('step3Pulse').classList.add('opacity-0');
    document.getElementById('step3Pulse').classList.remove('opacity-75');
    document.getElementById('step3Ring').classList.remove('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
    document.getElementById('step3Text').classList.add('text-gray-500', 'bg-gray-800/50', 'border-gray-700');
    document.getElementById('step3Text').classList.remove('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10');

    currentStep = 2;
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Step 2: Difficulty Selection
function selectDifficulty(element) {
    document.querySelectorAll('.difficulty-card').forEach(card => {
        card.classList.remove('selected');
    });

    element.classList.add('selected');
    selectedDifficulty = element.dataset.difficulty;

    document.getElementById('step2Btn').disabled = false;
}

function generateWorkout() {
    if (!selectedDifficulty) {
        showToast('請選擇難度等級!', 2000);
        return;
    }

    // Show loading state
    const btn = document.getElementById('step3Btn');
    const originalContent = btn.innerHTML;
    btn.innerHTML = '<div class="loading-spinner w-6 h-6 border-2 border-black border-t-transparent rounded-full animate-spin mr-2"></div><span>生成中...</span>';
    btn.disabled = true;

    // Simulate AI processing time for drama
    setTimeout(() => {
        // Fire confetti
        fireConfetti();

        // Generate exercises
        const exercises = generateExercises();

        // Render exercises
        renderExercises(exercises);

        // Update nutrition calculations based on weight
        updateNutritionDisplay();

        // Update summary with typing effect
        const muscleNames = {
            chest: '胸部', back: '背部', shoulders: '肩部', core: '核心',
            legs: '腿部', glutes: '臀部', arms: '手臂', fullbody: '全身'
        };
        const difficultyNames = { easy: '簡單', normal: '普通', hard: '困難' };
        const muscleText = selectedMuscles.map(m => muscleNames[m]).join('、');
        const summaryText = `針對${muscleText}的${difficultyNames[selectedDifficulty]}強度訓練,共 ${exercises.length} 個動作`;

        // Transition
        document.getElementById('step3').style.opacity = '0';
        document.getElementById('step3').style.transform = 'scale(0.9)';

        setTimeout(() => {
            document.getElementById('step3').classList.add('hidden');
            document.getElementById('step4').classList.remove('hidden');
            document.getElementById('step4').style.opacity = '0';

            // Update progress bar to 100% with glow effect
            const progressBar = document.getElementById('progressBar');
            progressBar.style.width = '100%';
            document.getElementById('progressPercent').textContent = '100%';

            // Update connecting line to full
            document.getElementById('connectingLine').style.width = '100%';

            // Update step 3 to completed state
            document.getElementById('step3Icon').classList.add('hidden');
            document.getElementById('step3Number').classList.remove('hidden');
            document.getElementById('step3Number').textContent = '✓';
            document.getElementById('step3Number').classList.add('text-green-400', 'font-bold');
            document.getElementById('step3Indicator').classList.remove('scale-110');
            document.getElementById('step3Indicator').classList.add('scale-100', 'bg-gray-700', 'border-gray-600');
            document.getElementById('step3Indicator').classList.remove('from-amber-400', 'to-orange-600', 'border-amber-500', 'shadow-orange-500/50');
            document.getElementById('step3OuterGlow').classList.add('opacity-0');
            document.getElementById('step3OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
            document.getElementById('step3Pulse').classList.add('opacity-0');
            document.getElementById('step3Pulse').classList.remove('opacity-75');
            document.getElementById('step3Ring').classList.remove('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
            document.getElementById('step3Text').classList.remove('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10', 'animate-pulse');
            document.getElementById('step3Text').classList.add('text-green-400', 'bg-green-500/10', 'border-green-500/20');

            // Update step 4 to active/completed state with celebration styling
            const step4Ind = document.getElementById('step4Indicator');
            step4Ind.classList.remove('bg-gray-800', 'border-gray-600', 'text-gray-400');
            step4Ind.classList.add('bg-gradient-to-br', 'from-amber-400', 'to-orange-600', 'text-black', 'border-amber-500', 'shadow-lg', 'shadow-orange-500/50', 'scale-110', 'bounce-in');
            document.getElementById('step4OuterGlow').classList.remove('opacity-0');
            document.getElementById('step4OuterGlow').classList.add('opacity-100', 'animate-pulse-slow');
            document.getElementById('step4Pulse').classList.remove('opacity-0');
            document.getElementById('step4Pulse').classList.add('opacity-75');
            document.getElementById('step4Ring').classList.add('border-amber-500/50', 'shadow-[0_0_15px_rgba(245,158,11,0.4)]');
            document.getElementById('step4Number').classList.add('hidden');
            document.getElementById('step4Icon').classList.remove('hidden');

            // Update step 4 text styling
            const step4Text = document.getElementById('step4Text');
            step4Text.classList.remove('text-gray-500', 'bg-gray-800/50', 'border-gray-700');
            step4Text.classList.add('text-amber-400', 'bg-amber-500/10', 'border-amber-500/20', 'font-bold', 'shadow-lg', 'shadow-amber-500/10', 'animate-pulse');

            // Type out summary
            const summaryElement = document.getElementById('workoutSummary');
            summaryElement.textContent = '';
            let i = 0;
            const typeInterval = setInterval(() => {
                if (i < summaryText.length) {
                    summaryElement.textContent += summaryText.charAt(i);
                    i++;
                } else {
                    clearInterval(typeInterval);
                }
            }, 30);

            setTimeout(() => {
                document.getElementById('step4').style.transition = 'all 0.5s ease';
                document.getElementById('step4').style.opacity = '1';
            }, 100);

            currentStep = 4;

            // Show success toast
            setTimeout(() => {
                showToast('🎉 訓練計畫生成完成!加油!', 3000);
            }, 500);

            // Re-init icons for new content
            lucide.createIcons();
        }, 300);

        // Reset button
        btn.innerHTML = originalContent;
        btn.disabled = false;

    }, 1500);

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function generateExercises() {
    let allExercises = [];

    selectedMuscles.forEach(muscle => {
        if (exerciseDB[muscle] && exerciseDB[muscle][selectedDifficulty]) {
            // Get exercises for this muscle and add muscle info to each
            const muscleExercises = exerciseDB[muscle][selectedDifficulty].map(ex => ({
                ...ex,
                muscle: muscle
            }));
            allExercises = allExercises.concat(muscleExercises);
        }
    });

    // Shuffle and pick 3-5 exercises
    const shuffled = allExercises.sort(() => 0.5 - Math.random());
    const count = Math.floor(Math.random() * 3) + 3; // 3 to 5
    const selected = shuffled.slice(0, Math.min(count, shuffled.length));

    // Add sets/reps details to each exercise
    return selected.map(exercise => {
        const details = getExerciseDetails(exercise.muscle, selectedDifficulty);
        return {
            ...exercise,
            sets: details.displaySets,
            reps: details.displayReps,
            rawSets: details.sets,
            rawReps: details.reps,
            isTimeBased: details.isTimeBased
        };
    });
}

function renderExercises(exercises) {
    const container = document.getElementById('exerciseContainer');
    container.innerHTML = '';

    const muscleNames = {
        chest: '胸部', back: '背部', shoulders: '肩部', core: '核心',
        legs: '腿部', glutes: '臀部', arms: '手臂', fullbody: '全身'
    };

    exercises.forEach((exercise, index) => {
        const muscle = exercise.muscle || selectedMuscles[0];

        const card = document.createElement('div');
        card.className = 'exercise-card glass rounded-3xl p-6 md:p-8 hover:shadow-2xl hover:shadow-gold-500/10 transition-all duration-300';
        card.style.animationDelay = `${index * 0.15}s`;

        // Add hover tilt effect
        card.addEventListener('mousemove', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            const rotateX = (y - centerY) / 20;
            const rotateY = (centerX - x) / 20;
            card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-5px)`;
        });

        card.addEventListener('mouseleave', () => {
            card.style.transform = 'perspective(1000px) rotateX(0) rotateY(0) translateY(0)';
        });

        // Build detailed info sections if available
        let detailsSection = '';
        if (exercise.description || exercise.precautions || exercise.targetMuscles || exercise.keyPoints) {
            detailsSection = `
                <div class="mt-4 space-y-3 border-t border-white/10 pt-4">
                    ${exercise.description ? `
                        <div class="flex items-start space-x-2 text-sm">
                            <div class="w-5 h-5 rounded-full bg-purple-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                <i data-lucide="info" class="w-3 h-3 text-purple-400"></i>
                            </div>
                            <div>
                                <span class="text-purple-400 font-medium block text-xs mb-0.5">動作說明</span>
                                <span class="text-gray-300">${exercise.description}</span>
                            </div>
                        </div>
                    ` : ''}
                    ${exercise.precautions ? `
                        <div class="flex items-start space-x-2 text-sm">
                            <div class="w-5 h-5 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                <i data-lucide="alert-triangle" class="w-3 h-3 text-red-400"></i>
                            </div>
                            <div>
                                <span class="text-red-400 font-medium block text-xs mb-0.5">注意事項</span>
                                <span class="text-gray-300">${exercise.precautions}</span>
                            </div>
                        </div>
                    ` : ''}
                    ${exercise.targetMuscles ? `
                        <div class="flex items-start space-x-2 text-sm">
                            <div class="w-5 h-5 rounded-full bg-blue-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                <i data-lucide="target" class="w-3 h-3 text-blue-400"></i>
                            </div>
                            <div>
                                <span class="text-blue-400 font-medium block text-xs mb-0.5">發力部位</span>
                                <span class="text-gray-300">${exercise.targetMuscles}</span>
                            </div>
                        </div>
                    ` : ''}
                    ${exercise.keyPoints ? `
                        <div class="flex items-start space-x-2 text-sm">
                            <div class="w-5 h-5 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                <i data-lucide="check-circle-2" class="w-3 h-3 text-green-400"></i>
                            </div>
                            <div>
                                <span class="text-green-400 font-medium block text-xs mb-0.5">重點注意</span>
                                <span class="text-gray-300">${exercise.keyPoints}</span>
                            </div>
                        </div>
                    ` : ''}
                </div>
            `;
        }

        // Split name into Chinese and English parts
        const nameParts = exercise.name.split(' ');
        const chineseName = nameParts[0];
        const englishName = nameParts.slice(1).join(' ');

        const hasVideo = exercise.videoUrl && exercise.videoUrl.length > 0;
        const videoId = hasVideo ? extractYouTubeId(exercise.videoUrl) : null;
        const isYouTube = videoId !== null;
        const videoThumbnail = isYouTube ? `https://img.youtube.com/vi/${videoId}/hqdefault.jpg` : (hasVideo ? '' : `http://static.photos/fitness/640x360/${(index % 5) + 1}`);

        // Generate unique ID for this video container
        const videoContainerId = `video-container-${index}`;

        card.innerHTML = `
            <div class="flex flex-col md:flex-row gap-6">
                <div class="md:w-1/3">
                    <div id="${videoContainerId}" class="video-placeholder rounded-2xl aspect-video relative overflow-hidden border border-gold-500/20 ${hasVideo ? 'hover:border-gold-500/50 cursor-pointer group' : ''}" ${hasVideo ? `onclick="playVideoInline('${videoContainerId}', '${exercise.videoUrl}', '${isYouTube ? 'youtube' : 'direct'}')"` : ''}>
                        <!-- Thumbnail/Preview State -->
                        <div id="${videoContainerId}-thumbnail" class="absolute inset-0 transition-opacity duration-300">
                            ${isYouTube ? `
                                <img src="${videoThumbnail}" alt="${exercise.name}" class="w-full h-full object-cover ${hasVideo ? 'opacity-80' : 'opacity-60'} group-hover:opacity-100 transition-all duration-500 group-hover:scale-110" onerror="this.src='http://static.photos/fitness/640x360/${(index % 5) + 1}'">
                                <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                                <div class="absolute inset-0 flex items-center justify-center">
                                    <div class="w-16 h-16 rounded-full bg-red-600/90 flex items-center justify-center transform group-hover:scale-125 transition-transform duration-300 shadow-lg shadow-red-600/50 group-hover:bg-red-500">
                                        <i data-lucide="play" class="w-8 h-8 text-white ml-1 fill-current"></i>
                                    </div>
                                </div>
                                <div class="absolute bottom-2 right-2 px-3 py-1 bg-black/70 rounded-full text-xs text-white border border-white/20 flex items-center gap-1">
                                    <i data-lucide="youtube" class="w-3 h-3 text-red-400"></i> 點擊播放
                                </div>
                                <div class="absolute top-2 left-2 px-2 py-1 bg-red-600/90 rounded text-xs text-white font-bold">YouTube</div>
                            ` : hasVideo ? `
                                <div class="w-full h-full bg-gray-800 flex items-center justify-center relative">
                                    <img src="http://static.photos/fitness/640x360/${(index % 5) + 1}" alt="${exercise.name}" class="w-full h-full object-cover opacity-60">
                                    <div class="absolute inset-0 flex items-center justify-center">
                                        <div class="w-16 h-16 rounded-full bg-gold-500/90 flex items-center justify-center transform group-hover:scale-125 transition-transform duration-300 shadow-lg shadow-gold-500/50 group-hover:bg-gold-400">
                                            <i data-lucide="play" class="w-8 h-8 text-white ml-1 fill-current"></i>
                                        </div>
                                    </div>
                                    <div class="absolute bottom-2 right-2 px-3 py-1 bg-black/70 rounded-full text-xs text-white border border-white/20 flex items-center gap-1">
                                        <i data-lucide="video" class="w-3 h-3 text-gold-400"></i> 點擊播放
                                    </div>
                                    <div class="absolute top-2 left-2 px-2 py-1 bg-gold-600/90 rounded text-xs text-white font-bold">影片</div>
                                </div>
                            ` : `
                                <img src="http://static.photos/fitness/640x360/${(index % 5) + 1}" alt="${exercise.name}" class="w-full h-full object-cover opacity-60">
                                <div class="absolute inset-0 flex items-center justify-center">
                                    <div class="w-16 h-16 rounded-full bg-gold-500/90 flex items-center justify-center">
                                        <i data-lucide="image" class="w-8 h-8 text-white"></i>
                                    </div>
                                </div>
                                <div class="absolute bottom-2 right-2 px-3 py-1 bg-black/70 rounded-full text-xs text-white border border-white/20">
                                    示範圖片
                                </div>
                            `}
                        </div>
                        
                        <!-- Video Player State (hidden initially) -->
                        <div id="${videoContainerId}-player" class="absolute inset-0 opacity-0 pointer-events-none transition-opacity duration-300 bg-black">
                            <!-- Video will be embedded here -->
                        </div>
                        
                        <!-- Close Button (hidden initially) -->
                        <button id="${videoContainerId}-close" onclick="event.stopPropagation(); closeVideoInline('${videoContainerId}')" class="absolute top-2 right-2 z-20 w-8 h-8 bg-black/80 rounded-full flex items-center justify-center text-white opacity-0 pointer-events-none transition-opacity duration-300 hover:bg-red-600">
                            <i data-lucide="x" class="w-5 h-5"></i>
                        </button>
                    </div>
                </div>
                <div class="md:w-2/3 flex flex-col justify-center">
                    <div class="flex items-center space-x-3 mb-3">
                        <span class="px-3 py-1 rounded-full bg-gold-500/20 text-gold-400 text-xs font-medium border border-gold-500/30 animate-pulse">
                            ${muscleNames[muscle]}
                        </span>
                        <span class="text-gray-500 text-sm flex items-center">
                            <i data-lucide="hash" class="w-3 h-3 mr-1"></i>
                            動作 ${index + 1}
                        </span>
                    </div>
                    <div class="mb-4">
                        <h3 class="text-2xl md:text-3xl font-bold text-white group-hover:text-gold-400 transition-colors mb-1">${chineseName}</h3>
                        <p class="text-base md:text-lg text-gray-400 font-medium italic">${englishName}</p>
                    </div>
                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div class="glass rounded-xl p-4 hover:bg-gold-500/10 transition-colors cursor-pointer group/stat">
                            <div class="text-gray-400 text-xs mb-1 flex items-center">
                                <i data-lucide="layers" class="w-3 h-3 mr-1"></i>
                                建議組數
                            </div>
                            <div class="text-2xl font-bold text-gold-400 group-hover/stat:scale-110 transition-transform">${exercise.sets}</div>
                        </div>
                        <div class="glass rounded-xl p-4 hover:bg-gold-500/10 transition-colors cursor-pointer group/stat">
                            <div class="text-gray-400 text-xs mb-1 flex items-center">
                                <i data-lucide="repeat" class="w-3 h-3 mr-1"></i>
                                建議次數
                            </div>
                            <div class="text-2xl font-bold text-gold-400 group-hover/stat:scale-110 transition-transform">${exercise.reps}</div>
                        </div>
                    </div>
                    ${detailsSection}
                </div>
            </div>
        `;

        container.appendChild(card);
    });
}

// Prepare and Print function
function prepareAndPrint() {
    // Add date to print header
    const printDate = document.getElementById('printDate');
    if (printDate) {
        const now = new Date();
        printDate.textContent = `生成日期:${now.getFullYear()}/${(now.getMonth() + 1).toString().padStart(2, '0')}/${now.getDate().toString().padStart(2, '0')}`;
    }

    // Show print-only elements
    document.querySelectorAll('.print-only').forEach(el => {
        el.style.display = 'block';
    });

    // Small delay to ensure rendering
    setTimeout(() => {
        window.print();

        // Hide print-only elements after printing
        setTimeout(() => {
            document.querySelectorAll('.print-only').forEach(el => {
                el.style.display = 'none';
            });
        }, 500);
    }, 100);
}

// Display conversion stats (can be called from console or added to UI)
function showConversionStats() {
    const report = ConversionTracker.getReport();
    console.table(report.byType);
    console.log('Attribution Report:', report.byAttribution);
    console.log('Recent Conversions:', report.recent);

    // Optional: Show in UI as toast
    const totalConversions = report.total;
    const contactCount = report.byType['contact_instructor'] || 0;
    const lineCount = report.byType['add_official_line'] || 0;
    const saveCount = report.byType['save_plan'] || 0;

    showToast(`📊 轉換統計: 總計 ${totalConversions} | 聯繫 ${contactCount} | Line ${lineCount} | 儲存 ${saveCount}`, 5000);
}

function resetWorkout() {
    // Visual feedback
    if (navigator.vibrate) {
        navigator.vibrate([100, 50, 100]);
    }

    // Fade out current step
    const currentStepEl = document.getElementById(`step${currentStep}`);
    currentStepEl.style.opacity = '0';
    currentStepEl.style.transform = 'scale(0.9) rotateX(10deg)';

    setTimeout(() => {
        // Reset state
        selectedMuscles = [];
        selectedDifficulty = null;
        currentStep = 1;

        // Reset UI with animation
        document.querySelectorAll('.muscle-card.selected').forEach((card, index) => {
            setTimeout(() => {
                card.classList.remove('selected');
                card.style.transform = 'rotate(360deg) scale(0.8)';
                setTimeout(() => card.style.transform = '', 300);
            }, index * 50);
        });

        document.querySelectorAll('.difficulty-card.selected').forEach(card => {
            card.classList.remove('selected');
            card.style.transform = '';
        });

        // Reset progress bar to initial state
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = '25%';
        document.getElementById('progressPercent').textContent = '25%';

        // Reset connecting line
        document.getElementById('connectingLine').style.width = '0%';

        // Reset Step 1 to active initial state
        document.getElementById('step1Number').classList.remove('hidden');
        document.getElementById('step1Check').classList.add('hidden');
        document.getElementById('step1Indicator').className = 'w-16 h-16 rounded-full bg-gradient-to-br from-amber-400 to-orange-600 flex items-center justify-center text-black font-bold text-xl shadow-lg shadow-orange-500/50 border-4 border-gray-900 relative z-10 transition-all duration-500 group-hover:scale-110 group-hover:shadow-orange-500/80';
        document.getElementById('step1Indicator').classList.add('from-amber-400', 'to-orange-600');
        document.getElementById('step1Indicator').classList.remove('bg-gray-700', 'border-gray-600');
        document.getElementById('step1Pulse').classList.remove('hidden');
        document.getElementById('step1Glow').classList.add('opacity-0');
        document.getElementById('step1Glow').classList.remove('opacity-100');
        document.getElementById('step1Label').className = 'text-sm font-bold text-amber-400 bg-amber-500/10 px-4 py-1.5 rounded-full border border-amber-500/30 shadow-lg shadow-amber-500/10 backdrop-blur-sm';
        document.getElementById('step1LabelGlow').classList.add('opacity-100');
        document.getElementById('step1LabelGlow').classList.remove('opacity-0');

        // Reset Step 2 to inactive state
        const step2Ind = document.getElementById('step2Indicator');
        step2Ind.className = 'w-16 h-16 rounded-full bg-gray-800 border-4 border-gray-600 flex items-center justify-center text-gray-400 font-bold text-xl transition-all duration-500 relative z-10 shadow-xl scale-100';
        step2Ind.innerHTML = '<i data-lucide="loader-2" class="w-7 h-7 hidden animate-spin" id="step2Loading"></i><span id="step2Number">2</span>';
        document.getElementById('step2OuterGlow').classList.add('opacity-0');
        document.getElementById('step2OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
        document.getElementById('step2Pulse').classList.add('opacity-0');
        document.getElementById('step2Pulse').classList.remove('opacity-75');
        document.getElementById('step2Ring').className = 'absolute -inset-1 rounded-full border-2 border-gold-500/0 transition-all duration-500';

        const step2Text = document.getElementById('step2Text');
        step2Text.className = 'text-sm font-medium text-gray-500 bg-gray-800/50 px-4 py-1.5 rounded-full border border-gray-700 transition-all duration-500 backdrop-blur-sm';

        // Reset Step 3 to inactive state
        const step3Ind = document.getElementById('step3Indicator');
        step3Ind.className = 'w-16 h-16 rounded-full bg-gray-800 border-4 border-gray-600 flex items-center justify-center text-gray-400 font-bold text-xl transition-all duration-500 relative z-10 shadow-xl scale-100';
        step3Ind.innerHTML = '<i data-lucide="user" class="w-7 h-7 hidden drop-shadow-md" id="step3Icon"></i><span id="step3Number">3</span>';
        document.getElementById('step3OuterGlow').classList.add('opacity-0');
        document.getElementById('step3OuterGlow').classList.remove('opacity-100', 'animate-pulse-slow');
        document.getElementById('step3Pulse').classList.add('opacity-0');
        document.getElementById('step3Pulse').classList.remove('opacity-75');
        document.getElementById('step3Ring').className = 'absolute -inset-1 rounded-full border-2 border-gold-500/0 transition-all duration-500';

        const step3Text = document.getElementById('step3Text');
        step3Text.className = 'text-sm font-medium text-gray-500 bg-gray-800/50 px-4 py-1.5 rounded-full border border-gray-700 transition-all duration-500 backdrop-blur-sm';

        // Reset buttons
        document.getElementById('step1Btn').disabled = true;
        document.getElementById('step2Btn').disabled = true;

        // Show step 1 with animation
        currentStepEl.classList.add('hidden');
        document.getElementById('step2').classList.add('hidden');
        document.getElementById('step3').classList.add('hidden');
        const step1 = document.getElementById('step1');
        step1.classList.remove('hidden');
        step1.style.opacity = '0';
        step1.style.transform = 'translateY(30px)';

        setTimeout(() => {
            step1.style.transition = 'all 0.5s ease';
            step1.style.opacity = '1';
            step1.style.transform = 'translateY(0)';
        }, 50);

        showToast('🔄 已重置!準備開始新的訓練', 2000);

        // Re-init icons
        lucide.createIcons();
    }, 300);

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Conversion Tracking System
const ConversionTracker = {
    // Store conversion data
    data: [],

    // Initialize tracking
    init() {
        this.attachEventListeners();
        this.loadStoredConversions();
    },

    // Attach click listeners to conversion elements
    attachEventListeners() {
        // 聯繫講師 (Contact Instructor) - data-line-cta
        document.querySelectorAll('a[data-line-cta]').forEach(el => {
            el.addEventListener('click', (e) => {
                this.trackConversion('contact_instructor', {
                    element: 'data-line-cta',
                    href: el.href,
                    text: el.textContent.trim(),
                    timestamp: new Date().toISOString()
                });
            });
        });

        // 加官方 Line (Add Official Line) - data-consult-cta
        document.querySelectorAll('a[data-consult-cta]').forEach(el => {
            el.addEventListener('click', (e) => {
                this.trackConversion('add_official_line', {
                    element: 'data-consult-cta',
                    href: el.href,
                    text: el.textContent.trim(),
                    timestamp: new Date().toISOString()
                });
            });
        });

        // 儲存計畫 (Save Plan) - prepareAndPrint button
        // Note: We need to intercept the prepareAndPrint function
        const originalPrepareAndPrint = window.prepareAndPrint;
        window.prepareAndPrint = () => {
            this.trackConversion('save_plan', {
                element: 'save_plan_button',
                action: 'print',
                workoutSummary: document.getElementById('workoutSummary')?.textContent || '',
                timestamp: new Date().toISOString()
            });
            // Call original function
            return originalPrepareAndPrint();
        };

        // Track product link clicks (optional - for e-commerce tracking)
        document.querySelectorAll('a[data-product]').forEach(el => {
            el.addEventListener('click', (e) => {
                this.trackConversion('product_click', {
                    element: 'product_link',
                    product: el.dataset.product,
                    productName: el.dataset.productName,
                    href: el.href,
                    timestamp: new Date().toISOString()
                });
            });
        });
    },

    // Track a conversion event
    trackConversion(type, details = {}) {
        const params = new URLSearchParams(window.location.search);
        const conversionData = {
            id: this.generateId(),
            type: type,
            timestamp: new Date().toISOString(),
            url: window.location.href,
            path: window.location.pathname,
            search: window.location.search,
            referrer: document.referrer || 'direct',
            userAgent: navigator.userAgent,
            // Include attribution params if available
            attribution: {
                rfme: params.get('rfme') || null,
                vipid: params.get('vipid') || null,
                utm_source: params.get('utm_source') || null,
                utm_medium: params.get('utm_medium') || null,
                utm_campaign: params.get('utm_campaign') || null
            },
            // Include workout context if available
            workoutContext: {
                selectedMuscles: selectedMuscles || [],
                difficulty: selectedDifficulty || null,
                hasPersonalInfo: !!(personalInfo.weight || personalInfo.height)
            },
            ...details
        };

        // Add to data array
        this.data.push(conversionData);

        // Store in localStorage for persistence
        this.saveConversions();

        // Log to console (for debugging)
        console.log(`[Conversion Tracked] ${type}:`, conversionData);

        // Send to analytics if available (Google Analytics, Facebook Pixel, etc.)
        this.sendToAnalytics(type, conversionData);

        // Optional: Send to custom backend endpoint
        // this.sendToBackend(conversionData);

        return conversionData;
    },

    // Generate unique ID for each conversion
    generateId() {
        return 'conv_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    },

    // Save to localStorage
    saveConversions() {
        try {
            localStorage.setItem('elitefit_conversions', JSON.stringify(this.data));
        } catch (e) {
            console.warn('Failed to save conversions to localStorage');
        }
    },

    // Load from localStorage
    loadStoredConversions() {
        try {
            const stored = localStorage.getItem('elitefit_conversions');
            if (stored) {
                this.data = JSON.parse(stored);
            }
        } catch (e) {
            console.warn('Failed to load conversions from localStorage');
        }
    },

    // Send to analytics platforms
    sendToAnalytics(type, data) {
        // Google Analytics 4 (gtag)
        if (typeof gtag !== 'undefined') {
            gtag('event', type, {
                event_category: 'conversion',
                event_label: data.element || type,
                custom_parameters: {
                    rfme: data.attribution.rfme,
                    vipid: data.attribution.vipid,
                    muscles: data.workoutContext.selectedMuscles?.join(','),
                    difficulty: data.workoutContext.difficulty
                }
            });
        }

        // Facebook Pixel
        if (typeof fbq !== 'undefined') {
            fbq('trackCustom', type, {
                content_name: data.element || type,
                content_type: 'button_click',
                value: 0,
                currency: 'TWD',
                referrer: data.referrer,
                utm_source: data.attribution.utm_source
            });
        }

        // Google Tag Manager dataLayer
        if (typeof dataLayer !== 'undefined') {
            dataLayer.push({
                event: 'elitefit_conversion',
                conversionType: type,
                conversionData: data
            });
        }
    },

    // Optional: Send to custom backend API
    async sendToBackend(data) {
        // Uncomment and modify endpoint when backend is ready
        /*
        try {
            const response = await fetch('https://your-api.com/conversions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            if (!response.ok) {
                throw new Error('Failed to send conversion');
            }
        } catch (error) {
            console.error('Backend conversion tracking failed:', error);
        }
        */
    },

    // Get all conversions
    getAllConversions() {
        return this.data;
    },

    // Get conversions by type
    getConversionsByType(type) {
        return this.data.filter(c => c.type === type);
    },

    // Get conversion report (summary)
    getReport() {
        const report = {
            total: this.data.length,
            byType: {},
            byAttribution: {
                rfme: {},
                vipid: {},
                utm_source: {}
            },
            recent: this.data.slice(-10) // Last 10 conversions
        };

        this.data.forEach(conv => {
            // Count by type
            report.byType[conv.type] = (report.byType[conv.type] || 0) + 1;

            // Count by attribution
            if (conv.attribution.rfme) {
                report.byAttribution.rfme[conv.attribution.rfme] =
                    (report.byAttribution.rfme[conv.attribution.rfme] || 0) + 1;
            }
            if (conv.attribution.vipid) {
                report.byAttribution.vipid[conv.attribution.vipid] =
                    (report.byAttribution.vipid[conv.attribution.vipid] || 0) + 1;
            }
            if (conv.attribution.utm_source) {
                report.byAttribution.utm_source[conv.attribution.utm_source] =
                    (report.byAttribution.utm_source[conv.attribution.utm_source] || 0) + 1;
            }
        });

        return report;
    },

    // Clear all data
    clear() {
        this.data = [];
        localStorage.removeItem('elitefit_conversions');
    },

    // Export as JSON (for reporting)
    exportJSON() {
        return JSON.stringify(this.data, null, 2);
    }
};

// Product Link Updater - Replaces default tracking code with rfme parameter
function updateProductLinks() {
    const params = new URLSearchParams(window.location.search);
    let rfme = params.get("rfme");

    function isValidParam(value) {
        if (value === null || value === undefined) return false;
        if (typeof value !== 'string') return false;
        const cleaned = value.trim().toLowerCase();
        return cleaned.length > 0 &&
            cleaned !== "undefined" &&
            cleaned !== "null" &&
            cleaned !== "undefinednull" &&
            cleaned !== "nan" &&
            !cleaned.includes("undefined") &&
            !cleaned.includes("null");
    }

    const DEFAULT_TRACKING_CODE = "dfd97cfc8971267a189047bbc90b56c7";

    // Only update if valid rfme exists
    if (!isValidParam(rfme)) return;

    const validRfme = String(rfme).trim();

    // Update all product links that contain the default tracking code
    document.querySelectorAll('a[href*="shop.amway.com.tw"]').forEach(link => {
        if (link.href.includes(DEFAULT_TRACKING_CODE)) {
            link.href = link.href.replace(DEFAULT_TRACKING_CODE, encodeURIComponent(validRfme));
        }
    });

    console.log(`[Product Links] Updated with rfme: ${validRfme}`);
}

// Add visual feedback for all interactive elements
document.addEventListener('DOMContentLoaded', () => {
    // Add hover sound effect simulation (visual)
    document.querySelectorAll('button, .muscle-card, .difficulty-card').forEach(el => {
        el.addEventListener('mouseenter', () => {
            el.style.transition = 'all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)';
        });
    });

    // Initialize Line CTA routing
    initLineCtaRouting();

    // Initialize Product Links with rfme parameter
    updateProductLinks();

    // Initialize Conversion Tracking
    ConversionTracker.init();

    // Make ConversionTracker available globally for debugging
    window.ConversionTracker = ConversionTracker;
});

// Debug helper - type ConversionTracker.getReport() in console to see stats

// Line CTA Routing - URL Query Parameter Handler
// Extract YouTube video ID from various YouTube URL formats
function extractYouTubeId(url) {
    if (!url) return null;

    // Handle different YouTube URL formats
    const patterns = [
        /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/,
        /^([a-zA-Z0-9_-]{11})$/ // Direct video ID
    ];

    for (const pattern of patterns) {
        const match = url.match(pattern);
        if (match) return match[1];
    }

    return null;
}

// Inline Video Player Functions
function playVideoInline(containerId, videoUrl, type) {
    const thumbnail = document.getElementById(`${containerId}-thumbnail`);
    const player = document.getElementById(`${containerId}-player`);
    const closeBtn = document.getElementById(`${containerId}-close`);

    // Hide thumbnail, show player
    thumbnail.style.opacity = '0';
    thumbnail.style.pointerEvents = 'none';
    player.style.opacity = '1';
    player.style.pointerEvents = 'auto';
    closeBtn.style.opacity = '1';
    closeBtn.style.pointerEvents = 'auto';

    // Clear previous content
    player.innerHTML = '';

    if (type === 'youtube') {
        const videoId = extractYouTubeId(videoUrl);
        if (videoId) {
            // Create YouTube iframe with autoplay
            const iframe = document.createElement('iframe');
            iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0&modestbranding=1&playsinline=1`;
            iframe.className = 'w-full h-full rounded-2xl';
            iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
            iframe.allowFullscreen = true;
            iframe.frameBorder = '0';
            player.appendChild(iframe);
        }
    } else {
        // Direct video file - use HTML5 video
        const video = document.createElement('video');
        video.src = videoUrl;
        video.className = 'w-full h-full rounded-2xl';
        video.controls = true;
        video.autoplay = true;
        video.playsInline = true; // Important for mobile
        video.style.objectFit = 'contain';
        player.appendChild(video);
    }

    // Re-init icons for the close button
    if (window.lucide) {
        lucide.createIcons();
    }
}

function closeVideoInline(containerId) {
    const thumbnail = document.getElementById(`${containerId}-thumbnail`);
    const player = document.getElementById(`${containerId}-player`);
    const closeBtn = document.getElementById(`${containerId}-close`);

    // Show thumbnail, hide player
    thumbnail.style.opacity = '1';
    thumbnail.style.pointerEvents = 'auto';
    player.style.opacity = '0';
    player.style.pointerEvents = 'none';
    closeBtn.style.opacity = '0';
    closeBtn.style.pointerEvents = 'none';

    // Stop video by clearing content
    setTimeout(() => {
        player.innerHTML = '';
    }, 300);
}

function initLineCtaRouting() {
    const params = new URLSearchParams(window.location.search);

    let rfme = params.get("rfme");
    let vipid = params.get("vipid");

    function isValidParam(value) {
        if (value === null || value === undefined) return false;
        if (typeof value !== 'string') return false;
        const cleaned = value.trim().toLowerCase();
        return cleaned.length > 0 &&
            cleaned !== "undefined" &&
            cleaned !== "null" &&
            cleaned !== "undefinednull" &&
            cleaned !== "nan" &&
            !cleaned.includes("undefined") &&
            !cleaned.includes("null");
    }

    const DEFAULT_LINE_CTA = "https://line.me/R/ti/p/@aplusteam";
    const DEFAULT_CONSULT_CTA = "https://line.me/R/app/1653879962-kMOqNXoG";

    let validRfme = null;
    let validVipid = null;

    if (isValidParam(rfme)) {
        validRfme = String(rfme).trim();
    }

    if (isValidParam(vipid)) {
        validVipid = String(vipid).trim();
    }

    // Update data-line-cta links (聯繫講師) - controlled by vipid
    let lineCtaUrl = DEFAULT_LINE_CTA;
    if (validVipid && validVipid.length > 0) {
        lineCtaUrl = `https://line.me/ti/p/~${encodeURIComponent(validVipid)}`;
    }

    document.querySelectorAll("a[data-line-cta]").forEach((a) => {
        if (a && lineCtaUrl) {
            a.href = lineCtaUrl;
            a.target = "_blank";
            a.rel = "noopener noreferrer";
        }
    });

    // Update data-consult-cta links (加官方 Line) - controlled by rfme
    let consultCtaUrl = DEFAULT_CONSULT_CTA;
    if (validRfme && validRfme.length > 0) {
        consultCtaUrl = `${DEFAULT_CONSULT_CTA}?rfme=${encodeURIComponent(validRfme)}`;
    }

    document.querySelectorAll("a[data-consult-cta]").forEach((a) => {
        if (a && consultCtaUrl) {
            a.href = consultCtaUrl;
            a.target = "_blank";
            a.rel = "noopener noreferrer";
        }
    });
}