Spaces:
Sleeping

File size: 174,963 Bytes
0bfd7b8
ae30394
 
1a8c409
ae30394
f13cbed
0d51d20
5203afb
1a8c409
c930e28
1a8c409
093c8e5
 
30ac4f0
 
ae30394
e36d094
0d51d20
c930e28
a5892a3
41708b9
1a8c409
30ac4f0
5203afb
0d51d20
ae30394
7e31bf0
1a8c409
 
0e0e7ab
a5892a3
 
 
b729dae
 
41708b9
 
b729dae
 
 
2b799cf
4e17e90
2b799cf
 
4e17e90
2b799cf
9abf676
2b799cf
 
 
 
 
4e17e90
2b799cf
 
b729dae
 
 
a5892a3
 
 
0e0e7ab
c92b125
7e31bf0
c92b125
9d2f8a4
1a8c409
8a6b673
9d2f8a4
 
 
 
1a8c409
7e31bf0
9d2f8a4
8a6b673
7e31bf0
4e17e90
 
9abf676
7e31bf0
4e17e90
7e31bf0
9d2f8a4
41708b9
 
9d2f8a4
 
8a6b673
7c6ac44
0e0e7ab
c930e28
a5892a3
78ff512
a5892a3
 
 
 
 
 
 
 
 
 
 
78ff512
a5892a3
 
 
 
 
 
 
 
 
78ff512
a5892a3
 
 
 
 
 
 
 
 
 
9abf676
45a2e54
a5892a3
 
 
 
 
 
 
 
 
c930e28
a5892a3
 
 
 
 
 
 
 
c930e28
 
 
 
 
7eb09e1
45a2e54
f13cbed
a5892a3
 
6924b31
 
a5892a3
e36d094
1a8c409
 
 
3633426
ebb0e5a
 
 
 
 
 
 
 
 
 
 
 
6924b31
 
 
 
 
 
 
 
 
 
 
 
a5892a3
249af8b
a5892a3
 
 
 
1a8c409
a5892a3
 
6924b31
 
 
ebb0e5a
45a2e54
a5892a3
7eb09e1
 
a5892a3
7eb09e1
bf34721
7eb09e1
 
bf34721
1a8c409
 
 
2b799cf
41708b9
 
7eb09e1
45a2e54
a5892a3
 
1a8c409
a5892a3
9abf676
a5892a3
153a108
 
 
 
 
 
78ff512
153a108
 
 
a5892a3
 
 
 
 
 
 
 
 
 
41708b9
 
153a108
a5892a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a8c409
 
 
 
 
 
 
 
 
a5892a3
1a8c409
 
 
 
 
a5892a3
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5892a3
1a8c409
a5892a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5203afb
a5892a3
ead9225
bf34721
 
 
a5892a3
bf34721
 
41708b9
 
 
 
 
8e91ed0
7e31bf0
4e17e90
3633426
 
 
 
 
 
 
bf34721
1a8c409
 
 
 
 
 
a5892a3
 
 
 
 
9abf676
 
 
 
5203afb
a5892a3
04b9b3f
7eb09e1
04b9b3f
 
 
 
 
 
 
a5892a3
7e31bf0
04b9b3f
 
a5892a3
7eb09e1
04b9b3f
7eb09e1
bf34721
a5892a3
45a2e54
7eb09e1
a5892a3
5203afb
7e31bf0
a5892a3
50f65ff
a5892a3
 
 
 
153a108
a5892a3
 
41708b9
 
a5892a3
 
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5892a3
 
 
 
1a8c409
 
 
 
 
 
a5892a3
41708b9
1a8c409
41708b9
 
a5892a3
 
5203afb
a5892a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb0e5a
4040cf4
 
a5892a3
 
 
 
 
 
 
 
 
 
 
 
 
 
ead9225
0bfd7b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5203afb
1a8c409
 
ae30394
9abf676
 
1a8c409
 
 
 
a5892a3
1a8c409
 
 
 
 
 
 
a209abd
 
1a8c409
50f65ff
1a8c409
 
 
 
 
4e17e90
 
82bb459
1a8c409
82bb459
3279ed3
 
 
874cb7b
1a8c409
bced39c
1a8c409
50f65ff
1a8c409
e36d094
1a8c409
 
 
 
 
 
 
 
 
 
 
527e290
 
 
 
 
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f0e4f1
 
 
 
 
 
 
 
 
 
 
 
 
1a8c409
 
 
 
 
6924b31
1a8c409
 
 
6924b31
1a8c409
 
 
 
 
 
 
ebb0e5a
 
1a8c409
 
 
 
 
 
ebb0e5a
 
 
 
 
 
 
 
 
 
 
1a8c409
 
 
 
 
 
 
6ae59de
 
 
 
 
 
1a8c409
 
 
 
6ae59de
1a8c409
527e290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
2fe1710
abfb5d8
8528213
 
abfb5d8
8528213
 
abfb5d8
 
8528213
abfb5d8
 
81b663d
8528213
 
 
 
 
 
 
 
2fe1710
 
 
 
 
81b663d
2fe1710
81b663d
2fe1710
8528213
 
 
 
abfb5d8
2fe1710
abfb5d8
8528213
2fe1710
81b663d
8528213
 
 
 
2fe1710
 
 
abfb5d8
 
2fe1710
 
abfb5d8
 
2fe1710
abfb5d8
 
81b663d
 
abfb5d8
 
2fe1710
abfb5d8
2fe1710
 
abfb5d8
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527e290
1a8c409
 
 
 
 
 
 
 
 
 
1a432bd
527e290
 
2fe1710
82bb459
ebb0e5a
8934f79
ebb0e5a
 
 
 
1a8c409
 
ebb0e5a
1a8c409
ebb0e5a
527e290
 
8934f79
ebb0e5a
1a8c409
 
 
 
 
 
 
ebb0e5a
527e290
ebb0e5a
 
 
527e290
1a8c409
ebb0e5a
527e290
1a8c409
a5892a3
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6924b31
 
 
1a8c409
 
 
6924b31
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82bb459
1a8c409
 
 
 
 
 
82bb459
c92b125
1a8c409
6924b31
82bb459
273f0f6
1a8c409
 
 
273f0f6
c93d4df
1a8c409
 
 
 
 
 
 
 
 
 
 
82bb459
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a58316
c93d4df
1a8c409
594a2aa
7eb09e1
c93d4df
1a8c409
 
 
 
 
05a407a
1a8c409
 
 
05a407a
1a8c409
 
 
d58438b
1a8c409
 
d58438b
1edf1f3
d58438b
1a8c409
41708b9
1a8c409
 
 
 
 
 
527e290
1a8c409
527e290
1a8c409
527e290
d58438b
1a8c409
 
 
 
 
d58438b
2fe1710
c93d4df
1a8c409
594a2aa
1a8c409
 
 
10b1057
 
1a8c409
 
 
 
 
10b1057
1a8c409
 
ae30394
10b1057
1a8c409
10b1057
1a8c409
594a2aa
c93d4df
1a8c409
594a2aa
5203afb
10b1057
1a8c409
 
a57924a
10b1057
 
1a8c409
7f0e4f1
1a8c409
 
 
 
 
 
 
 
 
 
 
 
50cafd3
1a8c409
6924b31
1a8c409
50cafd3
 
 
 
10b1057
 
7f0e4f1
1a8c409
 
9abf676
05a407a
1a8c409
7f0e4f1
1a8c409
 
05a407a
c93d4df
1a8c409
 
 
0be8db0
1a8c409
9abf676
 
 
1a8c409
9abf676
5203afb
 
 
9abf676
1a432bd
1a8c409
 
 
 
 
 
 
9abf676
 
 
 
 
 
6924b31
9abf676
 
 
 
 
1a8c409
9abf676
1a8c409
 
9abf676
 
 
 
 
 
6924b31
5203afb
1a8c409
5203afb
0ac87ff
1a8c409
 
0ac87ff
 
1a8c409
0ac87ff
 
 
1a8c409
 
 
1a432bd
0ac87ff
1a432bd
0ac87ff
1a8c409
e277387
0ac87ff
1a8c409
 
 
1a432bd
0ac87ff
1a8c409
 
1a432bd
6924b31
1a8c409
 
c93d4df
1a8c409
1a432bd
1a8c409
 
ebb0e5a
 
1a8c409
 
 
 
ebb0e5a
 
c930e28
30ac4f0
 
ebb0e5a
1a8c409
 
 
 
 
 
 
 
3279ed3
 
1a8c409
 
ebb0e5a
 
 
 
 
1a8c409
30ac4f0
3279ed3
1a8c409
ebb0e5a
 
1a8c409
 
 
 
7f0e4f1
 
1a8c409
 
 
 
 
 
ae30394
a5892a3
1a8c409
898fb51
 
 
1a8c409
 
898fb51
 
 
4040cf4
 
10b1057
4040cf4
6ae59de
4040cf4
6ae59de
 
 
 
4040cf4
 
 
 
 
6ae59de
 
 
 
 
 
 
 
 
 
 
4040cf4
6ae59de
4040cf4
 
 
 
6ae59de
4040cf4
 
 
 
10b1057
4040cf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
093c8e5
 
 
 
 
 
 
 
 
 
 
4040cf4
 
 
 
 
 
 
 
450bcc7
4040cf4
5debdd4
 
 
 
 
 
 
 
 
 
 
 
 
450bcc7
5debdd4
 
4040cf4
 
 
 
 
 
 
 
 
 
 
 
10b1057
4040cf4
 
 
 
 
 
6ae59de
4040cf4
 
6ae59de
4040cf4
 
 
6ae59de
 
 
 
 
4040cf4
 
6ae59de
4040cf4
 
 
 
 
 
 
527e290
4040cf4
527e290
 
 
 
 
4040cf4
527e290
4040cf4
 
 
527e290
 
4040cf4
4451fd0
6ae59de
4040cf4
 
6ae59de
 
4040cf4
 
10b1057
4040cf4
 
 
1a8c409
4040cf4
6ae59de
 
4040cf4
1a8c409
4040cf4
 
6ae59de
 
4040cf4
 
6ae59de
 
4040cf4
 
 
6ae59de
 
 
4451fd0
6ae59de
 
 
 
 
 
 
4451fd0
 
 
6ae59de
 
 
 
bd1a327
 
f60b665
 
 
bd1a327
 
 
 
f60b665
bd1a327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ae59de
bd1a327
 
 
 
6ae59de
f60b665
bd1a327
f60b665
 
 
 
6ae59de
 
 
 
4040cf4
6ae59de
 
7f0e4f1
 
 
 
10b1057
7f0e4f1
4040cf4
 
 
10b1057
6ae59de
4040cf4
 
 
6ae59de
 
 
 
 
 
 
 
 
 
 
 
527e290
 
4040cf4
6ae59de
 
f60b665
bd1a327
f60b665
bd1a327
 
 
 
 
 
 
 
 
 
 
f60b665
 
 
 
bf86ea4
 
 
f60b665
 
898fb51
bd1a327
 
6ae59de
 
898fb51
6ae59de
898fb51
 
4451fd0
abbf74d
 
 
6ae59de
8934f79
 
 
6ae59de
 
4451fd0
6ae59de
4451fd0
6ae59de
 
527e290
6ae59de
 
527e290
6ae59de
 
527e290
4040cf4
abbf74d
 
 
6ae59de
 
bd1a327
 
 
 
 
abbf74d
 
6ae59de
bd1a327
 
 
6ae59de
bd1a327
 
abbf74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4451fd0
 
a1137a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4451fd0
 
 
 
 
 
7f0e4f1
4040cf4
 
1a8c409
b45fdf8
4451fd0
 
 
 
 
abbf74d
 
 
 
 
 
 
 
 
ed344ce
 
 
abbf74d
 
ed344ce
abbf74d
 
 
 
 
 
 
 
 
 
 
ed344ce
abbf74d
 
 
ed344ce
abbf74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4451fd0
 
 
 
 
 
2f75255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dda215e
 
2f75255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dda215e
2f75255
 
dda215e
 
2f75255
 
 
 
 
 
 
ed344ce
dda215e
2f75255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dda215e
2f75255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dda215e
 
ed344ce
dda215e
 
2f75255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed344ce
2f75255
 
 
 
 
 
 
 
 
dda215e
 
 
2f75255
 
 
 
 
 
 
 
dda215e
 
 
 
 
 
 
 
 
 
 
 
 
 
2f75255
dda215e
2f75255
 
 
 
 
dda215e
2f75255
 
 
 
 
 
 
 
c201d52
 
 
 
 
 
 
 
 
 
 
 
 
 
2f75255
 
c201d52
2f75255
 
 
dda215e
2f75255
 
 
4451fd0
 
 
 
 
 
 
 
26ac68e
4451fd0
093c8e5
4451fd0
 
 
 
8934f79
 
 
 
 
4451fd0
 
8934f79
 
4451fd0
 
 
 
8934f79
 
4451fd0
 
 
 
 
 
abbf74d
4451fd0
 
 
 
 
 
8934f79
abbf74d
8934f79
 
 
 
 
 
 
 
4451fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
26ac68e
 
 
4451fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
abbf74d
 
 
4451fd0
abbf74d
4451fd0
 
8934f79
 
 
abbf74d
 
 
 
8934f79
 
 
4451fd0
 
abbf74d
 
 
4451fd0
 
abbf74d
4451fd0
 
7f0e4f1
 
4451fd0
 
 
898fb51
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450bcc7
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37116f6
 
 
 
 
 
093c8e5
 
 
 
 
 
 
 
 
37116f6
093c8e5
 
 
fe9116f
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
fe9116f
 
093c8e5
 
 
 
 
fe9116f
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527e290
093c8e5
 
 
 
 
 
 
 
abbf74d
 
 
 
 
 
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
abbf74d
37116f6
 
 
 
abbf74d
37116f6
093c8e5
 
 
 
 
 
 
 
 
 
 
abbf74d
 
093c8e5
 
 
 
 
 
 
abbf74d
 
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe9116f
 
 
093c8e5
 
 
 
abbf74d
093c8e5
 
 
 
 
abbf74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37116f6
abbf74d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
093c8e5
fe9116f
 
abbf74d
093c8e5
 
 
fe9116f
093c8e5
 
 
abbf74d
093c8e5
 
 
 
 
 
 
abbf74d
7f0e4f1
 
093c8e5
abbf74d
093c8e5
 
 
 
 
 
 
a5892a3
9d2f8a4
1a8c409
 
94dfbdf
1a8c409
c69d5a2
 
a5572c1
 
 
 
1a8c409
94dfbdf
 
 
51b10d2
a5572c1
 
 
 
149d1f4
f175cdb
 
 
 
 
 
 
 
 
 
 
a5572c1
 
 
 
3279ed3
a5572c1
 
 
 
149d1f4
a5572c1
 
 
 
149d1f4
a5572c1
 
149d1f4
e572948
 
a5572c1
149d1f4
a5572c1
149d1f4
a5572c1
5bf1bbb
a5572c1
09fe721
5bf1bbb
09fe721
5bf1bbb
 
293bd8b
a5572c1
 
09fe721
a5572c1
09fe721
293bd8b
149d1f4
a5572c1
09fe721
 
 
149d1f4
a5572c1
 
293bd8b
a5572c1
5bf1bbb
09fe721
149d1f4
a5572c1
5bf1bbb
 
 
09fe721
5bf1bbb
 
09fe721
a5572c1
149d1f4
a5572c1
 
 
 
 
 
 
f175cdb
a5572c1
 
 
 
149d1f4
a5572c1
 
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f175cdb
a5572c1
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
149d1f4
a5572c1
 
 
 
f175cdb
a5572c1
 
 
 
f175cdb
a5572c1
 
 
 
 
 
 
 
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f175cdb
149d1f4
a5572c1
 
 
 
 
 
149d1f4
a5572c1
 
 
149d1f4
a5572c1
 
 
f175cdb
a5572c1
 
 
3279ed3
a5572c1
 
3279ed3
a5572c1
 
 
 
 
 
3279ed3
a5572c1
 
 
 
3279ed3
a5572c1
f175cdb
a5572c1
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
149d1f4
a5572c1
 
149d1f4
a5572c1
a1137a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5572c1
 
 
 
 
 
 
 
 
 
149d1f4
a5572c1
 
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
 
 
 
 
 
149d1f4
a5572c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f175cdb
a5572c1
f175cdb
a5572c1
 
 
 
 
 
 
 
 
 
 
 
d9056aa
 
 
f175cdb
a5572c1
 
d9056aa
 
 
a5572c1
 
 
 
 
f175cdb
a5572c1
 
 
1a8c409
 
 
 
 
 
 
 
50cafd3
 
 
 
 
 
 
 
 
 
a5572c1
 
 
 
 
 
 
 
3279ed3
51b10d2
 
1a8c409
e572948
a5572c1
 
c92b125
a5572c1
293bd8b
 
a5572c1
 
 
 
 
149d1f4
a5572c1
c92b125
a5572c1
5203afb
bf34721
a5572c1
 
50cafd3
a5572c1
1a8c409
 
a5572c1
 
 
 
 
 
 
 
 
 
 
1a8c409
a5572c1
9abf676
 
 
 
 
 
a5572c1
1a8c409
 
a5572c1
50cafd3
 
 
 
 
 
1a8c409
50cafd3
 
 
 
 
 
 
1a8c409
 
 
50cafd3
 
 
 
 
 
a5572c1
50cafd3
a5572c1
50cafd3
a5572c1
 
1a8c409
 
 
 
 
 
 
 
 
 
 
 
 
a5572c1
6473723
a5572c1
50cafd3
 
1a8c409
 
50cafd3
 
 
 
1a8c409
 
50cafd3
1a8c409
 
 
 
a5572c1
 
 
4040cf4
 
898fb51
6ae59de
4040cf4
 
10b1057
450bcc7
898fb51
4040cf4
6ae59de
4040cf4
898fb51
6ae59de
 
4040cf4
6ae59de
 
 
 
5debdd4
 
 
 
 
4040cf4
6ae59de
 
4040cf4
6ae59de
 
 
4040cf4
 
a1137a2
 
 
 
b45fdf8
6ae59de
 
 
4451fd0
 
 
 
2f75255
dda215e
2f75255
 
 
 
 
 
 
 
6ae59de
a1137a2
 
898fb51
 
093c8e5
 
 
 
 
 
 
 
 
fe9116f
 
 
093c8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5572c1
50cafd3
 
 
1a8c409
a5572c1
 
 
50cafd3
 
 
1a8c409
 
a5572c1
 
6924b31
50cafd3
1a8c409
 
 
a5572c1
 
6924b31
50cafd3
 
 
 
 
 
 
1a8c409
50cafd3
 
1a8c409
a5572c1
 
 
50cafd3
1a8c409
 
50cafd3
 
 
 
 
 
ebb0e5a
a5572c1
 
 
05a407a
1a8c409
 
a5892a3
 
a5572c1
 
 
1a8c409
a5572c1
 
 
 
 
1a8c409
 
 
 
 
 
 
 
10b1057
1a8c409
a5572c1
 
 
1a8c409
a5572c1
bced39c
50cafd3
1a8c409
50cafd3
a5572c1
 
 
 
 
 
1a8c409
 
 
a5572c1
 
 
 
 
 
 
1a8c409
a5572c1
 
 
 
1a8c409
a5572c1
 
 
 
bced39c
a5572c1
 
 
 
ebb0e5a
 
a5572c1
 
a5892a3
6924b31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4040cf4
 
6ae59de
a1137a2
 
 
 
 
 
 
 
4451fd0
 
 
 
 
2f75255
 
 
 
 
fe9116f
093c8e5
 
 
 
 
 
 
 
450bcc7
 
 
 
4040cf4
 
 
 
 
 
5debdd4
 
 
4040cf4
 
ae30394
0d51d20
1a8c409
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
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
import xml.etree.ElementTree as ET
import gradio as gr
import geopandas as gpd
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import matplotlib as mpl
import matplotlib.font_manager as fm
from matplotlib.figure import Figure
from matplotlib.patches import Patch, FancyBboxPatch, Circle
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PIL import Image
import io
import os
import requests
import warnings
import tempfile
import re
import json
from html import escape
from typing import Tuple, List, Dict, Optional

warnings.filterwarnings('ignore')

# === 設定 Matplotlib 後端 ===
mpl.use('Agg')
mpl.rcParams['axes.unicode_minus'] = False

# ===============================================
# 0. 自動下載與檢查地圖檔
# ===============================================
def check_and_download_maps():
    map_sources = {
        "twCounty2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twcounty2010.json",
        "twTown2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twtown2010.json"
    }
    
    for filename, url in map_sources.items():
        if os.path.exists(filename):
            print(f"📂 偵測到現有地圖檔: {filename}")
            continue
            
        print(f"🔍 下載地圖檔 {filename} ...")
        try:
            r = requests.get(url, timeout=30)
            if r.status_code == 200:
                with open(filename, 'wb') as f:
                    f.write(r.content)
                print(f"✅ 下載成功: {filename}")
            else:
                print(f"⚠️ 下載失敗 {filename} (HTTP {r.status_code})")
        except Exception as e:
            print(f"❌ 下載過程錯誤: {e}")

check_and_download_maps()

# ===============================================
# 1. 設定中文字型
# ===============================================
def set_custom_font():
    if os.path.exists("kaiu.ttf"):
        try:
            fm.fontManager.addfont("kaiu.ttf")
            font_prop = fm.FontProperties(fname="kaiu.ttf")
            mpl.rcParams['font.family'] = font_prop.get_name()
            print(f"✅ 成功載入本地 kaiu.ttf,已設為預設字型。")
            return font_prop
        except Exception as e: 
            print(f"⚠️ 載入 kaiu.ttf 失敗: {e}")
    
    mpl.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'KaiTi', 'SimHei', 'Arial Unicode MS', 'sans-serif'] + mpl.rcParams['font.sans-serif']
    font_download_path = "NotoSansTC-Regular.otf"
    
    if not os.path.exists(font_download_path) and not any(f.name in ['Microsoft JhengHei', 'SimHei', 'KaiTi'] for f in fm.fontManager.ttflist):
        print("⬇️ 嘗試下載備用中文字型 (NotoSansTC)...")
        try:
            url = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/TraditionalChinese/NotoSansTC-Regular.otf"
            r = requests.get(url, allow_redirects=True, timeout=60)
            with open(font_download_path, 'wb') as f:
                f.write(r.content)
            fm.fontManager.addfont(font_download_path)
            print("✅ 備用字型下載完成")
        except Exception as e:
            print(f"⚠️ 備用字型下載失敗: {e}")
    elif os.path.exists(font_download_path):
         fm.fontManager.addfont(font_download_path)
    return None

CUSTOM_FONT_PROP = set_custom_font()

# ===============================================
# 2. 台灣 Open Data 智能解析核心
# ===============================================

# 【時間欄位識別】
TIME_FIELDS = [
    '年', '月', '日', '時', '分', '秒', 
    'year', 'month', 'day', 'hour', 'minute', 'second',
    '日期', '時間', '日時', 'date', 'time', 'datetime',
    '統計期', '期別', 'period',
    '發布', '報告', 'release', 'report'
]

# 【時間格式模式】
TIME_PATTERNS = {
    'iso_8601_date': r'^\d{4}-\d{2}-\d{2}$',
    'iso_8601_datetime': r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}',
    'iso_8601_compact': r'^\d{8}$',
    'compact_datetime': r'^\d{14}$',
    'compact_datetime_tz': r'^\d{14}[+-]\d{2}$',
    'roc_date': r'^1\d{2}[-/]\d{1,2}[-/]\d{1,2}$',
    'roc_year_month': r'^1\d{2}[-/]\d{1,2}$',
    'roc_compact': r'^1\d{6}$',
    'roc_year_only': r'^\d{2,3}$',
    'taiwanese_date': r'^\d{4}年\d{1,2}月\d{1,2}日$',
    'taiwanese_datetime': r'^\d{4}年\d{1,2}月\d{1,2}日\d{1,2}時\d{1,2}分',
    'slash_ymd': r'^\d{4}/\d{1,2}/\d{1,2}$',
    'slash_mdy': r'^\d{1,2}/\d{1,2}/\d{4}$',
    'slash_dmy': r'^\d{1,2}/\d{1,2}/\d{4}$',
    'season': r'^[12]\d{3}[Q1-4]$',
    'season_zh': r'^[12]\d{3}年[第]?[1-4]季$',
    'year_only': r'^[12]\d{3}$',
    'month_seq': r'^([1-9]|1[0-2])$',
}
TIME_PATTERNS = {k: re.compile(v) for k, v in TIME_PATTERNS.items()}

# 【地區欄位識別】
REGION_FIELDS = [
    '縣', '市', '鄉', '鎮', '區', '地區',
    'county', 'city', 'township', 'town', 'district', 'area',
    '行政區', '所在地', 'location', '地點',
    '村里', '里', 'village', 'site', 'site_id'
]

# 【縣市代碼對映】
COUNTY_CODE_MAP = {
    '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': '連江縣',
    '65000': '新北市', '63000': '臺北市', '68000': '桃園市', '66000': '臺中市', 
    '67000': '臺南市', '64000': '高雄市', '10002': '宜蘭縣', '10004': '新竹縣', 
    '10005': '苗栗縣', '10007': '彰化縣', '10008': '南投縣', '10009': '雲林縣', 
    '10010': '嘉義縣', '10013': '屏東縣', '10014': '臺東縣', '10015': '花蓮縣', 
    '10016': '澎湖縣', '10017': '基隆市', '10018': '新竹市', '10020': '嘉義市', 
    '09007': '連江縣', '09020': '金門縣'
}

# 【標準地區名稱對映】
REGION_NAME_MAP = {
    # normalize_name 會先把「台」換成「臺」,所以鍵要用「臺」
    '臺灣': '全臺灣', '全國': '全臺灣'
}

NON_VALUE_KEYWORDS = ['code', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date', 'yyy',
                      '代碼', '編號', '序號', '經度', '緯度']
TOTAL_REGION_NAMES = {'全臺灣', '總計', '合計', '全國總計'}

# 圖資是 2010 年版本,之後桃園縣升格為直轄市、轄下鄉鎮市改制為區
MAP_NAME_ALIASES = {'桃園縣': '桃園市'}

def modernize_name(name: str) -> str:
    """把舊行政區名稱換成現行名稱,並去掉圖資中海域部分的「(海)」標記。圖資與使用者資料都套用同一個函式才對得上。"""
    for old, new in MAP_NAME_ALIASES.items():
        name = name.replace(old, new)
    name = name.replace('(海)', '').replace('(海)', '')
    if name.startswith('桃園市') and len(name) > 3 and name[-1] in '鄉鎮市':
        name = '桃園市' + name[3:-1] + '區'   # 桃園市中壢市 → 桃園市中壢區;桃園市桃園市 → 桃園市桃園區
    return name

# 縣市標準名稱;資料只寫「臺中」「新北」時,用來補上「市/縣」
COUNTY_NAMES = {v for v in COUNTY_CODE_MAP.values() if len(v) == 3}

# 欄名看起來是比率/平均類指標時,跨地區或跨年度不能加總
RATE_PATTERN = re.compile(r'率|%|%|每[十百千萬]|平均|比例|比重|指數|密度|人均')

def is_rate_col(col) -> bool:
    return bool(RATE_PATTERN.search(str(col)))

def default_agg(col) -> str:
    return "平均" if is_rate_col(col) else "加總"

# --- 工具函數 ---

def normalize_name(name: str) -> str:
    if pd.isna(name) or name == '': return ""
    name = str(name).strip().replace(' ', '').replace(' ', '')
    name = name.replace('台', '臺')
    if name.endswith('.0'): name = name[:-2]  # 數字代碼被讀成 float 時 (10.0 → 10)
    if name in COUNTY_CODE_MAP: return COUNTY_CODE_MAP[name]
    if name in REGION_NAME_MAP: return REGION_NAME_MAP[name]
    # 「臺中」→ 臺中市;「新竹」「嘉義」同時有市和縣,無法判斷就不補
    candidates = [name + s for s in '市縣' if name + s in COUNTY_NAMES]
    if len(candidates) == 1: return candidates[0]
    return modernize_name(name)

def get_numeric_columns(df: pd.DataFrame, exclude: List[str]) -> List[str]:
    numeric_cols = []
    for col in df.columns:
        if col in exclude: continue
        if any(k in str(col).lower() for k in NON_VALUE_KEYWORDS): continue
        if pd.api.types.is_numeric_dtype(df[col]):
            numeric_cols.append(col)
        else:
            try:
                sample = df[col].dropna().head(50)
                # 至少 80% 可轉為數字才算數值欄,避免夾雜少量數字的文字欄被誤判
                if len(sample) > 0 and pd.to_numeric(sample, errors='coerce').notna().mean() >= 0.8:
                    numeric_cols.append(col)
            except (ValueError, TypeError):
                pass
    return numeric_cols

def parse_time_format(time_str: str) -> Optional[Tuple[str, str]]:
    time_str = str(time_str).strip()
    if time_str.endswith('.0'): time_str = time_str[:-2]  # 含缺值的整數欄會被讀成 float
    for pattern_type, pattern in TIME_PATTERNS.items():
        if pattern.match(time_str):
            if 'roc' in pattern_type:
                try:
                    if pattern_type == 'roc_year_only':
                        roc_year = int(time_str)
                        if 10 <= roc_year <= 200:
                            return (pattern_type, str(roc_year + 1911))
                        else:
                            continue
                    
                    parts = re.split(r'[-/]', time_str)
                    if len(parts) >= 1:
                        roc_year = int(parts[0])
                        ad_year = roc_year + 1911
                        if pattern_type == 'roc_year_month' and len(parts) >= 2:
                            month = int(parts[1])
                            normalized = f"{ad_year:04d}-{month:02d}"
                        elif pattern_type == 'roc_date' and len(parts) >= 3:
                            month = int(parts[1]); day = int(parts[2])
                            normalized = f"{ad_year:04d}-{month:02d}-{day:02d}"
                        else: normalized = str(ad_year)
                        return (pattern_type, normalized)
                except (ValueError, IndexError):
                    pass
            
            elif pattern_type == 'taiwanese_date':
                match = re.search(r'(\d{4})年(\d{1,2})月(\d{1,2})日', time_str)
                if match:
                    y, m, d = match.groups()
                    return (pattern_type, f"{y}-{int(m):02d}-{int(d):02d}")
            elif pattern_type == 'slash_ymd':
                parts = time_str.split('/')
                if len(parts) == 3 and int(parts[0]) > 1900:
                    return (pattern_type, f"{parts[0]}-{int(parts[1]):02d}-{int(parts[2]):02d}")
            elif pattern_type == 'iso_8601_compact' or pattern_type == 'compact_date':
                if len(time_str) == 8:
                    return (pattern_type, f"{time_str[0:4]}-{time_str[4:6]}-{time_str[6:8]}")
            return (pattern_type, time_str)
    return None

def _name_looks_like_time(col_name: str) -> bool:
    name = str(col_name).lower()
    # 單字關鍵字(年、月、日…)只比對欄名結尾,避免「平均年齡」「身分證」這類欄名被誤判
    return any((k in name) if len(k) > 1 else name.endswith(k) for k in TIME_FIELDS + ['期'])

def _values_look_like_time(series: pd.Series) -> bool:
    sample = series.dropna().astype(str).head(20)
    return len(sample) > 0 and sum(parse_time_format(s) is not None for s in sample) / len(sample) > 0.5

def detect_time_column(df: pd.DataFrame) -> Optional[Tuple[str, List[str], Dict]]:
    def by_name():
        return [c for c in df.columns if _name_looks_like_time(c)]

    def by_numeric_range():
        found = []
        for col in df.columns:
            if not pd.api.types.is_numeric_dtype(df[col]): continue
            sample = df[col].dropna().head(20)
            if sample.empty or not (sample % 1 == 0).all(): continue
            if sample.between(1900, 2100).all() or sample.between(90, 200).all():
                found.append(col)
        return found

    def by_pattern():
        return list(df.columns)

    possible_time_cols = []
    for finder in (by_name, by_numeric_range, by_pattern):
        possible_time_cols = [c for c in finder() if _values_look_like_time(df[c])]
        if possible_time_cols: break

    if not possible_time_cols: return None

    time_col = possible_time_cols[0]
    available_times = []
    time_formats = {}
    
    temp_parsed = df[time_col].astype(str).apply(parse_time_format)
    
    valid_times = []
    for idx, val in temp_parsed.items():
        if val:
            fmt_type, normalized = val
            valid_times.append(normalized)
            time_formats[normalized] = fmt_type
            
    if valid_times:
        available_times = sorted(list(set(valid_times)), reverse=True)
    
    return (time_col, available_times, time_formats)

def smart_parse_data(df: pd.DataFrame):
    if df is None or df.empty: return None, "資料為空", [], [], [], "county", None, {}, None
    
    data_start_idx = 0
    for i in range(min(5, len(df))):
        row = df.iloc[i]
        num_count = 0; total_count = 0
        for val in row:
            total_count += 1
            try:
                float(str(val).replace(',', ''))
                num_count += 1
            except (ValueError, TypeError):
                pass
        if total_count > 0 and (num_count / total_count) > 0.4:
            data_start_idx = i; break
            
    if data_start_idx > 0:
        new_header = df.iloc[data_start_idx-1]
        df_processed = df.iloc[data_start_idx:].copy()
        df_processed.columns = new_header
    else:
        df_processed = df.copy()
        
    for col in df_processed.columns:
        if pd.api.types.is_numeric_dtype(df_processed[col]): continue
        # 容許千分位逗號 (1,234);只有整欄都能轉成數字才轉換
        cleaned = df_processed[col].astype(str).str.replace(',', '', regex=False).str.strip()
        converted = pd.to_numeric(cleaned, errors='coerce')
        if converted.notna().any() and converted.notna().sum() == df_processed[col].notna().sum():
            df_processed[col] = converted
        
    time_col = None; available_times = []; time_formats = {}
    time_result = detect_time_column(df_processed)
    if time_result:
        time_col, available_times, time_formats = time_result
        def _norm_time(x):
            parsed = parse_time_format(x)
            return parsed[1] if parsed else str(x)
        df_processed['time_parsed'] = df_processed[time_col].astype(str).map(_norm_time)
    
    region_col = None; map_level = "county"
    potential_cols = [c for c in df_processed.columns if any(k in str(c).lower() for k in REGION_FIELDS)]
    
    for col in potential_cols + list(df_processed.columns):
        if col not in df_processed.columns: continue
        sample = df_processed[col].dropna().head(20).astype(str).tolist()
        if not sample: continue
        has_town = any(('區' in s or '鄉' in s or '鎮' in s) for s in sample)
        has_county = any(('縣' in s or '市' in s) for s in sample)
        has_code = any(str(s).split('.')[0] in COUNTY_CODE_MAP for s in sample)
        
        if has_town: region_col = col; map_level = "town"; break
        elif has_county or has_code:
            if not region_col: region_col = col; map_level = "county"
            
    regions = []
    if region_col:
        df_processed['region_normalized'] = df_processed[region_col].apply(normalize_name)
        regions = sorted(df_processed[df_processed['region_normalized']!=""]['region_normalized'].unique().tolist())
        exclude = [region_col, time_col, 'time_parsed', 'region_normalized'] if time_col else [region_col, 'region_normalized']
        numeric_cols = get_numeric_columns(df_processed, exclude)
        level_name = "鄉鎮市區" if map_level == "town" else "縣市"
        msg = f"✓ 偵測成功 (層級: {level_name}, 時間: {time_col}, 地區: {region_col})"
    else:
        msg = "⚠️ 未偵測到明確的地區欄位"
        exclude = [time_col, 'time_parsed'] if time_col else []
        numeric_cols = get_numeric_columns(df_processed, exclude)
        
    return df_processed, msg, numeric_cols, available_times, regions, map_level, time_col, time_formats, region_col

# ===============================================
# 3. 地圖與圖表生成函數
# ===============================================

COUNTY_MAP_FILE = "twCounty2010.geo.json"
TOWN_MAP_FILE = "twTown2010.geo.json"
GDF_COUNTY = None
GDF_TOWN = None


def _clean_rings(coords):
    return [ring for ring in coords if len(ring) >= 4]  # 少於 4 點的環不是合法 LinearRing

def _read_geojson_robust(filename):
    """新版 shapely/pyogrio 遇到退化環 (<4 點) 會直接拋錯,這裡先濾掉再建立 GeoDataFrame"""
    with open(filename, encoding='utf-8') as f:
        data = json.load(f)
    features = []
    for feat in data.get('features', []):
        geom = feat.get('geometry') or {}
        if geom.get('type') == 'Polygon':
            rings = _clean_rings(geom['coordinates'])
            if not rings: continue
            geom['coordinates'] = rings
        elif geom.get('type') == 'MultiPolygon':
            polys = [r for r in (_clean_rings(p) for p in geom['coordinates']) if r]
            if not polys: continue
            geom['coordinates'] = polys
        features.append(feat)
    return gpd.GeoDataFrame.from_features(features, crs="EPSG:4326")

def load_map_file(level="county"):
    filename = TOWN_MAP_FILE if level == "town" else COUNTY_MAP_FILE
    try:
        if not os.path.exists(filename): return gpd.GeoDataFrame({'name': [], 'geometry': []})
        try:
            gdf = gpd.read_file(filename)
        except Exception:
            gdf = _read_geojson_robust(filename)
        if gdf.crs is None: gdf = gdf.set_crs("EPSG:4326")
        elif gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")
        if not gdf['geometry'].is_valid.all(): gdf['geometry'] = gdf['geometry'].buffer(0)
        try:
            gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.0005 if level == 'town' else 0.001, preserve_topology=True)
        except Exception:
            pass
        gdf = gdf[gdf['geometry'].notna()]
        gdf = gdf[~gdf['geometry'].is_empty]

        cols_lower = {c.lower(): c for c in gdf.columns}
        county_col = next((cols_lower[k] for k in ['countyname', 'county', 'c_name'] if k in cols_lower), None)
        town_col = next((cols_lower[k] for k in ['townname', 'town', 't_name'] if k in cols_lower), None)
        
        if level == "town":
            if county_col and town_col: gdf['name'] = gdf[county_col] + gdf[town_col]
            elif town_col: gdf['name'] = gdf[town_col]
            elif county_col: gdf['name'] = gdf[county_col]
        else:
            if county_col: gdf['name'] = gdf[county_col]
        
        if 'name' not in gdf.columns:
            str_cols = gdf.select_dtypes(include=['object']).columns
            if len(str_cols) > 0: gdf['name'] = gdf[str_cols[0]]
            else: gdf['name'] = gdf.index.astype(str)

        gdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')
        gdf['name'] = gdf['name'].map(modernize_name)
        if level == "town" and county_col:
            gdf['縣市'] = gdf[county_col].astype(str).str.replace('台', '臺').map(modernize_name)
        print(f"✅ 地圖 ({level}) 載入成功,筆數: {len(gdf)}")
        return gdf
    except Exception as e:
        print(f"❌ 地圖檔讀取失敗 ({filename}): {e}")
        return gpd.GeoDataFrame({'name': [], 'geometry': []})

def get_gdf(level):
    global GDF_TOWN, GDF_COUNTY
    if level == "town":
        if GDF_TOWN is None or GDF_TOWN.empty: GDF_TOWN = load_map_file("town")
        return GDF_TOWN
    else:
        if GDF_COUNTY is None or GDF_COUNTY.empty: GDF_COUNTY = load_map_file("county")
        return GDF_COUNTY

# ===============================================
# 新增:XML 通用解析函式
# ===============================================
def parse_xml_to_df(file_path):
    try:
        # 優先嘗試 Pandas 內建讀取 (需要 pandas >= 1.3 以及 lxml)
        try:
            return pd.read_xml(file_path)
        except:
            pass
            
        # 如果 Pandas 讀取失敗,使用手動解析 (相容性較高)
        tree = ET.parse(file_path)
        root = tree.getroot()
        
        data = []
        for child in root:
            row = {}
            # 1. 讀取屬性 (Attributes)
            row.update(child.attrib)
            # 2. 讀取子節點 (Child Tags)
            for subchild in child:
                # 如果子節點還有子節點,為了簡化,僅取文字內容
                if subchild.text:
                    row[subchild.tag] = subchild.text.strip()
            if row:
                data.append(row)
                
        return pd.DataFrame(data)
    except Exception as e:
        print(f"XML 解析失敗: {e}")
        return pd.DataFrame() # 回傳空表

def _upload_outputs_empty(msg):
    """上傳失敗/清除檔案時的 18 個輸出(順序需與 file_input.change 的 outputs 一致)"""
    e = gr.update(choices=[])
    return (
        None, msg, e, e, gr.update(choices=["全國總計"], value=["全國總計"]), None,
        e, e, "county", e, "",
        e, e, e, [],
        gr.update(value="10"), gr.update(value=2), e
    )

def _read_table(file_path: str) -> Optional[pd.DataFrame]:
    lower = file_path.lower()
    if lower.endswith('.csv'):
        for enc in ('utf-8-sig', 'cp950'):  # utf-8-sig 可去除 Excel 匯出的 BOM
            try: return pd.read_csv(file_path, encoding=enc)
            except UnicodeDecodeError: continue
        return pd.read_csv(file_path, encoding='utf-8', encoding_errors='replace')
    if lower.endswith('.json'): return pd.read_json(file_path)
    if lower.endswith('.xlsx'): return pd.read_excel(file_path)
    if lower.endswith('.xml'): return parse_xml_to_df(file_path)
    return None

def unmatched_regions(df, gdf) -> List[str]:
    """資料中有、但地圖上找不到的地區名稱(多半是名稱寫法或行政區沿革不同)"""
    if df is None or 'region_normalized' not in df.columns or gdf is None or gdf.empty: return []
    known = set(gdf['name'])
    return sorted(r for r in df['region_normalized'].unique()
                  if r and r not in known and r not in TOTAL_REGION_NAMES)

def process_uploaded_file(file_obj):
    if file_obj is None:
        return _upload_outputs_empty("請先上傳資料檔案 📂")
    try:
        # gr.Examples 傳入的是路徑字串,一般上傳則是檔案物件
        file_path = file_obj if isinstance(file_obj, str) else file_obj.name
        df = _read_table(file_path)
        if df is None:
            return _upload_outputs_empty("❌ 不支援的檔案格式")

        processed_df, msg, cols, times, regions, map_level, time_col, time_formats, region_col = smart_parse_data(df)
        gdf = get_gdf(map_level)

        missing = unmatched_regions(processed_df, gdf)
        if missing:
            shown = '、'.join(missing[:6]) + (f" …共 {len(missing)} 個" if len(missing) > 6 else "")
            msg += f"\n⚠️ 無法對應到地圖的地區:{shown}"

        latest_year = times[0] if times else "全部"
        stats_html = generate_stats_summary(processed_df, cols, latest_year)

        return (
            processed_df, msg,
            gr.update(choices=cols, value=cols[0] if cols else None),
            gr.update(choices=["全部"] + times, value=times[0] if times else "全部"),
            gr.update(choices=["全國總計"] + regions, value=["全國總計"]),
            processed_df.head(100),
            gr.update(choices=times, value=times[-1] if times else None),
            gr.update(choices=times, value=times[0] if times else None),
            map_level,
            gr.update(choices=["全部"] + times, value=times[0] if times else "全部"),
            stats_html,
            gr.update(choices=times, value=times[-1] if times else None),
            gr.update(choices=times, value=times[0] if times else None),
            gr.update(choices=cols, value=cols[1] if len(cols) > 1 else None),
            cols,
            gr.update(value="10"),
            gr.update(minimum=1, maximum=10, value=2, step=1),
            gr.update(choices=["全部"] + times, value=times[0] if times else "全部")
        )
    except Exception as e:
        import traceback; traceback.print_exc()
        return _upload_outputs_empty(f"❌ 檔案處理錯誤: {e}")

# ===============================================
# 4. 共用輔助函式(資料彙整、分級、繪圖)
# ===============================================

COLOR_SCALES = {"紅色系": "YlOrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "Hot"}
MPL_CMAPS = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}
AGG_FUNCS = {"加總": "sum", "平均": "mean", "最大值": "max"}
CLASS_MODES = ["連續", "分位數 (5 級)", "等距 (5 級)"]
NO_DATA_COLOR = "#d1d5db"
# 地圖底圖與框線(與 tw-county-map 一致):海面淡藍底;縣市界深灰;鄉鎮界淺灰細線,再疊一層深灰縣市界,層級一眼分得出來。
# 原本界線是白色,低值的淡色區域與白色背景混在一起,看不出海岸線與相鄰邊界。
MAP_SEA = "#e4eef7"
MAP_EDGE = "#5f6b7c"
MAP_EDGE_TOWN = "#aab3bf"
MAP_COUNTY_LINE = "#374151"
NO_DATA_LABEL = "無資料"

def _scheme_key(color_scheme) -> str:
    key = (color_scheme or "紅色系").split()[0]
    return key if key in COLOR_SCALES else "紅色系"

def _resolve_col(col, all_cols):
    if col: return col
    if all_cols: return all_cols[0]
    raise gr.Error("未選擇指標")

def _require_df(df):
    if df is None: raise gr.Error("請先上傳資料檔案")

def _require_regions(df):
    _require_df(df)
    if 'region_normalized' not in df.columns:
        raise gr.Error("資料中未偵測到地區欄位,無法產生此圖表")

def _require_map(level):
    gdf = get_gdf(level)
    if gdf is None or gdf.empty: raise gr.Error("地圖圖資載入失敗")
    return gdf

def _period_label(time) -> str:
    return str(time) if time and time != "全部" else "全部時間加總"

def _tmp_path(suffix: str) -> str:
    fd, path = tempfile.mkstemp(suffix=suffix)
    os.close(fd)
    return path

def _named_path(stem: str, suffix: str) -> str:
    """下載檔名用中文:放在獨立的暫存資料夾裡,檔名即為使用者下載到的名稱"""
    safe = re.sub(r'[\\/:*?"<>|\r\n\t]+', '_', str(stem)).strip(' ._')[:80] or "統計圖"
    return os.path.join(tempfile.mkdtemp(), safe + suffix)

def _level_name(map_level_state) -> str:
    return "鄉鎮市區" if map_level_state == "town" else "縣市"

def _map_stem(col, time, map_level_state, extra="") -> str:
    """例:縣市出生數統計圖_2024、鄉鎮市區人口數統計圖_動畫_2020-2024"""
    period = f"_{time}" if time and time != "全部" else ""
    return f"{_level_name(map_level_state)}{col}統計圖{extra}{period}"

def filter_time(df, time):
    if time and time != "全部" and 'time_parsed' in df.columns:
        return df[df['time_parsed'] == str(time)]
    return df

def aggregate_by_region(df, col, time, agg_method=None):
    """依地區彙整單一指標;沒有資料的地區保留 NaN,不再當成 0"""
    plot_df = filter_time(df, time).copy()
    plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce')
    return plot_df.groupby('region_normalized')[col].agg(AGG_FUNCS.get(agg_method or default_agg(col), 'sum')).reset_index()

def merge_geo(gdf, data):
    return gdf.merge(data, left_on='name', right_on='region_normalized', how='left')

def _fmt_num(x, big: bool) -> str:
    return f"{x:,.0f}" if big else f"{x:,.2f}"

def class_edges(values: pd.Series, mode: str, k: int = 5):
    """分級邊界;連續模式或資料不足以分級時回傳 None。動畫要用全時段的邊界,所以獨立成函式。"""
    s = values.dropna()
    if mode not in CLASS_MODES[1:] or s.nunique() < 2: return None
    if mode.startswith("分位數"):
        edges = np.unique(s.quantile(np.linspace(0, 1, k + 1)).to_numpy())
    else:
        edges = np.linspace(s.min(), s.max(), k + 1)
    return edges if len(edges) >= 3 else None

def classify(values: pd.Series, mode: str, k: int = 5, edges=None):
    """
    將數值分級,回傳 (依序的級距標籤, 每列對應的標籤 Series);不分級時回傳 None。
    可傳入既有的 edges,讓多張圖共用同一組級距。
    """
    if edges is None: edges = class_edges(values, mode, k)
    if edges is None: return None
    s = values.dropna()
    big = float(np.abs(edges).max()) >= 100
    cats = pd.cut(s, bins=edges, include_lowest=True)
    labels = [f"{_fmt_num(iv.left, big)} – {_fmt_num(iv.right, big)}" for iv in cats.cat.categories]
    mapping = dict(zip(cats.cat.categories, labels))
    label_series = pd.Series(NO_DATA_LABEL, index=values.index, dtype=object)
    label_series.loc[s.index] = cats.map(mapping).astype(object)
    return labels, label_series

def _to_hex(c: str) -> str:
    """plotly 的顏色可能是 'rgb(r, g, b)',matplotlib 只吃 hex"""
    if not c.startswith('rgb('): return c
    r, g, b = (int(float(v)) for v in c[4:-1].split(','))
    return f'#{r:02x}{g:02x}{b:02x}'

def _class_palette(labels: List[str], scheme: str) -> Dict[str, str]:
    # 色階低端接近白色會看不到,從 0.2 開始取色
    pos = np.linspace(0.2, 1.0, len(labels)).tolist()
    colors = px.colors.sample_colorscale(COLOR_SCALES[scheme], pos)
    return dict(zip(labels, (_to_hex(c) for c in colors)))

def _is_town(merged) -> bool:
    """鄉鎮市區層級的地圖資料才有「縣市」欄(load_map_file 加的)"""
    return '縣市' in getattr(merged, 'columns', [])

def _edge_style(merged) -> Tuple[str, float]:
    return (MAP_EDGE_TOWN, 0.4) if _is_town(merged) else (MAP_EDGE, 0.6)

def _add_county_outline(fig, merged, geo="geo"):
    """鄉鎮圖疊上縣市界(深灰)。只畫圖上有的縣市,fitbounds 才不會被撐大"""
    if not _is_town(merged): return
    lon, lat = county_outline_lines(tuple(sorted(merged['縣市'].dropna().unique())))
    fig.add_trace(go.Scattergeo(lon=lon, lat=lat, mode="lines", geo=geo, hoverinfo="skip", showlegend=False,
                                line=dict(color=MAP_COUNTY_LINE, width=1.6)))

def _style_map_ax(ax):
    """matplotlib 地圖軸:海面底色、不畫座標軸(set_axis_off 會連底色一起關掉,所以改成只隱藏刻度與邊框)"""
    ax.set_facecolor(MAP_SEA)
    ax.set_xticks([]); ax.set_yticks([])
    ax.set_xlabel(''); ax.set_ylabel('')   # geopandas 會自動標「Geodetic latitude [degree]」
    for spine in ax.spines.values(): spine.set_visible(False)

def _plot_county_outline(ax, merged):
    if not _is_town(merged): return
    county = _require_map("county")
    county[county['name'].isin(merged['縣市'].dropna().unique())].boundary.plot(ax=ax, color=MAP_COUNTY_LINE, linewidth=0.8)

def _style_map_layout(fig, title: str, bottom_legend: bool = False, merged=None):
    fig.update_geos(fitbounds="locations", visible=False, bgcolor=MAP_SEA)
    color, width = _edge_style(merged)
    fig.update_traces(marker_line_width=width, marker_line_color=color, selector=dict(type="choropleth"))
    layout = dict(
        margin={"r": 0, "t": 50, "l": 0, "b": 40},
        height=750, autosize=True,
        title=dict(text=title, y=0.97, x=0.5, xanchor='center', font=dict(size=18)),
    )
    if bottom_legend:
        layout["legend"] = dict(orientation="h", yanchor="top", y=0, xanchor="center", x=0.5, title_text="")
    else:
        layout["coloraxis_colorbar"] = dict(orientation="h", yanchor="top", y=0, xanchor="center", x=0.5,
                                            thickness=12, len=0.6, title_side="top")
    fig.update_layout(**layout)

def add_region_picker(fig, merged, geos=("geo",), stats=()):
    """
    加縣市/鄉鎮市區下拉選單:選取後在該區標一個點,並在圖上方顯示標籤框
    (參考圖解排名的標籤:名稱+名次+數值)。標籤框是固定大小的標註,不隨地圖縮放。
    鄉鎮市區層級先選縣市、再選該縣市的鄉鎮市區(第二個選單隨縣市切換內容)。
    純 plotly updatemenus,匯出的互動 HTML 也能用。
    geos:要同步標點的 geo 子圖;stats:[(指標名, 數值 Series)],名次依數值由大到小。
    """
    m = merged[merged.geometry.notna() & ~merged.geometry.is_empty]
    pill = "#1f4e79"
    base = len(fig.data)
    for geo in geos:
        fig.add_trace(go.Scattergeo(lon=[], lat=[], mode="markers", geo=geo, hoverinfo="skip", showlegend=False,
                                    marker=dict(size=12, color=pill, line=dict(color="white", width=2))))
    idx = list(range(base, base + len(geos)))
    fig.update_layout(annotations=[*fig.layout.annotations, dict(
        xref="paper", yref="paper", x=0.5, y=0.93, xanchor="center", yanchor="top", showarrow=False,
        visible=False, text="", font=dict(size=15, color="#111827"), bgcolor="white",
        bordercolor=pill, borderwidth=2, borderpad=6)])
    ann = f"annotations[{len(fig.layout.annotations) - 1}]"
    ranks = [(lbl, ser, ser.rank(ascending=False, method="min")) for lbl, ser in stats]

    def label(i, name):
        parts = []
        for lbl, ser, rk in ranks:
            v = ser.get(i)
            head = f"{lbl} " if len(ranks) > 1 else ""
            if pd.isna(v):
                parts.append(f"{head}{NO_DATA_LABEL}")
            else:
                val = _fmt_num(v, abs(v) >= 100)
                if len(ranks) == 1: val = f"{lbl}:{val}"
                parts.append(f"{head}<span style='color:{pill}'><b>#{int(rk[i])}</b></span> {val}")
        return f"<span style='color:{pill}'><b>{name}</b></span>" + (" │ " + " │ ".join(parts) if parts else "")

    def btn(label_, name=None, geom=None, i=None, extra=None):
        if geom is None:
            st, lay = {"lon": [[]] * len(idx), "lat": [[]] * len(idx)}, {f"{ann}.visible": False}
        else:
            pt = geom.representative_point()
            html = label(i, name) if i is not None else f"<span style='color:{pill}'><b>{name}</b></span>"
            st = {"lon": [[pt.x]] * len(idx), "lat": [[pt.y]] * len(idx)}
            lay = {f"{ann}.visible": True, f"{ann}.text": html}
        return dict(label=label_, method="update", args=[st, {**lay, **(extra or {})}, idx])

    def menu(buttons, x):
        return dict(type="dropdown", buttons=buttons, x=x, y=1.0, xanchor="left", yanchor="top",
                    showactive=True, bgcolor="white")

    def regions(group):
        return [btn(str(n), n, g, i) for i, n, g in zip(group.index, group['name'], group.geometry)]

    if '縣市' not in m.columns:
        fig.update_layout(updatemenus=[menu([btn("(不選取)")] + regions(m), 0.01)])
        return fig

    county_btns = [btn("(全部縣市)", extra={"updatemenus[1].buttons": [btn("(先選縣市)")],
                                            "updatemenus[1].active": 0})]
    for county, group in m.groupby('縣市'):
        geom = group.geometry.union_all() if hasattr(group.geometry, "union_all") else group.geometry.unary_union
        sub = [btn("(整個縣市)", county, geom)] + regions(group)
        county_btns.append(btn(str(county), county, geom,
                               extra={"updatemenus[1].buttons": sub, "updatemenus[1].active": 0}))
    fig.update_layout(updatemenus=[menu(county_btns, 0.01), menu([btn("(先選縣市)")], 0.16)])
    return fig

def build_choropleth(merged, value_col, title, scheme="紅色系", mode="連續",
                     scale=None, midpoint=None, hover_data=None):
    """
    互動地圖。連續模式用色條;分級模式用離散色塊+圖例(避免北部都會區極端值把其他縣市壓成同一色)。
    沒有資料的地區以灰色顯示。
    """
    binned = classify(merged[value_col], mode) if scale is None else None
    hover_data = hover_data or {value_col: ':,.2f'}

    if binned is None:
        fig = px.choropleth(
            merged, geojson=merged.geometry, locations=merged.index, color=value_col,
            color_continuous_scale=scale or COLOR_SCALES[scheme], color_continuous_midpoint=midpoint,
            projection="mercator", hover_name='name', hover_data=hover_data
        )
        missing = merged[merged[value_col].isna()]
        if not missing.empty:
            fig.add_trace(go.Choropleth(
                geojson=json.loads(missing.geometry.to_json()), locations=missing.index,
                z=[0] * len(missing), colorscale=[[0, NO_DATA_COLOR], [1, NO_DATA_COLOR]],
                showscale=False, text=missing['name'],
                hovertemplate=f"%{{text}}<br>{NO_DATA_LABEL}<extra></extra>"
            ))
        _style_map_layout(fig, title, merged=merged)
    else:
        labels, label_series = binned
        merged = merged.assign(分級=label_series)
        palette = _class_palette(labels, scheme)
        palette[NO_DATA_LABEL] = NO_DATA_COLOR
        order = labels + ([NO_DATA_LABEL] if (label_series == NO_DATA_LABEL).any() else [])
        fig = px.choropleth(
            merged, geojson=merged.geometry, locations=merged.index, color='分級',
            color_discrete_map=palette, category_orders={'分級': order},
            projection="mercator", hover_name='name', hover_data={**hover_data, '分級': False}
        )
        _style_map_layout(fig, title, bottom_legend=True, merged=merged)
    _add_county_outline(fig, merged)
    return add_region_picker(fig, merged, stats=[(value_col, merged[value_col])])

def build_static_map(merged, value_col, title, scheme="紅色系", mode="連續", figsize=(12, 12),
                     edges=None, vrange=None, title_size=24, legend_size=12, cbar_pad=0.05):
    """
    靜態圖 (matplotlib),使用 Figure 物件而非 pyplot,避免多人同時使用時共用全域狀態。
    動畫的每一幀傳入相同的 edges(分級)或 vrange(連續),各幀顏色才能互相比較。
    """
    fig = Figure(figsize=figsize)
    ax = fig.subplots()
    binned = classify(merged[value_col], mode, edges=edges)
    if binned is None:
        vmin, vmax = vrange if vrange else (None, None)
        edge, lw = _edge_style(merged)
        merged.plot(column=value_col, cmap=MPL_CMAPS[scheme], linewidth=lw, ax=ax, edgecolor=edge,
                    vmin=vmin, vmax=vmax, legend=True, legend_kwds={'shrink': 0.6, 'pad': cbar_pad},
                    missing_kwds={'color': NO_DATA_COLOR, 'label': NO_DATA_LABEL})
    else:
        labels, label_series = binned
        palette = _class_palette(labels, scheme)
        palette[NO_DATA_LABEL] = NO_DATA_COLOR
        handles = []
        for lab in labels + [NO_DATA_LABEL]:
            sub = merged[label_series == lab]
            if lab == NO_DATA_LABEL and sub.empty: continue
            if not sub.empty: sub.plot(ax=ax, color=palette[lab], linewidth=_edge_style(merged)[1], edgecolor=_edge_style(merged)[0])
            handles.append(Patch(facecolor=palette[lab], edgecolor='0.5', label=lab))  # 空級距也列在圖例,各幀圖例一致
        ax.legend(handles=handles, title=value_col, loc='lower right', fontsize=legend_size,
                  title_fontsize=legend_size + 1)
    _plot_county_outline(ax, merged)
    font_kw = {'fontproperties': CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}
    ax.set_title(title, size=title_size, **font_kw)
    _style_map_ax(ax)
    return fig

# === 統計摘要函式 (白底深字版) ===
def generate_stats_summary(df, all_cols, target_year=None):
    if df is None or not all_cols: return ""
    calc_df = df.copy()
    if target_year and target_year != "全部" and 'time_parsed' in calc_df.columns:
        calc_df = calc_df[calc_df['time_parsed'] == str(target_year)]
        title_suffix = f" ({escape(str(target_year))})"
    else:
        title_suffix = " (全部年份)"

    stats_html = f"<div style='margin-bottom: 10px; font-size: 16px; color: #374151; font-weight: 700; display: flex; align-items: center;'>📊 數據總覽 <span style='font-size: 14px; color: #6b7280; font-weight: 400; margin-left: 8px;'>{title_suffix}</span></div>"
    stats_html += "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-bottom: 8px;'>"

    if isinstance(all_cols, str): all_cols = [all_cols]

    for col in all_cols:
        if col in ['time_parsed', 'time_sort', 'time_gif_parsed', 'region_normalized']: continue
        try:
            data = pd.to_numeric(calc_df[col], errors='coerce').dropna()
            if len(data) == 0: continue
            name = escape(str(col))
            rate = is_rate_col(col)
            big = f"{data.mean():,.1f}" if rate else f"{data.sum():,.0f}"
            note = "<span style='font-size:12px;color:#9ca3af;font-weight:400'>(比率型指標,顯示平均)</span>" if rate else ""
            stats_html += f"""
            <div style='background: white; padding: 14px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); border: 1px solid #f3f4f6; border-left: 5px solid #667eea;'>
                <div style='font-size: 13px; color: #6b7280; margin-bottom: 4px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;' title='{name}'>{name}</div>
                <div style='font-size: 26px; font-weight: 800; color: #1f2937; margin-bottom: 4px; letter-spacing: -0.5px;'>{big}{note}</div>
                <div style='font-size: 12px; color: #9ca3af; display: flex; justify-content: space-between;'>
                    <span>Avg: {data.mean():,.1f}</span>
                    <span>Max: {data.max():,.0f}</span>
                </div>
            </div>"""
        except Exception:
            continue
    stats_html += "</div>"
    return stats_html

# ===============================================
# 5. 圖表產生函式(地圖、排行、趨勢、動畫)
# ===============================================

RANK_ORDERS = ["最高", "最低"]
DIFF_MODES = ["變化率 (%)", "絕對差異"]

def generate_ranking(df, col, time, top_n_str, rank_order, all_cols):
    _require_regions(df)
    col = _resolve_col(col, all_cols)
    try:
        ranking = aggregate_by_region(df, col, time).fillna(0)
        slice_n = len(ranking) if str(top_n_str).strip() == "全部" else int(top_n_str or 10)
        lowest = rank_order == "最低"
        # 取前 N 名後反轉,讓第 1 名顯示在長條圖最上方
        ranking = ranking.sort_values(col, ascending=lowest).head(slice_n).iloc[::-1]

        fig = go.Figure(go.Bar(
            x=ranking[col], y=ranking['region_normalized'], orientation='h',
            marker=dict(color=ranking[col], colorscale='Viridis', showscale=False),
            text=ranking[col].apply(lambda x: f'{x:,.1f}' if is_rate_col(col) else f'{x:,.0f}'), textposition='outside', cliponaxis=False
        ))
        fig.update_layout(
            title=f'🏆 {col} — {rank_order} {top_n_str} 名({_period_label(time)})',
            xaxis_title='數值', yaxis_title='地區',
            height=max(400, len(ranking) * 30 + 120), margin=dict(l=10, r=60, t=60, b=40)
        )
        return fig, gr.Tabs(selected="tab_ranking")
    except Exception as e:
        raise gr.Error(f"排行榜產生失敗: {e}")

def generate_comparison_map(df, col, time1, time2, diff_mode, map_level_state, all_cols):
    _require_regions(df)
    target_gdf = _require_map(map_level_state)
    col = _resolve_col(col, all_cols)
    if 'time_parsed' not in df.columns: raise gr.Error("資料中未偵測到時間欄位,無法做時間差異比較")
    all_times = sorted(df['time_parsed'].unique())
    time1 = time1 or all_times[0]
    time2 = time2 or all_times[-1]

    try:
        d1 = aggregate_by_region(df, col, time1).rename(columns={col: 't1'})
        d2 = aggregate_by_region(df, col, time2).rename(columns={col: 't2'})
        data = d1.merge(d2, on='region_normalized', how='outer')
        data['絕對差異'] = data['t2'] - data['t1']
        # 基期為 0 時變化率無意義,留空而不是硬塞 100%
        data['變化率'] = data['絕對差異'] / data['t1'].where(data['t1'] != 0) * 100
        merged = merge_geo(target_gdf, data)

        if diff_mode == "絕對差異":
            value_col, unit_fmt = '絕對差異', ':,.0f'
        else:
            value_col, unit_fmt = '變化率', ':.1f'
        hover = {value_col: unit_fmt, 't1': ':,.0f', 't2': ':,.0f'}
        fig = build_choropleth(
            merged, value_col, f'⚖️ {col} {value_col}對比 ({time1} → {time2})',
            scale='RdYlGn', midpoint=0, hover_data=hover
        )
        return fig, gr.Tabs(selected="tab_compare")
    except Exception as e:
        raise gr.Error(f"差異地圖產生失敗: {e}")

def generate_dual_map(df, col1, col2, time, map_level_state, all_cols):
    _require_regions(df)
    target_gdf = _require_map(map_level_state)
    col1 = _resolve_col(col1, all_cols)
    if not col2: col2 = all_cols[1] if len(all_cols) > 1 else col1

    try:
        data1 = aggregate_by_region(df, col1, time)
        data2 = aggregate_by_region(df, col2, time)
        merged = merge_geo(target_gdf, data1)
        merged = merged.merge(data2, left_on='name', right_on='region_normalized', how='left', suffixes=('', '_2'))
        col2_name = col2 + '_2' if col1 == col2 else col2  # 兩邊選同一指標時 merge 會加 _2 後綴
        merged[col1] = merged[col1].fillna(0); merged[col2_name] = merged[col2_name].fillna(0)

        fig = make_subplots(
            rows=1, cols=2,
            specs=[[{"type": "choropleth"}, {"type": "choropleth"}]],
            subplot_titles=(f"{col1}", f"{col2}"),
            horizontal_spacing=0.02
        )

        geo_json = json.loads(merged.geometry.to_json())
        for idx, (name, z, scale, x) in enumerate(
                [(col1, merged[col1], "Blues", 0.25), (col2, merged[col2_name], "OrRd", 0.75)], start=1):
            fig.add_trace(go.Choropleth(
                geojson=geo_json, locations=merged.index, z=z, colorscale=scale, name=name,
                text=merged['name'], hovertemplate="%{text}<br>" + name + ": %{z:,.0f}<extra></extra>",
                showscale=True, colorbar=dict(orientation="h", x=x, y=0, len=0.4, thickness=10, title=name),
                geo="geo" if idx == 1 else "geo2", marker_line_width=_edge_style(merged)[1], marker_line_color=_edge_style(merged)[0]
            ), row=1, col=idx)
        for g in ("geo", "geo2"): _add_county_outline(fig, merged, geo=g)

        geo_common = dict(visible=False, projection_type="mercator", fitbounds="locations", bgcolor=MAP_SEA)
        fig.update_layout(
            geo=dict(**geo_common, domain=dict(x=[0, 0.48], y=[0, 1])),
            geo2=dict(**geo_common, domain=dict(x=[0.52, 1], y=[0, 1])),
            title=dict(text=f"🆚 {col1}  vs  {col2}  ── 雙指標地理分布對比({_period_label(time)})",
                       x=0.5, xanchor="center", font=dict(size=17)),
            margin={"r": 10, "t": 70, "l": 10, "b": 50}, height=750, autosize=True, showlegend=False
        )
        add_region_picker(fig, merged, geos=("geo", "geo2"), stats=[(col1, merged[col1]), (col2, merged[col2_name])])
        return fig, gr.Tabs(selected="tab_dual")
    except Exception as e:
        raise gr.Error(f"雙指標地圖產生失敗: {e}")

ISLAND_COUNTIES = ('金門縣', '連江縣', '澎湖縣')

def _map_frame(df, col, time, agg_method, map_level_state, show_islands):
    """彙整指標並合併到地圖;關閉離島時移除金門/連江/澎湖,讓本島可以放大"""
    target_gdf = _require_map(map_level_state)
    if not show_islands:
        target_gdf = target_gdf[~target_gdf['name'].str.startswith(ISLAND_COUNTIES)]
    return merge_geo(target_gdf, aggregate_by_region(df, col, time, agg_method))

def generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):
    _require_regions(df)
    col = _resolve_col(col, all_cols)
    try:
        merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands)
        fig = build_choropleth(
            merged, col, f"🗺️ {col} - 地理分布圖({_period_label(time)})",
            scheme=_scheme_key(color_scheme), mode=class_mode
        )
        return fig, gr.Tabs(selected="tab_map")
    except Exception as e:
        raise gr.Error(f"繪圖失敗: {e}")

def export_static_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):
    _require_regions(df)
    col = _resolve_col(col, all_cols)
    try:
        merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands)
        fig = build_static_map(merged, col, f"{col} - 地圖 ({_period_label(time)})",
                               scheme=_scheme_key(color_scheme), mode=class_mode, figsize=(15, 15))
        path = _named_path(_map_stem(col, time, map_level_state), ".png")
        fig.savefig(path, dpi=200, bbox_inches='tight', facecolor='white')
        return gr.update(value=path, visible=True)
    except Exception as e:
        raise gr.Error(f"PNG 匯出失敗: {e}")

def auto_render_map(df, all_cols, map_level_state):
    """
    上傳成功後自動畫第一張地圖。這裡不讀畫面上的下拉選單:
    .then() 觸發時選單的新值還沒回傳,會讀到舊值/None,所以直接用與預設選項相同的值。
    失敗就靜默略過,不打斷上傳流程。
    """
    if df is None or not all_cols: return gr.update()
    try:
        latest = sorted(df['time_parsed'].unique())[-1] if 'time_parsed' in df.columns else "全部"
        fig, _ = generate_map(df, all_cols[0], latest, default_agg(all_cols[0]), "紅色系 🔴", CLASS_MODES[0], True,
                              map_level_state, all_cols)
        return fig
    except Exception:
        return gr.update()

def export_html_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):
    fig, _ = generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols)
    path = _named_path(_map_stem(_resolve_col(col, all_cols), time, map_level_state, "(互動)"), ".html")
    fig.write_html(path, include_plotlyjs="cdn")
    return gr.update(value=path, visible=True)

def export_csv(df):
    _require_df(df)
    path = _named_path("統計資料(已辨識)", ".csv")
    df.to_csv(path, index=False, encoding="utf-8-sig")
    return gr.update(value=path, visible=True)

def generate_trend_chart(df, col, selected_region, line_metric, all_cols):
    _require_df(df)
    col = _resolve_col(col, all_cols)
    if 'time_parsed' not in df.columns: raise gr.Error("資料中未偵測到時間欄位,無法做趨勢分析")
    if not line_metric: line_metric = "3年移動平均"

    # 支援多選:selected_region 可能是字串或清單
    if isinstance(selected_region, str): selected_region = [selected_region]
    regions = [r for r in (selected_region or []) if r] or ["全國總計"]
    if 'region_normalized' not in df.columns: regions = ["全國總計"]

    try:
        trend_df = df.copy()
        trend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)

        try: trend_df['time_sort'] = pd.to_numeric(trend_df['time_parsed'])
        except (ValueError, TypeError): trend_df['time_sort'] = trend_df['time_parsed']

        common_layout = dict(
            legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.5, bgcolor='rgba(255,255,255,0.8)'),
            hovermode="x unified", height=500, plot_bgcolor='rgba(250,250,250,0.5)', paper_bgcolor='white',
            margin=dict(l=60, r=60, t=100, b=80)
        )

        # 多地區比較模式:每個地區一條線
        if len(regions) > 1:
            fig = go.Figure()
            for r in regions:
                sub = trend_df if r == "全國總計" else trend_df[trend_df['region_normalized'] == r]
                g = sub.groupby('time_sort')[col].agg(AGG_FUNCS[default_agg(col)]).reset_index().sort_values('time_sort')
                fig.add_trace(go.Scatter(
                    x=g['time_sort'].astype(str), y=g[col], name=r,
                    mode='lines+markers', marker=dict(size=7), line=dict(width=3),
                    hovertemplate='<b>%{x}</b><br>' + r + ': %{y:,.0f}<extra></extra>'
                ))
            fig.update_xaxes(title_text="時間", tickangle=-45, type='category', showgrid=True, gridcolor='rgba(200,200,200,0.2)')
            fig.update_yaxes(title_text=col, showgrid=True, gridcolor='rgba(200,200,200,0.2)')
            fig.update_layout(title=dict(text=f"📈 {col} - 多地區趨勢比較({'、'.join(regions)})", font=dict(size=20, color='#1f2937')),
                              **common_layout)
            return fig, gr.Tabs(selected="tab_trend")

        title_suffix = regions[0]
        if title_suffix != "全國總計":
            trend_df = trend_df[trend_df['region_normalized'] == title_suffix]

        grouped = trend_df.groupby('time_sort')[col].agg(AGG_FUNCS[default_agg(col)]).reset_index().sort_values('time_sort')
        x_data = grouped['time_sort'].astype(str)

        fig = make_subplots(specs=[[{"secondary_y": True}]])
        fig.add_trace(
            go.Bar(x=x_data, y=grouped[col], name=f"{col} (數量)", marker_color='rgb(99, 102, 241)', opacity=0.7,
                   hovertemplate='<b>%{x}</b><br>數量: %{y:,.0f}<extra></extra>'),
            secondary_y=False
        )

        if line_metric == "年增率 (%)":
            line_data = grouped[col].pct_change() * 100
            fig.add_trace(
                go.Scatter(x=x_data, y=line_data.tolist(), name="年增率 (%)", mode='lines+markers',
                           marker=dict(size=8, color='rgb(239, 68, 68)', symbol='circle'), line=dict(width=3),
                           hovertemplate='<b>%{x}</b><br>年增率: %{y:.2f}%<extra></extra>'),
                secondary_y=True
            )
            fig.update_yaxes(title_text="年增率 (%)", secondary_y=True, showgrid=False)
        elif line_metric == "3年移動平均":
            # min_periods=3:資料不足 3 期時不顯示誤導性數據
            line_data = grouped[col].rolling(window=3, min_periods=3).mean()
            fig.add_trace(
                go.Scatter(x=x_data, y=line_data.tolist(), name="3年移動平均", mode='lines+markers',
                           marker=dict(size=8, color='rgb(239, 68, 68)', symbol='diamond'), line=dict(width=3, dash='dash'),
                           hovertemplate='<b>%{x}</b><br>3年平均: %{y:,.1f}<extra></extra>'),
                secondary_y=False
            )

        fig.update_xaxes(title_text="時間", tickangle=-45, type='category', showgrid=True, gridcolor='rgba(200,200,200,0.2)')
        fig.update_yaxes(title_text=col, secondary_y=False, showgrid=True, gridcolor='rgba(200,200,200,0.2)')
        if title_suffix == "全國總計" and is_rate_col(col): title_suffix = "全國平均"
        fig.update_layout(title=dict(text=f"📈 {col} - 歷史趨勢分析 ({title_suffix})", font=dict(size=20, color='#1f2937')),
                          **common_layout)
        return fig, gr.Tabs(selected="tab_trend")
    except Exception as e:
        import traceback; traceback.print_exc()
        raise gr.Error(f"趨勢圖產生失敗: {e}")

def generate_map_gif(df, col, color_scheme, class_mode, fps, start_t, end_t, sort_order, show_islands,
                     map_level_state, all_cols, progress=gr.Progress()):
    _require_regions(df)
    target_gdf = _require_map(map_level_state)
    col = _resolve_col(col, all_cols)
    if 'time_parsed' not in df.columns: raise gr.Error("資料中未偵測到時間欄位,無法產生動畫")
    if not show_islands:
        target_gdf = target_gdf[~target_gdf['name'].str.startswith(ISLAND_COUNTIES)]

    try:
        plot_df = df.copy()
        plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce')
        times = plot_df['time_parsed'].unique()
        try: all_times = sorted(times, key=float)
        except (ValueError, TypeError): all_times = sorted(times)

        idx_start = all_times.index(str(start_t)) if str(start_t) in all_times else 0
        idx_end = all_times.index(str(end_t)) if str(end_t) in all_times else len(all_times) - 1
        if idx_start > idx_end: idx_start, idx_end = idx_end, idx_start
        selected_times = all_times[idx_start: idx_end + 1]
        if sort_order == "時間反序 (新 → 舊)": selected_times.reverse()
        if len(selected_times) < 2: raise gr.Error("時間點過少,至少需要 2 個時間點")

        agg_all = plot_df.groupby(['time_parsed', 'region_normalized'])[col].sum().reset_index()
        in_range = agg_all[agg_all['time_parsed'].isin(selected_times)][col]
        # 所選時段共用同一組色階/級距,各幀才能互相比較
        edges = class_edges(in_range, class_mode)
        vrange = (in_range.min(), in_range.max())
        scheme = _scheme_key(color_scheme)

        frames = []
        for t in progress.tqdm(selected_times, desc="繪製動畫圖框"):
            merged = merge_geo(target_gdf, agg_all[agg_all['time_parsed'] == t])
            fig = build_static_map(merged, col, f"{col} - {t}", scheme=scheme, mode=class_mode, figsize=(8, 8),
                                   edges=edges, vrange=vrange, title_size=20, legend_size=10)
            buf = io.BytesIO()
            fig.savefig(buf, format='png', dpi=100, facecolor='white')  # 不用 tight,避免各幀尺寸不一造成抖動
            buf.seek(0)
            frames.append(Image.open(buf).convert('RGB'))
        span = f"{selected_times[0]}-{selected_times[-1]}"
        path = _named_path(_map_stem(col, None, map_level_state, f"_動畫_{span}"), ".gif")
        frames[0].save(path, save_all=True, append_images=frames[1:], optimize=False, duration=int(1000 / fps), loop=0)
        return path, gr.Tabs(selected="tab_gif")
    except gr.Error:
        raise
    except Exception as e:
        raise gr.Error(f"GIF 產生失敗: {e}")

# ===============================================
# 6. 手動填寫分布圖
# ===============================================

DEFAULT_COUNTIES = [
    "基隆市", "臺北市", "新北市", "桃園市", "新竹市", "新竹縣", "苗栗縣", "臺中市",
    "彰化縣", "南投縣", "雲林縣", "嘉義市", "嘉義縣", "臺南市", "高雄市", "屏東縣",
    "宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"
]

MANUAL_LEVELS = ["縣市", "鄉鎮市區"]
MANUAL_NATIONAL = "全國"

MANUAL_LABEL_MODES = ["名稱 + 內容", "僅內容", "僅名稱", "不顯示標籤"]
MANUAL_COLORS = ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"]
MANUAL_COL_NAME, MANUAL_COL_CONTENT = "名稱", "填寫內容"
# 分類模式的調色盤(Set2 + Set3,約 20 色,超過會循環)
QUALITATIVE_COLORS = [_to_hex(c) for c in px.colors.qualitative.Set2 + px.colors.qualitative.Set3]
UNFILLED_LABEL = "未填寫"

# 面積小又擠在一起的縣市,標籤移到海上(經度, 緯度)並以引線連回區域(只用於縣市層級)
LABEL_OFFSETS = {
    "基隆市": (122.45, 25.40), "臺北市": (122.55, 25.10), "新北市": (122.55, 24.80),
    "桃園市": (120.30, 25.15), "新竹市": (120.15, 24.80), "嘉義市": (119.90, 23.55),
}

MANUAL_EXAMPLES = {
    "分區": {"臺北市": "北部", "新北市": "北部", "基隆市": "北部", "桃園市": "北部", "新竹市": "北部", "新竹縣": "北部",
           "苗栗縣": "中部", "臺中市": "中部", "彰化縣": "中部", "南投縣": "中部", "雲林縣": "中部",
           "嘉義市": "南部", "嘉義縣": "南部", "臺南市": "南部", "高雄市": "南部", "屏東縣": "南部",
           "宜蘭縣": "東部", "花蓮縣": "東部", "臺東縣": "東部",
           "澎湖縣": "離島", "金門縣": "離島", "連江縣": "離島"},
    "數值": {c: str(v) for c, v in zip(DEFAULT_COUNTIES, [12, 85, 60, 45, 18, 20, 22, 70, 30, 14, 16,
                                                          9, 11, 48, 66, 21, 13, 10, 7, 3, 4, 1])},
}

# --- 名稱清單與資料表 ---

def _town_gdf():
    gdf = get_gdf("town")
    if gdf is None or gdf.empty or '縣市' not in gdf.columns: raise gr.Error("鄉鎮市區圖資載入失敗")
    return gdf

def manual_names(level: str, scope: str) -> List[str]:
    """目前表格要列出的名稱:縣市層級=22 縣市;鄉鎮層級=全國或某縣市底下的鄉鎮市區"""
    if level != "鄉鎮市區": return list(DEFAULT_COUNTIES)
    gdf = _town_gdf()
    if scope in DEFAULT_COUNTIES: gdf = gdf[gdf['縣市'] == scope]
    order = {c: i for i, c in enumerate(DEFAULT_COUNTIES)}
    sort_cols = ['town_id'] if 'town_id' in gdf.columns else ['name']
    gdf = gdf.assign(_o=gdf['縣市'].map(order)).sort_values(['_o'] + sort_cols)
    return gdf['name'].tolist()

def all_manual_names(level: str) -> List[str]:
    return manual_names(level, MANUAL_NATIONAL)

def manual_table(level: str, scope: str, store: Optional[Dict[str, str]]) -> pd.DataFrame:
    names = manual_names(level, scope)
    store = store or {}
    return pd.DataFrame({MANUAL_COL_NAME: names, MANUAL_COL_CONTENT: [store.get(n, "") for n in names]})


def on_manual_table_input(df, store):
    """使用者在表格輸入時,同步到 store(以名稱為鍵;清空內容就從 store 移除)"""
    store = dict(store or {})
    if df is None: return store
    for name, content in zip(df[MANUAL_COL_NAME], df[MANUAL_COL_CONTENT]):
        name = str(name).strip()
        content = "" if content is None or (isinstance(content, float) and pd.isna(content)) else str(content).strip()
        if not name or name == "nan": continue
        if content: store[name] = content
        else: store.pop(name, None)
    return store

def merge_table_into_store(df, store):
    """只「加入/更新」表格裡有內容的列,不刪除。匯出時用:表格的值可能還沒回傳到後端(例如剛載入範例),
    此時拿到的是舊表格,不能讓它把 store 裡的資料清掉;真正的刪除已由表格的 input 事件同步。"""
    store = dict(store or {})
    if df is None: return store
    for name, content in zip(df[MANUAL_COL_NAME], df[MANUAL_COL_CONTENT]):
        name = str(name).strip()
        content = "" if content is None or (isinstance(content, float) and pd.isna(content)) else str(content).strip()
        if name and name != "nan" and content: store[name] = content
    return store

def clear_manual(level, scope, store):
    store = dict(store or {})
    for n in manual_names(level, scope): store.pop(n, None)
    return store, manual_table(level, scope, store)

def load_manual_example(kind: str, store):
    store = {k: v for k, v in (store or {}).items() if k not in DEFAULT_COUNTIES}
    store.update(MANUAL_EXAMPLES[kind])
    return store, gr.update(value="縣市"), gr.update(), manual_table("縣市", MANUAL_NATIONAL, store)

TOWN_EXAMPLE_COUNTIES = ["臺北市", "新北市"]

def load_town_example(kind: str, store):
    """
    鄉鎮層級的示範資料(臺北市+新北市共 41 區,數值為示範用的假資料,不是真實統計)。
    切到鄉鎮市區、範圍選新北市;匯出 PPTX 會得到臺北市、新北市兩頁,可用來預覽版面。
    """
    names = [n for c in TOWN_EXAMPLE_COUNTIES for n in manual_names("鄉鎮市區", c)]
    town_names = set(all_manual_names("鄉鎮市區"))
    store = {k: v for k, v in (store or {}).items() if k not in town_names}
    for i, name in enumerate(names):
        store[name] = f"{(i * 37) % 90 * 100 + 1000:,}" if kind == "數值" else ["甲類", "乙類", "丙類"][i % 3]
    scope = TOWN_EXAMPLE_COUNTIES[-1]
    return (store, gr.update(value="鄉鎮市區"), gr.update(value=scope),
            manual_table("鄉鎮市區", scope, store))

def _resolver(level: str, scope: str):
    """把使用者輸入的名稱對到標準名稱:容許「台北市」、舊名、以及在單一縣市範圍內只寫鄉鎮名(板橋區)"""
    names = set(all_manual_names(level))
    short: Dict[str, List[str]] = {}
    if level == "鄉鎮市區":
        gdf = _town_gdf()
        for full, county in zip(gdf['name'], gdf['縣市']):
            short.setdefault(full[len(county):], []).append(full)
    def resolve(raw: str) -> Optional[str]:
        n = normalize_name(raw)
        if n in names: return n
        if level == "鄉鎮市區":
            if scope in DEFAULT_COUNTIES and scope + n in names: return scope + n
            cands = short.get(n, [])
            if len(cands) == 1: return cands[0]   # 全國範圍下,名稱唯一的鄉鎮可以只寫短名
        return None
    return resolve

def import_pasted_text(text: str, level, scope, store):
    """
    批次貼上:每行「名稱 內容」,分隔可用 Tab(從 Excel 複製)、逗號、冒號、等號或空白。
    同名會覆蓋;認不得的名稱用警告列出。不在目前範圍的鄉鎮也會存起來,切換範圍就看得到。
    """
    store = dict(store or {})
    resolve = _resolver(level, scope)
    unknown, got = [], 0
    for line in (text or "").splitlines():
        line = line.strip()
        if not line: continue
        parts = re.split(r"[\t,,::=]+|\s+", line, maxsplit=1)
        if len(parts) < 2 or not parts[1].strip(): continue
        name = resolve(parts[0])
        if name: store[name] = parts[1].strip(); got += 1
        else: unknown.append(parts[0])
    if not got and not unknown:
        raise gr.Error("沒有讀到資料:每行請寫成「名稱 內容」,例如「臺北市 85」")
    if unknown: gr.Warning(f"以下名稱對不到{level},已略過:{'、'.join(unknown[:8])}")
    return store, manual_table(level, scope, store)

# --- 資料合併與繪圖 ---

_COUNTY_OUTLINE_CACHE: Dict[Tuple[str, ...], Tuple[list, list]] = {}

def county_outline_lines(counties: Tuple[str, ...] = ()) -> Tuple[list, list]:
    """縣市界線的座標(以 None 分段),疊在鄉鎮圖上才看得出縣市邊界;counties 空=全部縣市"""
    if counties not in _COUNTY_OUTLINE_CACHE:
        gdf = _require_map("county")
        if counties: gdf = gdf[gdf['name'].isin(counties)]
        lon, lat = [], []
        for geom in gdf.geometry.boundary:
            for line in getattr(geom, "geoms", [geom]):
                xs, ys = line.xy
                lon += list(xs) + [None]; lat += list(ys) + [None]
        _COUNTY_OUTLINE_CACHE[counties] = (lon, lat)
    return _COUNTY_OUTLINE_CACHE[counties]

def _manual_frame(input_df, level, scope, show_islands=True, numeric=None):
    """
    把表格合併到地圖,回傳 (merged, is_numeric)。
    merged 欄位:label_name、填寫內容、filled、數值(數值模式)、類別(分類模式)。
    全部填寫內容都是數字 → 數值模式(漸層色階);否則 → 分類模式(相同文字同色+圖例)。
    """
    if level == "鄉鎮市區":
        target = _town_gdf()
        if scope in DEFAULT_COUNTIES: target = target[target['縣市'] == scope]
    else:
        target = _require_map("county")
    if input_df is None or len(input_df) == 0: raise gr.Error("請至少填寫一個項目的內容")
    data = input_df.copy()
    data[MANUAL_COL_NAME] = data[MANUAL_COL_NAME].astype(str).map(normalize_name)
    data[MANUAL_COL_CONTENT] = data[MANUAL_COL_CONTENT].fillna("").astype(str).str.strip()
    valid = data[data[MANUAL_COL_CONTENT] != ""].drop_duplicates(MANUAL_COL_NAME, keep="last")
    if valid.empty: raise gr.Error("請至少填寫一個項目的內容")

    unknown = sorted(set(valid[MANUAL_COL_NAME]) - set(target["name"]))
    if unknown: gr.Warning(f"找不到這些地區,已略過:{'、'.join(unknown[:8])}")

    if not show_islands:
        target = target[~target["name"].str.startswith(ISLAND_COUNTIES)]
    merged = target.merge(valid, left_on="name", right_on=MANUAL_COL_NAME, how="left")
    merged[MANUAL_COL_CONTENT] = merged[MANUAL_COL_CONTENT].fillna("")
    merged["filled"] = merged[MANUAL_COL_CONTENT] != ""
    # 鄉鎮層級的標籤只顯示鄉鎮名(板橋區),不帶縣市前綴
    merged["label_name"] = merged["name"] if level != "鄉鎮市區" else [
        n[len(c):] for n, c in zip(merged["name"], merged["縣市"])]

    numbers = pd.to_numeric(merged.loc[merged["filled"], MANUAL_COL_CONTENT].str.replace(",", "", regex=False),
                            errors="coerce")
    is_numeric = bool(numbers.notna().all()) if numeric is None else numeric
    if is_numeric:
        merged["數值"] = np.nan
        merged.loc[merged["filled"], "數值"] = numbers
    else:
        merged["類別"] = np.where(merged["filled"], merged[MANUAL_COL_CONTENT], UNFILLED_LABEL)
    return merged, is_numeric

def _category_palette(merged, cats=None) -> Tuple[List[str], Dict[str, str]]:
    if cats is None:
        cats = list(dict.fromkeys(merged.loc[merged["filled"], "類別"]))  # 依出現順序,顏色才穩定
    palette = {c: QUALITATIVE_COLORS[i % len(QUALITATIVE_COLORS)] for i, c in enumerate(cats)}
    palette[UNFILLED_LABEL] = NO_DATA_COLOR
    return cats, palette

LABEL_SPREAD_MAX = 80   # 標籤超過這個數量(例如全國 375 鄉鎮)就不做互斥,太慢也擠不開

LABEL_PAD = (1.6, 1.3)        # 排版用的外框內距(字級倍數):放寬,標籤之間才留得出空隙
LABEL_DRAW_PAD = (0.9, 0.7)   # 畫出來的外框內距:貼近文字

def _text_box_units(text: str, fs: float) -> Tuple[float, float]:
    """估計標籤外框大小(與字級同單位):全形字寬 ≈ 字級,數字/英文 ≈ 0.56 倍,再加內距。"""
    lines = text.split("\n")
    width = max(sum(fs if ord(ch) > 0x2E7F else fs * 0.56 for ch in line) for line in lines)
    return width + fs * LABEL_PAD[0], len(lines) * fs * 1.25 + fs * LABEL_PAD[1]

def spread_labels(anchors, texts, fs, kx, ky, init=None, iters=300):
    """
    標籤互斥:把每個標籤當成矩形,重疊的兩個沿重疊較少的方向互相推開,並以微弱彈力拉回各自的區域,
    直到沒有重疊。回傳 [(中心座標, (寬, 高))](單位:度)。
    kx、ky = 畫面上每個字級單位(pt 或 px)相當於幾度經度/緯度,用來把外框換算成經緯度。
    """
    n = len(anchors)
    sizes = [(_text_box_units(t, fs)[0] * kx, _text_box_units(t, fs)[1] * ky) for t in texts]
    pos = [list(init[i]) if init and init[i] else list(anchors[i]) for i in range(n)]
    if n <= LABEL_SPREAD_MAX:
        for _ in range(iters):
            moved = False
            for i in range(n):
                for j in range(i + 1, n):
                    dx, dy = pos[j][0] - pos[i][0], pos[j][1] - pos[i][1]
                    ox = (sizes[i][0] + sizes[j][0]) / 2 - abs(dx)
                    oy = (sizes[i][1] + sizes[j][1]) / 2 - abs(dy)
                    if ox <= 0 or oy <= 0: continue
                    moved = True
                    axis = 0 if ox < oy else 1          # 沿重疊少的方向推
                    d = (dx, dy)[axis]
                    sign = 1 if d > 0 else -1 if d < 0 else (1 if j > i else -1)
                    push = (ox, oy)[axis] / 2 * 1.05
                    pos[i][axis] -= sign * push
                    pos[j][axis] += sign * push
            if not moved: break
            for i in range(n):                         # 彈力:不要飄太遠
                pos[i][0] += 0.04 * (anchors[i][0] - pos[i][0])
                pos[i][1] += 0.04 * (anchors[i][1] - pos[i][1])
    return [((pos[i][0], pos[i][1]), sizes[i]) for i in range(n)]

def _clip_to_box(anchor, center, size):
    """引線終點:從中心朝錨點方向,走到外框邊緣為止"""
    dx, dy = anchor[0] - center[0], anchor[1] - center[1]
    if dx == 0 and dy == 0: return center
    t = min((size[0] / 2) / abs(dx) if dx else float("inf"), (size[1] / 2) / abs(dy) if dy else float("inf"), 1.0)
    return (center[0] + dx * t, center[1] + dy * t)

def _place_labels(merged, level, label_mode, fs, kx, ky):
    """
    算出每個已填區域的標籤位置。回傳 list of dict:text、anchor(區域內的點)、pos(標籤中心)、
    edge(引線接到外框的點,沒有引線則為 None)。
    representative_point 保證錨點落在區域內(centroid 可能落在海上)。
    """
    filled = merged[merged["filled"]]
    if filled.empty: return []
    pts = filled.geometry.representative_point()
    anchors = [(pt.x, pt.y) for pt in pts]
    texts = [_label_text(n, c, label_mode) for n, c in zip(filled["label_name"], filled[MANUAL_COL_CONTENT])]
    init = [LABEL_OFFSETS.get(n) if level != "鄉鎮市區" else None for n in filled["name"]]
    laid = spread_labels(anchors, texts, fs, kx, ky, init=init)
    out = []
    ex, ey = (LABEL_PAD[0] - LABEL_DRAW_PAD[0]) * fs * kx, (LABEL_PAD[1] - LABEL_DRAW_PAD[1]) * fs * ky
    for text, anchor, (pos, size) in zip(texts, anchors, laid):
        tight = (size[0] - ex, size[1] - ey)            # 實際畫出來的外框
        inside = abs(anchor[0] - pos[0]) <= tight[0] / 2 and abs(anchor[1] - pos[1]) <= tight[1] / 2
        out.append({"text": text, "anchor": anchor, "pos": pos, "w": tight[0], "h": tight[1],
                    "edge": None if inside else _clip_to_box(anchor, pos, tight)})
    return out

def _label_text(name: str, content: str, mode: str) -> str:
    if mode == "僅內容": return content
    if mode == "僅名稱": return name
    return f"{name}\n{content}"

def _manual_file_stem(title: str, level: str, scope: str) -> str:
    """有填標題就用標題;沒填就用「縣市統計圖」「新北市鄉鎮市區統計圖」"""
    if (title or "").strip(): return title.strip()
    if level != "鄉鎮市區": return "縣市統計圖"
    return "全國鄉鎮市區統計圖" if scope not in DEFAULT_COUNTIES else f"{scope}鄉鎮市區統計圖"

def _manual_title(title: str, level: str, scope: str) -> str:
    if (title or "").strip(): return title.strip()
    if level != "鄉鎮市區": return "臺灣各縣市"
    return "全國各鄉鎮市區" if scope not in DEFAULT_COUNTIES else f"{scope}各鄉鎮市區"

def generate_manual_distribution_map(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands):
    merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)
    title = _manual_title(title, level, scope)
    scheme = _scheme_key(color_scheme)

    if is_numeric:
        fig = build_choropleth(merged, "數值", title, scheme=scheme, hover_data={"數值": ":,.2f"})
    else:
        cats, palette = _category_palette(merged)
        fig = px.choropleth(
            merged, geojson=merged.geometry, locations=merged.index, color="類別",
            color_discrete_map=palette,
            category_orders={"類別": cats + ([UNFILLED_LABEL] if (~merged["filled"]).any() else [])},
            projection="mercator", hover_name="name", hover_data={"類別": False}
        )
        _style_map_layout(fig, title, bottom_legend=True, merged=merged)
        _add_county_outline(fig, merged)   # 數值模式由 build_choropleth 疊縣市界

    filled = merged[merged["filled"]]
    if label_mode != "不顯示標籤" and not filled.empty:
        # 互動圖高 800px;地圖最長邊在一般視窗約佔 640px(視窗寬窄會有些出入)
        xmin, ymin, xmax, ymax = merged.total_bounds
        k = max(xmax - xmin, ymax - ymin, 1e-6) / 640
        placed = _place_labels(merged, level, label_mode, int(label_size), k, k)
        moved = [lab for lab in placed if lab["edge"]]
        if moved:
            lon, lat = [], []
            for lab in moved:
                lon += [lab["anchor"][0], lab["edge"][0], None]; lat += [lab["anchor"][1], lab["edge"][1], None]
            fig.add_trace(go.Scattergeo(lon=lon, lat=lat, mode="lines", hoverinfo="skip", showlegend=False,
                                        line=dict(color="#6b7280", width=1)))
            fig.add_trace(go.Scattergeo(lon=[lab["anchor"][0] for lab in moved], lat=[lab["anchor"][1] for lab in moved],
                                        mode="markers", hoverinfo="skip", showlegend=False,
                                        marker=dict(size=4, color="#374151")))
        # 白底外框(與匯出圖一致),文字不會再和深色區域糊在一起
        bx, by = [], []
        for lab in placed:
            (cx, cy), hw, hh = lab["pos"], lab["w"] / 2, lab["h"] / 2
            # 順時針(d3 地理座標的外環方向);逆時針會被當成「整個地球扣掉這個框」,把地圖蓋成一片白
            bx += [cx - hw, cx - hw, cx + hw, cx + hw, cx - hw, None]
            by += [cy - hh, cy + hh, cy + hh, cy - hh, cy - hh, None]
        fig.add_trace(go.Scattergeo(lon=bx, lat=by, mode="lines", fill="toself", fillcolor="rgba(255,255,255,0.92)",
                                    line=dict(color="#6b7280", width=1), hoverinfo="skip", showlegend=False))
        fig.add_trace(go.Scattergeo(
            lon=[lab["pos"][0] for lab in placed], lat=[lab["pos"][1] for lab in placed],
            text=[lab["text"].replace("\n", "<br>") for lab in placed], mode="text",
            textfont=dict(color="black", size=int(label_size), family="Microsoft JhengHei, Noto Sans TC, sans-serif"),
            hoverinfo="skip", showlegend=False
        ))
    fig.update_layout(height=800)
    return fig

def _render_manual_static(merged, is_numeric, level, scope, title, scheme, label_mode, label_size,
                          vrange=None, cats=None, figsize=(12, 12), scene=None):
    """靜態圖 (matplotlib)。PPTX 每頁共用 vrange(數值)或 cats(分類),各頁顏色才能互相比較。
    傳入 scene(dict)時,另外把地圖區塊、標籤、圖例收集起來,供匯出可編輯的原生 PPTX 使用。"""
    if is_numeric:
        # 縣市層級的離島外標籤會往右伸出,色條要往右讓開才不會蓋住
        fig = build_static_map(merged, "數值", title, scheme=scheme, figsize=figsize, vrange=vrange,
                               cbar_pad=0.16 if level != "鄉鎮市區" else 0.05)
        ax = fig.axes[0]
    else:
        fig = Figure(figsize=figsize)
        ax = fig.subplots()
        cats, palette = _category_palette(merged, cats)
        for cat in cats + [UNFILLED_LABEL]:
            sub = merged[merged["類別"] == cat]
            if not sub.empty: sub.plot(ax=ax, color=palette[cat], edgecolor=_edge_style(merged)[0], linewidth=_edge_style(merged)[1])
        handles = [Patch(facecolor=palette[c], edgecolor="0.5", label=c) for c in cats]
        if handles: ax.legend(handles=handles, loc="lower right", fontsize=12)
        _plot_county_outline(ax, merged)   # 數值模式由 build_static_map 疊縣市界
        font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}
        ax.set_title(title, size=24, **font_kw)
        _style_map_ax(ax)

    ax.apply_aspect()
    fs = int(label_size) * 0.85
    placed = []
    if label_mode != "不顯示標籤":
        font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}
        # 量出座標軸實際大小,換算「每 pt 幾度」(色條、圖例都會影響軸的大小,不能用估的)
        pos = ax.get_position()
        (x0, x1), (y0, y1) = ax.get_xlim(), ax.get_ylim()
        kx = (x1 - x0) / (pos.width * fig.get_figwidth() * 72)
        ky = (y1 - y0) / (pos.height * fig.get_figheight() * 72)
        placed = _place_labels(merged, level, label_mode, fs, kx, ky)
        for lab in placed:
            ax.annotate(
                lab["text"], xy=lab["anchor"], xytext=lab["pos"], ha="center", va="center", fontsize=fs, **font_kw,
                bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.92),
                arrowprops=dict(arrowstyle="-", color="#6b7280", linewidth=0.9, shrinkA=0, shrinkB=0) if lab["edge"] else None
            )
            if lab["edge"]:
                ax.plot(*lab["anchor"], "o", ms=2.5, color="#374151", zorder=5)
    if scene is not None:
        if is_numeric:
            vals = merged["數值"]
            lo, hi = vrange if vrange else (float(vals.min()), float(vals.max()))
            cmap = mpl.colormaps[MPL_CMAPS[scheme]]
            color_of = lambda row: (NO_DATA_COLOR if pd.isna(row["數值"]) else
                                    mpl.colors.to_hex(cmap((row["數值"] - lo) / (hi - lo) if hi > lo else 1.0)))
            legend = {"kind": "num", "lo": lo, "hi": hi, "cmap": cmap}
        else:
            cat_list, pal = _category_palette(merged, cats)
            color_of = lambda row: pal[row["類別"]]
            legend = {"kind": "cat", "items": [(c, pal[c]) for c in cat_list]}
        scene.update(
            xf=lambda a: ax.transData.transform(np.asarray(a, dtype=float)) / fig.dpi,
            regions=[(r["name"], r.geometry, color_of(r)) for _, r in merged.iterrows()],
            labels=placed, legend=legend, fs=fs)
    return fig

def regenerate_manual_map(*args):
    """改了顯示選項(離島、標籤、配色)就自動重畫;表格還沒填東西時靜默略過,不跳錯誤訊息"""
    try:
        return generate_manual_distribution_map(*args)
    except gr.Error:
        return gr.update()

def _checkerboard_preview(png_path: str) -> str:
    """把透明背景的 PNG 合成到棋盤格上,才看得出哪裡是透明的"""
    from PIL import Image as PILImage
    img = PILImage.open(png_path).convert("RGBA")
    board = PILImage.new("RGBA", img.size, "#ffffff")
    cell = 16
    dark = PILImage.new("RGBA", (cell, cell), "#d1d5db")
    for y in range(0, img.size[1], cell):
        for x in range(0, img.size[0], cell):
            if (x // cell + y // cell) % 2: board.paste(dark, (x, y))
    out = _tmp_path(".png")
    PILImage.alpha_composite(board, img).convert("RGB").save(out)
    return out

def export_manual_with_preview(*args, fmt="png"):
    """匯出檔案;PNG 另外給一張預覽(透明背景以棋盤格顯示),讓「透明背景」勾選有看得到的回饋"""
    file_update = export_manual(*args, fmt=fmt)
    if fmt != "png": return file_update, gr.update(visible=False)
    path, transparent = file_update["value"], bool(args[-1])
    return file_update, gr.update(value=_checkerboard_preview(path) if transparent else path, visible=True)

def export_manual(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands,
                  transparent=False, fmt="png"):
    """匯出 PNG/SVG(可透明背景,貼到簡報不留白底);顏色、標籤與畫面上的互動圖一致"""
    merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)
    fig = _render_manual_static(merged, is_numeric, level, scope, _manual_title(title, level, scope),
                                _scheme_key(color_scheme), label_mode, label_size)
    path = _named_path(_manual_file_stem(title, level, scope), f".{fmt}")
    fig.savefig(path, format=fmt, bbox_inches="tight", dpi=200,
                transparent=bool(transparent), facecolor="none" if transparent else "white")
    return gr.update(value=path, visible=True)

# --- PPTX:一頁一個縣市 ---

PPT_FONT = "Microsoft JhengHei"
PPT_TABLE_MAX_ROWS = 22

# --- 原生 PowerPoint 物件:文字方塊、圖形、向量地圖,匯出後都能在 PowerPoint 裡直接編輯 ---

def _emu(inches: float) -> int:
    return int(round(inches * 914400))

def _pp_rgb(hex_str: str):
    from pptx.dml.color import RGBColor
    return RGBColor.from_string(hex_str.lstrip("#").upper())

def _pp_fill_text(tf, lines, size, bold=False, color="#111827", align="c", anchor="m", margins=(0, 0, 0, 0), wrap=False):
    """把文字寫進 text_frame(每行一個段落)。align: l/c/r;anchor: t/m/b;margins 為英吋 (左, 上, 右, 下)。
    wrap=True 時交給 PowerPoint 自動換行(字寬估算略偏時會自己折,不會衝出框外)。"""
    from pptx.util import Pt, Inches
    from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
    tf.word_wrap = bool(wrap)
    tf.margin_left, tf.margin_top, tf.margin_right, tf.margin_bottom = (Inches(m) for m in margins)
    tf.vertical_anchor = {"t": MSO_ANCHOR.TOP, "m": MSO_ANCHOR.MIDDLE, "b": MSO_ANCHOR.BOTTOM}[anchor]
    lines = [lines] if isinstance(lines, str) else list(lines)
    for i, line in enumerate(lines):
        para = tf.paragraphs[0] if i == 0 else tf.add_paragraph()
        para.alignment = {"l": PP_ALIGN.LEFT, "c": PP_ALIGN.CENTER, "r": PP_ALIGN.RIGHT}[align]
        run = para.add_run()
        run.text = line
        run.font.size, run.font.bold, run.font.name = Pt(size), bold, PPT_FONT
        run.font.color.rgb = _pp_rgb(color)

def _pp_text(shapes, x, y, w, h, lines, size, bold=False, color="#111827", align="c", anchor="m", name=None, wrap=False):
    from pptx.util import Inches
    tb = shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    if name: tb.name = name
    _pp_fill_text(tb.text_frame, lines, size, bold, color, align, anchor, wrap=wrap)
    return tb

def _pp_shape(shapes, kind, x, y, w, h, fill=None, line=None, line_pt=1.0, name=None, radius=0.5):
    """kind: rect / round / oval。round 的 radius=0.5 就是膠囊形。"""
    from pptx.util import Inches, Pt
    from pptx.enum.shapes import MSO_SHAPE
    shp = shapes.add_shape({"rect": MSO_SHAPE.RECTANGLE, "round": MSO_SHAPE.ROUNDED_RECTANGLE,
                            "oval": MSO_SHAPE.OVAL}[kind], Inches(x), Inches(y), Inches(w), Inches(h))
    if kind == "round": shp.adjustments[0] = radius
    if fill: shp.fill.solid(); shp.fill.fore_color.rgb = _pp_rgb(fill)
    else: shp.fill.background()
    if line: shp.line.color.rgb = _pp_rgb(line); shp.line.width = Pt(line_pt)
    else: shp.line.fill.background()
    shp.shadow.inherit = False
    if name: shp.name = name
    return shp

def _pp_line(shapes, p1, p2, color="#8a8f98", width_pt=0.9):
    from pptx.util import Inches, Pt
    from pptx.enum.shapes import MSO_CONNECTOR
    conn = shapes.add_connector(MSO_CONNECTOR.STRAIGHT, Inches(p1[0]), Inches(p1[1]), Inches(p2[0]), Inches(p2[1]))
    conn.line.color.rgb = _pp_rgb(color)
    conn.line.width = Pt(width_pt)
    return conn

def _pp_polygon(shapes, geom, to_slide, fill, line="#ffffff", line_pt=0.75, name=None):
    """shapely 多邊形 → PowerPoint 自由形狀(向量,可在 PowerPoint 裡換色、編輯節點)。
    to_slide:(n,2) 座標 → 投影片英吋座標(y 向下)。外環與內環(洞)方向相反,才會正確挖洞。"""
    from pptx.util import Pt
    from shapely.geometry.polygon import orient
    rings = []
    for poly in getattr(geom, "geoms", [geom]):
        if poly.geom_type != "Polygon" or poly.is_empty: continue
        poly = orient(poly, 1.0)
        for ring in [poly.exterior, *poly.interiors]:
            pts = np.asarray(to_slide(np.asarray(ring.coords)))
            snapped = [(round(x * 200) / 200, round(y * 200) / 200) for x, y in pts]    # 0.005 英吋格點,去掉看不見的細節
            uniq = [snapped[0]] + [b for a, b in zip(snapped, snapped[1:]) if a != b]
            if uniq[0] == uniq[-1]: uniq = uniq[:-1]
            if len(uniq) >= 3: rings.append([(_emu(x), _emu(y)) for x, y in uniq])
    if not rings: return None
    builder = shapes.build_freeform(rings[0][0][0], rings[0][0][1], 1.0)
    for i, ring in enumerate(rings):
        if i: builder.move_to(*ring[0])
        builder.add_line_segments(ring[1:], close=True)
    shp = builder.convert_to_shape()
    shp.fill.solid(); shp.fill.fore_color.rgb = _pp_rgb(fill)
    shp.line.color.rgb = _pp_rgb(line); shp.line.width = Pt(line_pt)
    shp.shadow.inherit = False
    if name: shp.name = name
    return shp

def _pp_native_map(slide, scene, box):
    """
    把 _render_manual_static 收集的 scene 畫成原生物件:地圖區塊(向量)、標籤(文字方塊)、引線、圖例。
    box = (x, y, w, h) 英吋;內容等比例縮放置中。
    """
    bx, by, bw, bh = box
    xf, fs = scene["xf"], scene["fs"]
    legend = scene["legend"]
    map_w = bw - (1.8 if legend else 0)

    def label_geom(lab):    # 標籤中心與外框大小(英吋,圖形座標,y 向上)
        (cx, cy), (hx, hy) = (xf(np.array([lab["pos"]]))[0],
                              xf(np.array([[lab["pos"][0] + lab["w"] / 2, lab["pos"][1] + lab["h"] / 2]]))[0])
        return (cx, cy), (abs(hx - cx) * 2, abs(hy - cy) * 2)

    corners = [xf(np.array([(g.bounds[0], g.bounds[1]), (g.bounds[2], g.bounds[3])])) for _, g, _ in scene["regions"]]
    xs = [p[0] for c in corners for p in c]; ys = [p[1] for c in corners for p in c]
    laid = [(lab, *label_geom(lab)) for lab in scene["labels"]]
    for _, (cx, cy), (w, h) in laid:
        xs += [cx - w / 2, cx + w / 2]; ys += [cy - h / 2, cy + h / 2]
    ex0, ex1, ey0, ey1 = min(xs), max(xs), min(ys), max(ys)
    k = min(map_w / (ex1 - ex0), bh / (ey1 - ey0))
    ox = bx + (map_w - k * (ex1 - ex0)) / 2
    oy = by + (bh - k * (ey1 - ey0)) / 2
    def to_slide(lonlat):    # 經緯度 → 圖形英吋(xf)→ 投影片英吋(等比例縮放、y 向下)
        a = xf(np.asarray(lonlat, dtype=float).reshape(-1, 2))
        return np.column_stack([ox + (a[:, 0] - ex0) * k, oy + (ey1 - a[:, 1]) * k])

    grp = slide.shapes.add_group_shape()
    grp.name = "地圖"
    for name, geom, color in scene["regions"]:
        _pp_polygon(grp.shapes, geom, to_slide, color, "#ffffff", 0.75, name)
    for lab, _, _ in laid:                                    # 引線與錨點在標籤下面
        if lab["edge"]:
            a, e = to_slide([lab["anchor"]])[0], to_slide([lab["edge"]])[0]
            _pp_line(slide.shapes, a, e, "#6b7280", 0.9)
            _pp_shape(slide.shapes, "oval", a[0] - 0.03, a[1] - 0.03, 0.06, 0.06, fill="#374151")
    for lab, (cx, cy), (w, h) in laid:
        X, Y = ox + (cx - ex0) * k, oy + (ey1 - cy) * k
        shp = _pp_shape(slide.shapes, "round", X - w * k / 2, Y - h * k / 2, w * k, h * k, fill="#ffffff",
                        line="#9ca3af", line_pt=0.75, name=f"標籤 {lab['text'].splitlines()[0]}", radius=0.2)
        _pp_fill_text(shp.text_frame, lab["text"].split("\n"), max(6.0, fs * k), False, "#111827", "c", "m")

    if legend:                                                # 圖例(右下角)
        lx, ly1 = bx + bw - 1.7, by + bh
        if legend["kind"] == "cat":
            for i, (text, color) in enumerate(reversed(legend["items"][:12])):
                y = ly1 - 0.3 * (i + 1)
                _pp_shape(slide.shapes, "rect", lx, y + 0.04, 0.2, 0.2, fill=color, line="#9ca3af", line_pt=0.5,
                          name=f"圖例色塊 {text}")
                _pp_text(slide.shapes, lx + 0.3, y, 1.35, 0.28, text, 11, align="l", name=f"圖例 {text}")
        else:
            steps, top = 8, ly1 - 2.6
            for i in range(steps):                            # 上面是最大值、下面是最小值
                frac = 1 - i / (steps - 1)
                _pp_shape(slide.shapes, "rect", lx, top + i * 0.3, 0.3, 0.3, name=f"色階 {i + 1}",
                          fill=mpl.colors.to_hex(legend["cmap"](frac)))
            fmt = lambda v: f"{v:,.0f}" if abs(legend["hi"]) >= 100 else f"{v:,.2f}"
            _pp_text(slide.shapes, lx + 0.4, top - 0.05, 1.3, 0.3, fmt(legend["hi"]), 11, align="l", name="色階最大值")
            _pp_text(slide.shapes, lx + 0.4, top + steps * 0.3 - 0.25, 1.3, 0.3, fmt(legend["lo"]), 11, align="l",
                     name="色階最小值")

def _fig_png(fig, dpi=170):
    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", transparent=True)
    buf.seek(0)
    return buf

# ===============================================
# PPTX:標註框版型(一頁總覽,地圖居中、左右長出標註框)
# ===============================================
# 這一版型不做色階,改成「有填內容的地區上色+標註框+指標線」:
# 適合「各縣市主要受損作物」這種一格放一段文字的清單型資料。

import math

ANNO_W, ANNO_H = 13.333, 7.5      # 16:9 投影片(英吋)
ANNO_PAD = 0.40                   # 外距
ANNO_BOX_W = 3.52                 # 標註框寬
ANNO_COL_GAP = 0.26               # 標註框與地圖之間留的空間
ANNO_INSET = ("澎湖縣", "金門縣", "連江縣")   # 這三個畫成地圖下方的小圖
ANNO_MAX_PT, ANNO_MIN_PT = 12.5, 7.5


def _hex_mix(a: str, b: str, t: float) -> str:
    """混色:t=0 就是 a、t=1 就是 b"""
    a, b = a.lstrip("#"), b.lstrip("#")
    ca = [int(a[i:i + 2], 16) for i in (0, 2, 4)]
    cb = [int(b[i:i + 2], 16) for i in (0, 2, 4)]
    return "#" + "".join(f"{round(x + (y - x) * t):02X}" for x, y in zip(ca, cb))


def _anno_lines(content) -> List[str]:
    """一格裡的內容拆成幾行:換行、|、;、; 都算分隔(簡報上一個縣市常有好幾類資訊)"""
    return [p.strip() for p in re.split(r"[\n\r||;;]+", str(content or "")) if p.strip()]


def _anno_char_w(ch: str) -> float:
    """字寬(以字級為 1):全形 1.0、數字與英文字母約 0.56"""
    return 1.0 if ord(ch) > 0x2E7F else 0.56


ANNO_NO_START = ",。、;:?!)」』】》〉”’%…—·,.;:?!)]}>»"   # 不能落在行首
ANNO_NO_END = "(「『【《〈“‘([{<«"                                  # 不能落在行尾


def _anno_wrap(text: str, max_in: float, pt: float) -> List[str]:
    """自己折行(不靠 PowerPoint 的自動換行,每行才會跟估算的一樣寬),並做中文避頭尾。"""
    unit, out, line, w = pt / 72.0, [], "", 0.0
    for ch in str(text):
        cw = _anno_char_w(ch) * unit
        if line and w + cw > max_in and ch not in ANNO_NO_START:
            if line[-1] in ANNO_NO_END:          # 開括號留在上一行很難看,跟著一起換行
                out.append(line[:-1])
                line, w = line[-1], _anno_char_w(line[-1]) * unit
            else:
                out.append(line)
                line, w = "", 0.0
        line += ch
        w += cw
    if line:
        out.append(line)
    return out or [""]


def _anno_balance(text: str, max_in: float, pt: float) -> List[str]:
    """標題這種大字:折行後如果最後一行只剩一兩個字,改成每行等長"""
    lines = _anno_wrap(text, max_in, pt)
    n = len(lines)
    if n < 2:
        return lines
    total = sum(sum(_anno_char_w(c) for c in ln) * pt / 72 for ln in lines)
    for i in range(1, 61):                     # 從「總寬 ÷ 行數」往上試,找到還排得成同樣行數的最小寬度
        trial = _anno_wrap(text, total / n * (1 + i * 0.01), pt)
        if len(trial) <= n and all(sum(_anno_char_w(c) for c in t) * pt / 72 <= max_in for t in trial):
            return trial
    return lines


def _anno_metrics(pt: float, n_lines: int):
    """標註框的尺寸(英吋):標題條高度、內文區高度、行距"""
    header = pt * 1.78 / 72
    line = pt * 1.45 / 72
    body = n_lines * line + pt * 1.25 / 72
    return header, body, line


def _anno_projection(box, bounds):
    """等距圓柱投影:以範圍中心緯度修正東西向,回傳 (to_in, 每度英吋)。
    to_in(lons, lats) 直接給投影片英吋座標(y 向下)。"""
    bx, by, bw, bh = box
    lon0, lat0, lon1, lat1 = [float(v) for v in bounds]
    kx = math.cos(math.radians((lat0 + lat1) / 2))
    span_x, span_y = max((lon1 - lon0) * kx, 1e-9), max(lat1 - lat0, 1e-9)
    s = min(bw / span_x, bh / span_y)
    ox, oy = bx + (bw - span_x * s) / 2, by + (bh - span_y * s) / 2

    def to_in(lons, lats):
        return (ox + (np.asarray(lons, dtype=float) - lon0) * kx * s,
                oy + (lat1 - np.asarray(lats, dtype=float)) * s)

    def to_slide(pts):
        xs, ys = to_in(np.asarray(pts)[:, 0], np.asarray(pts)[:, 1])
        return np.column_stack([xs, ys])

    return to_slide, (ox, oy, span_x * s, span_y * s)


def _anno_plan(merged, title: str, subtitle: str, note: str, main_color: str,
               max_items: int = 12, level: str = "縣市", show_islands: bool = True,
               order: Optional[Dict[str, int]] = None) -> Dict:
    """算出整張投影片的配置(全部是英吋座標),畫圖與除錯預覽共用同一份計算。"""
    main_color = (main_color or "#2F5D8A").strip()
    if not re.fullmatch(r"#[0-9a-fA-F]{6}", main_color):
        main_color = "#2F5D8A"
    paper, ink = "#FFFFFF", "#111827"
    base_fill = _hex_mix(main_color, "#16222E", 0.32)      # 沒有標註的地區:暗底
    hi_fill = _hex_mix(main_color, "#FFFFFF", 0.66)        # 有標註的地區:亮底
    line_color = _hex_mix(main_color, "#FFFFFF", 0.45)

    top, bottom = 0.28, ANNO_H - 0.32 - (0.34 if note else 0.08)
    inset_names = [n for n in ANNO_INSET if level == "縣市"] if show_islands else []
    main_df = merged[~merged["name"].isin(inset_names)] if inset_names else merged
    inset_df = merged[merged["name"].isin(inset_names)] if inset_names else merged.iloc[0:0]

    # 地圖區塊:夾在左右兩欄之間,下面留一條放離島小圖
    mid_x0 = ANNO_PAD + ANNO_BOX_W + ANNO_COL_GAP
    mid_x1 = ANNO_W - ANNO_PAD - ANNO_BOX_W - ANNO_COL_GAP
    strip = 0.66 if len(inset_names) else 0.0
    map_box = (mid_x0, top, mid_x1 - mid_x0, bottom - top - (strip + 0.16 if strip else 0.0))
    bounds = main_df.total_bounds if len(main_df) else merged.total_bounds
    to_slide, (mx, my, mw, mh) = _anno_projection(map_box, bounds)

    # 標註項目:依「表格填寫的順序」(不是地圖檔的順序),超過上限就取前幾個
    items = []
    filled = merged[merged["filled"]]
    if order is not None:
        filled = filled.assign(_order=[order.get(str(n), 10 ** 6) for n in filled["name"]]).sort_values("_order")
    for _, row in filled.iterrows():
        lines = _anno_lines(row[MANUAL_COL_CONTENT])
        if not lines:
            continue
        pt = row.geometry.representative_point()
        items.append({"name": str(row["label_name"]), "full": str(row["name"]), "lines": lines,
                      "lon": pt.x, "lat": pt.y})
    dropped = max(0, len(items) - max(int(max_items), 1))
    dropped_names = [it["name"] for it in items[max(int(max_items), 1):]]
    items = items[:max(int(max_items), 1)]
    for it in items:
        it["x"], it["y"] = to_slide([(it["lon"], it["lat"])])[0]

    # 離島小圖:主圖下方排一排,各自用自己的範圍放大
    cards = []
    if strip:
        cw, ch = 0.98, strip
        total = len(inset_names) * cw
        cx0 = mx + (mw - total) / 2
        for i, name in enumerate(inset_names):
            rows = inset_df[inset_df["name"] == name]
            if rows.empty:
                continue
            geom = rows.geometry.iloc[0]
            card = (cx0 + i * cw + 0.05, bottom - strip, cw - 0.10, ch - 0.26)
            c_to_slide, _ = _anno_projection(card, geom.bounds)
            on = any(it["full"] == name for it in items)
            cards.append({"name": name.replace("縣", ""), "full": name, "geom": geom, "on": on,
                          "box": (cx0 + i * cw + 0.05, bottom - strip, cw - 0.10, ch),
                          "to_slide": c_to_slide, "cx": cx0 + i * cw + cw / 2, "cy": bottom - strip + (ch - 0.26) / 2})
    # 離島的錨點換成小圖中心,指標線才不會指到畫面上不存在的位置
    for it in items:
        card = next((c for c in cards if c["full"] == it["full"]), None)
        if card:
            it["x"], it["y"] = card["cx"], card["cy"]
        it["side"] = "L" if it["x"] < ANNO_W / 2 else "R"

    # 左右兩欄:先依位置分邊(指標線最短),再把多的搬到另一邊讓兩欄一樣長
    def split(force):
        """force=False:兩邊都有東西才搬(線才不會橫越整張圖);
        force=True:一邊全空或太擠時也搬,寧可線長一點也要放得下"""
        for it in items:
            it["side"] = "L" if it["x"] < ANNO_W / 2 else "R"

        def side(k):
            return [it for it in items if it["side"] == k]

        while abs(len(side("L")) - len(side("R"))) > 1:
            if not force and (not side("L") or not side("R")):
                break
            big, other = ("L", "R") if len(side("L")) > len(side("R")) else ("R", "L")
            pick = sorted(side(big), key=lambda d: abs(d["x"] - ANNO_W / 2))[0]
            pick["side"] = other
        return sorted(side("L"), key=lambda d: d["y"]), sorted(side("R"), key=lambda d: d["y"])

    # 標題區(右欄上方)
    title_pt, sub_pt = 21.0, 14.0
    title_lines = _anno_balance(title, ANNO_BOX_W, title_pt) if title else []
    sub_lines = _anno_balance(subtitle, ANNO_BOX_W, sub_pt) if subtitle else []
    title_h = len(title_lines) * title_pt * 1.26 / 72 + (0.13 + len(sub_lines) * sub_pt * 1.42 / 72 if sub_lines else 0)

    # 兩欄排得下嗎?放不下就把字級一路縮
    def layout(pt, left, right):
        cols, fit = {}, True
        for key, lst in (("L", left), ("R", right)):
            boxes = []
            for it in lst:
                lines = [ln for line in it["lines"] for ln in _anno_wrap(line, ANNO_BOX_W - 0.30, pt)]
                header, body, line_h = _anno_metrics(pt, len(lines))
                boxes.append({"name": it["name"], "pt": pt, "lines": lines, "header": header, "body": body,
                              "line_h": line_h, "h": header + 0.03 + body, "anchor": it,
                              "x": ANNO_PAD if key == "L" else ANNO_W - ANNO_PAD - ANNO_BOX_W})
            col_top = top if key == "L" else top + title_h + 0.22
            gap = pt * 1.05 / 72
            room = bottom - col_top
            need = sum(b["h"] for b in boxes) + gap * max(len(boxes) - 1, 0)
            fit = fit and need <= room

            def place(g, shift=0.0):
                """理想位置=框心對齊地區;依序往下推、超出底部再整體往上收"""
                y = col_top + shift
                for b in boxes:
                    want = min(max(b["anchor"]["y"] - b["h"] / 2, y), bottom - b["h"])
                    b["y"] = max(y, want)
                    y = b["y"] + b["h"] + g
                for i in range(len(boxes) - 1, -1, -1):
                    lim = (bottom - boxes[i]["h"]) if i == len(boxes) - 1 else boxes[i + 1]["y"] - boxes[i]["h"] - g
                    boxes[i]["y"] = max(min(boxes[i]["y"], lim), col_top)

            place(gap)
            # 欄位還有空間時,把留白平均分到每個間隔(每個間隔最多多 0.45 吋),框才不會全擠在一起
            slack = room - need
            if len(boxes) > 1 and slack > 0.25:
                extra = min(0.45, slack / (len(boxes) - 1))
                place(gap + extra, max(0.0, (room - need - extra * (len(boxes) - 1)) / 2))
            cols[key] = boxes
        return cols, fit

    # 兩種分邊都試:挑「放得下、字最大、兩欄最平均」的那個
    best = None
    for force in (False, True):
        left, right = split(force)
        pt = ANNO_MAX_PT
        cols, fit = layout(pt, left, right)
        while not fit and pt > ANNO_MIN_PT:
            pt = round(pt - 0.5, 2)
            cols, fit = layout(pt, left, right)
        score = (0 if fit else 1, -pt, abs(len(left) - len(right)))
        if best is None or score < best[0]:
            best = (score, cols, fit, pt)
    _, cols, fit, pt = best

    # 指標線:框的內側邊中點 → 地區錨點,兩頭各留一點空隙
    leaders = []
    for key, boxes in cols.items():
        start_x = ANNO_PAD + ANNO_BOX_W if key == "L" else ANNO_W - ANNO_PAD - ANNO_BOX_W
        for b in boxes:
            ax, ay = b["anchor"]["x"], b["anchor"]["y"]
            ey = b["y"] + b["h"] / 2
            dx, dy = ax - start_x, ay - ey
            dist = math.hypot(dx, dy) or 1.0
            u = min(0.14, dist / 2)
            leaders.append({"from": (start_x + dx * u / dist, ey + dy * u / dist),
                            "to": (ax - dx * u / dist, ay - dy * u / dist),
                            "anchor": (ax, ay), "color": line_color})

    # 地圖填色:有標註的亮、其餘暗
    marked = {it["full"] for it in items}
    regions = [(str(r["name"]), r.geometry, hi_fill if str(r["name"]) in marked else base_fill)
               for _, r in main_df.iterrows()]

    return {"paper": paper, "ink": ink, "main": main_color, "base_fill": base_fill, "hi_fill": hi_fill,
            "to_slide": to_slide, "regions": regions, "cards": cards, "boxes": cols, "leaders": leaders,
            "title": {"lines": title_lines, "pt": title_pt, "x": ANNO_W - ANNO_PAD - ANNO_BOX_W, "y": top,
                      "w": ANNO_BOX_W, "h": title_h},
            "subtitle": {"lines": sub_lines, "pt": sub_pt,
                         "x": ANNO_W - ANNO_PAD - ANNO_BOX_W,
                         "y": top + (len(title_lines) * title_pt * 1.26 / 72 + 0.13 if title_lines else 0),
                         "w": ANNO_BOX_W, "h": len(sub_lines) * sub_pt * 1.42 / 72},
            "note": {"text": note, "x": ANNO_PAD, "y": bottom + 0.12,
                     "w": ANNO_W - 2 * ANNO_PAD - (5.6 if dropped else 0), "pt": 8.5} if note else None,
            "dropped": dropped, "max_items": int(max_items),
            "dropped_text": ("另有 %d 個未顯示:%s%s" % (dropped, "、".join(dropped_names[:5]),
                                                        "…" if dropped > 5 else "")) if dropped else "",
            "bottom": bottom, "fit": fit, "pt": pt}


def _append_anno_slide(prs, plan):
    """把 plan 畫成一頁:底色、向量地圖、離島小圖、指標線、標註框、標題/副標/註記。
    全部是原生物件,匯出後在 PowerPoint 裡可以直接改字、換色、拉位置。"""
    from pptx.util import Inches, Pt

    slide = prs.slides.add_slide(prs.slide_layouts[6])
    fill = slide.background.fill
    fill.solid()
    fill.fore_color.rgb = _pp_rgb(plan["paper"])
    main = plan["main"]

    grp = slide.shapes.add_group_shape()
    grp.name = "地圖"
    for name, geom, color in plan["regions"]:
        _pp_polygon(grp.shapes, geom, plan["to_slide"], color, "#FFFFFF", 0.75, name)
    for card in plan["cards"]:
        x, y, w, h = card["box"]
        _pp_shape(slide.shapes, "rect", x, y, w, h, fill=_hex_mix(plan["paper"], main, 0.04),
                  line=_hex_mix(main, "#FFFFFF", 0.78), line_pt=0.75, name=f"離島框 {card['name']}")
        _pp_polygon(slide.shapes, card["geom"], card["to_slide"], plan["hi_fill"] if card["on"] else plan["base_fill"],
                    _hex_mix(main, "#FFFFFF", 0.40), 0.6, f"離島 {card['name']}")
        _pp_text(slide.shapes, x, y + h - 0.24, w, 0.20, card["name"], 7.5,
                 bold=bool(card["on"]), color=main if card["on"] else "#6B7280", align="c", anchor="m",
                 name=f"離島名稱 {card['name']}")

    for ld in plan["leaders"]:
        _pp_line(slide.shapes, ld["from"], ld["to"], ld["color"], 1.0)
        ax, ay = ld["anchor"]
        _pp_shape(slide.shapes, "oval", ax - 0.035, ay - 0.035, 0.07, 0.07, fill=main, name="錨點")

    for key, boxes in plan["boxes"].items():
        for b in boxes:
            shp = _pp_shape(slide.shapes, "rect", b["x"], b["y"], ANNO_BOX_W, b["header"], fill=main,
                            name=f"標題條 {b['name']}")
            _pp_fill_text(shp.text_frame, b["name"], b["pt"], True, "#FFFFFF", "l", "m", (0.10, 0, 0.04, 0))
            _pp_shape(slide.shapes, "rect", b["x"], b["y"] + b["header"] + 0.03, ANNO_BOX_W, b["body"],
                      fill="#FFFFFF", line=_hex_mix(main, "#FFFFFF", 0.62), line_pt=0.75, name=f"說明框 {b['name']}")
            _pp_text(slide.shapes, b["x"] + 0.11, b["y"] + b["header"] + 0.03 + 0.04,
                     ANNO_BOX_W - 0.22, b["body"] - 0.06, b["lines"], b["pt"], False, "#1F2937", "l", "t",
                     name=f"說明 {b['name']}", wrap=True)

    t = plan["title"]
    if t["lines"]:
        _pp_text(slide.shapes, t["x"], t["y"], t["w"], t["h"], t["lines"], t["pt"], True, plan["ink"], "l", "t",
                 name="主標題")
    s = plan["subtitle"]
    if s["lines"]:
        _pp_text(slide.shapes, s["x"], s["y"], s["w"], s["h"], s["lines"], s["pt"], True, main, "l", "t",
                 name="副標")
    if plan.get("dropped_text"):
        _pp_text(slide.shapes, ANNO_W - ANNO_PAD - 5.5, plan["bottom"] + 0.12, 5.5, 0.24,
                 plan["dropped_text"], 8.5, False, "#9CA3AF", "r", "t", name="省略提示")
    n = plan["note"]
    if n:
        _pp_line(slide.shapes, (n["x"], n["y"] - 0.04), (n["x"] + n["w"], n["y"] - 0.04), "#E5E7EB", 0.75)
        _pp_text(slide.shapes, n["x"], n["y"], n["w"], 0.24, n["text"], n["pt"], False, "#6B7280", "l", "t",
                 name="註記")
    return slide


def _anno_order(input_df) -> Dict[str, int]:
    """表格填寫的順序(名稱 → 第幾列),標註框照這個順序取前幾個,使用者才猜得到哪幾個會被留下"""
    if input_df is None or len(input_df) == 0:
        return {}
    out = {}
    try:
        for i, (name, content) in enumerate(zip(input_df[MANUAL_COL_NAME], input_df[MANUAL_COL_CONTENT])):
            if str(content or "").strip():
                out.setdefault(normalize_name(str(name)), i)
    except Exception:      # 欄位對不上就退回地圖檔順序,不要讓匯出整個失敗
        return {}
    return out


def build_annotation_pptx(merged, level, scope, title, subtitle, note, main_color,
                          max_items=12, show_islands=True, order=None) -> str:
    """標註框版型 → 一份一頁的 PPTX(16:9)"""
    from pptx import Presentation
    from pptx.util import Inches

    plan = _anno_plan(merged, _manual_title(title, level, scope), subtitle or "", note or "",
                      main_color, max_items=max_items, level=level, show_islands=show_islands, order=order)
    prs = Presentation()
    prs.slide_width, prs.slide_height = Inches(ANNO_W), Inches(ANNO_H)
    _append_anno_slide(prs, plan)
    path = _named_path(_manual_file_stem(title, level, scope) + "_標註框", ".pptx")
    prs.save(path)
    return path


def _anno_rows(input_df):
    """表格 → 每個地區一列。同一個地區寫了好幾列時合併成一個標註框(不要讓後面的蓋掉前面的)。"""
    if input_df is None or len(input_df) == 0:
        return input_df
    data = input_df.copy()
    data[MANUAL_COL_NAME] = data[MANUAL_COL_NAME].astype(str).map(normalize_name)
    data[MANUAL_COL_CONTENT] = data[MANUAL_COL_CONTENT].fillna("").astype(str).str.strip()
    data = data[data[MANUAL_COL_CONTENT] != ""]
    if data.empty:
        return data
    return data.groupby(MANUAL_COL_NAME, sort=False, as_index=False).agg(
        {MANUAL_COL_CONTENT: lambda s: ";".join(dict.fromkeys(str(v) for v in s))})


def export_annotation_pptx(input_df, level, scope, title, subtitle, note, main_color, max_items, show_islands):
    """「手動填寫」表格 → 一頁標註框地圖 PPTX。內容一格可以寫好幾行(換行或 ; 分隔)。"""
    merged, _ = _manual_frame(_anno_rows(input_df), level, scope, show_islands)
    if not merged["filled"].any():
        raise gr.Error("請先在表格裡至少填一格的內容")
    path = build_annotation_pptx(merged, level, scope, title, subtitle, note, main_color,
                                 max_items=max_items, show_islands=show_islands, order=_anno_order(input_df))
    gr.Info("已產生標註框版型 PPTX(地圖、標註框、文字都是可編輯物件)")
    return gr.update(value=path, visible=True)

def export_manual_pptx(input_df, store, title, color_scheme, label_mode, label_size,
                       with_overview=True, with_table=True, progress=gr.Progress()):
    """
    每個有資料的縣市一頁:標題+該縣市鄉鎮市區地圖(+右側資料表)。
    所有頁共用同一組色階/分類顏色,翻頁比較才有意義。資料取自 store(涵蓋所有縣市,不限目前表格範圍)。
    """
    from pptx import Presentation
    from pptx.util import Inches, Pt
    from pptx.enum.text import MSO_ANCHOR

    store = merge_table_into_store(input_df, store)
    town_gdf = _town_gdf()
    county_of = dict(zip(town_gdf["name"], town_gdf["縣市"]))
    town_entries = {k: v for k, v in store.items() if k in county_of}
    county_entries = {k: v for k, v in store.items() if k in DEFAULT_COUNTIES}
    if not town_entries and not county_entries:
        raise gr.Error("還沒有資料可以匯出:請先在表格填寫內容(縣市或鄉鎮市區皆可)")
    # 有鄉鎮資料:每縣市一頁,放該縣市的鄉鎮地圖。只有縣市資料:每縣市一頁,全國圖標出該縣市並列出它的內容。
    county_mode = not town_entries
    entries = county_entries if county_mode else town_entries

    scheme = _scheme_key(color_scheme)
    order = all_manual_names("縣市" if county_mode else "鄉鎮市區")   # 順序固定,頁序才穩定
    ordered = [(n, entries[n]) for n in order if n in entries]
    numbers = pd.to_numeric(pd.Series([v for _, v in ordered]).str.replace(",", "", regex=False), errors="coerce")
    is_numeric = bool(numbers.notna().all())
    vrange = (float(numbers.min()), float(numbers.max())) if is_numeric else None
    cats = None if is_numeric else list(dict.fromkeys(v for _, v in ordered))
    counties = ([n for n, _ in ordered] if county_mode
                else [c for c in DEFAULT_COUNTIES if any(county_of[n] == c for n, _ in ordered)])
    base = (title or "").strip()

    prs = Presentation()
    prs.slide_width, prs.slide_height = Inches(13.333), Inches(7.5)
    blank = prs.slide_layouts[6]

    def add_slide(heading, scene, rows, info=None):
        slide = prs.slides.add_slide(blank)
        tb = slide.shapes.add_textbox(Inches(0.5), Inches(0.3), Inches(12.3), Inches(0.9))
        run = tb.text_frame.paragraphs[0].add_run()
        run.text = heading
        run.font.size, run.font.bold, run.font.name = Pt(32), True, PPT_FONT

        box_w = 7.9 if (rows or info) else 12.3
        _pp_native_map(slide, scene, (0.5, 1.35, box_w, 5.8))   # 地圖、標籤、圖例都是可編輯的原生物件
        if info:   # 只有縣市資料時:右側用大字呈現該縣市的內容
            panel = slide.shapes.add_textbox(Inches(8.7), Inches(2.4), Inches(4.1), Inches(3.2)).text_frame
            panel.word_wrap = True
            for i, (text, size, bold) in enumerate(((info[0], 28, False), (info[1], 54, True))):
                para = panel.paragraphs[0] if i == 0 else panel.add_paragraph()
                run = para.add_run()
                run.text = text
                run.font.size, run.font.bold, run.font.name = Pt(size), bold, PPT_FONT
        if rows:
            shown = rows[:PPT_TABLE_MAX_ROWS]
            extra = len(rows) - len(shown)
            n = len(shown) + 1 + (1 if extra > 0 else 0)
            row_h = min(0.3, 5.8 / n)                          # 列數多時縮小列高與字級,才放得進頁面
            font_pt = 12 if row_h >= 0.28 else 10
            table = slide.shapes.add_table(n, 2, Inches(8.7), Inches(1.4), Inches(4.1), Inches(row_h * n)).table
            table.columns[0].width, table.columns[1].width = Inches(2.3), Inches(1.8)
            for row in table.rows: row.height = Inches(row_h)
            cells = [(MANUAL_COL_NAME, MANUAL_COL_CONTENT)] + shown + ([(f"…另有 {extra} 筆", "")] if extra > 0 else [])
            for r, (a, b) in enumerate(cells):
                for c, text in enumerate((a, b)):
                    cell = table.cell(r, c)
                    cell.text = str(text)
                    # PowerPoint 的儲存格預設上下內距很大,列高會被撐開、整張表超出頁面;縮小內距並垂直置中
                    cell.margin_top = cell.margin_bottom = Inches(0.02)
                    cell.vertical_anchor = MSO_ANCHOR.MIDDLE
                    for para in cell.text_frame.paragraphs:
                        for run in para.runs:
                            run.font.size, run.font.name = Pt(font_pt), PPT_FONT
                    if c == 1 and r > 0 and is_numeric:
                        cell.text_frame.paragraphs[0].alignment = 3   # 右對齊(PP_ALIGN.RIGHT)
        return slide

    steps = len(counties) + (1 if with_overview and county_entries else 0)
    done = 0
    progress((0, steps), desc="產生簡報")

    if with_overview and county_entries:
        df = manual_table("縣市", MANUAL_NATIONAL, store)
        merged, num = _manual_frame(df, "縣市", MANUAL_NATIONAL, True)
        sc = {}
        _render_manual_static(merged, num, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,
                              figsize=(10, 10), scene=sc)
        rows = [(n, county_entries[n]) for n in DEFAULT_COUNTIES if n in county_entries] if with_table else []
        add_slide(base or "臺灣各縣市", sc, rows)
        done += 1; progress((done, steps), desc="產生簡報")

    for county in counties if county_mode else []:
        df = manual_table("縣市", MANUAL_NATIONAL, {county: county_entries[county]})   # 只留這個縣市有值,其餘灰色
        merged, _ = _manual_frame(df, "縣市", MANUAL_NATIONAL, True, numeric=is_numeric)
        sc = {}
        _render_manual_static(merged, is_numeric, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,
                              vrange=vrange, cats=cats, figsize=(9, 9), scene=sc)
        add_slide(f"{county}|{base}" if base else county, sc, [], info=(county, county_entries[county]))
        done += 1; progress((done, steps), desc="產生簡報")

    for county in [] if county_mode else counties:
        df = manual_table("鄉鎮市區", county, store)
        merged, _ = _manual_frame(df, "鄉鎮市區", county, True, numeric=is_numeric)
        sc = {}
        _render_manual_static(merged, is_numeric, "鄉鎮市區", county, "", scheme, label_mode, label_size,
                              vrange=vrange, cats=cats, figsize=(9, 9), scene=sc)
        rows = [(n[len(county):], v) for n, v in ordered if county_of[n] == county]
        if is_numeric: rows.sort(key=lambda r: -float(r[1].replace(",", "")))
        add_slide(f"{county}|{base}" if base else f"{county}各鄉鎮市區", sc, rows if with_table else [])
        done += 1; progress((done, steps), desc="產生簡報")

    stem = base or ("縣市統計圖" if county_mode else "鄉鎮市區統計圖")
    path = _named_path(f"{stem}_一頁一縣市", ".pptx")
    prs.save(path)
    return gr.update(value=path, visible=True)

# ===============================================
# 7. 圖解排名(資訊圖表風格的縣市排名圖)
# ===============================================

INFO_ISLANDS = ["澎湖縣", "金門縣", "連江縣"]
INFO_ORDERS = ["數值高 → 低(第 1 名 = 最高)", "數值低 → 高(第 1 名 = 最低)"]
INFO_DEFAULT_COLORS = ("#3b82c4", "#dc4b3a", "#c7c7c7")   # 排名前段 / 後段 / 其他

# 示範數值(抄自使用者提供的出生率圖,僅供預覽版型,未經查證)
RANK_EXAMPLE = {
    "新北市": "4.52", "桃園市": "7.68", "新竹市": "6.02", "新竹縣": "6.79", "苗栗縣": "4.24", "雲林縣": "4.8",
    "嘉義市": "4.53", "嘉義縣": "4.75", "臺南市": "4.98", "澎湖縣": "7.02", "臺北市": "6.38", "金門縣": "5.04",
    "基隆市": "3.66", "宜蘭縣": "5.32", "臺中市": "5.94", "彰化縣": "7.79", "南投縣": "4.99", "花蓮縣": "5.74",
    "臺東縣": "6.86", "高雄市": "5.7", "屏東縣": "5.3", "連江縣": "6.99",
}

def load_rank_example(store):
    store = {k: v for k, v in (store or {}).items() if k not in DEFAULT_COUNTIES}
    store.update(RANK_EXAMPLE)
    return store, gr.update(value="縣市"), gr.update(), manual_table("縣市", MANUAL_NATIONAL, store)

def _county_numeric_entries(store) -> Dict[str, Tuple[str, float]]:
    """縣市層級、已填的內容 → {縣市: (原文, 數值)}。排名一定要是數字。"""
    out = {}
    for name in DEFAULT_COUNTIES:
        raw = str((store or {}).get(name, "")).strip()
        if not raw: continue
        num = pd.to_numeric(raw.replace(",", ""), errors="coerce")
        if pd.isna(num):
            raise gr.Error(f"「{name}」填的是「{raw}」,不是數字;圖解排名需要數值")
        out[name] = (raw, float(num))
    if not out:
        raise gr.Error("還沒有縣市資料:請先到「手動填寫」分頁填寫縣市數值(或按本頁的範例)")
    return out

def _county_anchors() -> Dict[str, Tuple[float, float]]:
    gdf = _require_map("county")
    return {n: (pt.x, pt.y) for n, pt in zip(gdf["name"], gdf.geometry.representative_point())}

def _rank_columns(anchors):
    """
    標籤分欄:臺北市放上方中間;三個離島放最下排(不畫引線);其餘 18 縣市依經度對半分成左右兩欄,
    各欄由北到南排列,引線才不容易交錯。
    """
    mainland = sorted((c for c in DEFAULT_COUNTIES if c not in INFO_ISLANDS and c != "臺北市"),
                      key=lambda c: anchors[c][0])
    half = len(mainland) // 2
    by_lat = lambda cs: sorted(cs, key=lambda c: -anchors[c][1])
    return by_lat(mainland[:half]), by_lat(mainland[half:])

def _contrast_text(fill_hex: str) -> str:
    """依底色明暗挑文字色:淺底(例如灰色)用深色字,深底用白字,避免灰底白字看不清楚"""
    r, g, b = mpl.colors.to_rgb(fill_hex)
    return "#1f2937" if 0.299 * r + 0.587 * g + 0.114 * b > 0.62 else "#ffffff"

def _draw_pill(ov, x, y, w, h, name, rank_text, value_text, color, ranked, fs, rank_color=None, text_color="#ffffff"):
    """膠囊標籤:左側色塊(名次圓圈+縣市名)+右側白底數值,外框同色"""
    wl = w * 0.64
    ov.add_patch(FancyBboxPatch((x, y - h / 2), w, h, boxstyle=f"round,pad=0,rounding_size={h / 2}",
                                fc="white", ec=color, lw=1.3, zorder=6))
    ov.add_patch(FancyBboxPatch((x, y - h / 2), wl, h, boxstyle=f"round,pad=0,rounding_size={h / 2}",
                                fc=color, ec=color, lw=1.3, zorder=7))
    ov.add_patch(Circle((x + h / 2, y), h * 0.36, fc="white", ec="white", zorder=8))
    ov.text(x + h / 2, y, rank_text, ha="center", va="center", fontsize=fs * 0.72, fontweight="bold",
            color=rank_color or color, zorder=9)
    ov.text(x + h + 0.08, y, name, ha="left", va="center", fontsize=fs, fontweight="bold", color=text_color, zorder=9)
    ov.text(x + wl + (w - wl) / 2, y, value_text, ha="center", va="center", fontsize=fs, fontweight="bold",
            color="#111827" if ranked else "#9ca3af", zorder=9)

def render_rank_infographic(entries, title, subtitle, unit_note, footnote, descending, top_n, bottom_n, colors,
                            figsize=(14.0, 9.6)):
    """
    資訊圖表風的縣市排名圖:中間是臺灣本島(依名次著色),左右兩欄與上下排是膠囊標籤
    (名次、縣市、數值),以折線引到各縣市;離島只列標籤。
    """
    W, H = figsize
    c_top, c_bottom, c_other = colors
    fig = Figure(figsize=figsize)
    FigureCanvasAgg(fig)
    font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}

    values = {n: v for n, (_, v) in entries.items()}
    ranked = sorted(values, key=lambda n: values[n], reverse=descending)
    total = len(ranked)
    top_k = max(0, min(int(top_n), total))                    # 標示前幾名(0=不標)
    bottom_k = max(0, min(int(bottom_n), total - top_k))       # 標示後幾名;不和前段重疊
    rank_no = {n: 1 + sum(1 for m in ranked if (values[m] > values[n] if descending else values[m] < values[n]))
               for n in ranked}
    def klass(n):
        if n not in values: return "none"
        i = ranked.index(n)
        return "top" if i < top_k else "bottom" if bottom_k and i >= total - bottom_k else "other"
    color_of = {"top": c_top, "bottom": c_bottom, "other": c_other, "none": "#e5e7eb"}

    # --- 版面(單位:英吋)---
    rows = 10
    y_first, y_last = H - 2.25, 0.75
    pitch = (y_first - y_last) / (rows - 1)
    pill_w, pill_h = 2.7, 0.46
    x_left, x_right = 0.45, W - 0.45 - pill_w
    map_x0, map_x1 = x_left + pill_w + 0.5, x_right - 0.5
    map_y0, map_y1 = y_first - 8 * pitch - 0.35, y_first - 0.4

    gdf = _require_map("county")
    main = gdf[~gdf["name"].isin(INFO_ISLANDS)].copy()
    main["_class"] = main["name"].map(klass)
    map_ax = fig.add_axes([map_x0 / W, map_y0 / H, (map_x1 - map_x0) / W, (map_y1 - map_y0) / H])
    for cls in ("none", "other", "top", "bottom"):
        sub = main[main["_class"] == cls]
        if not sub.empty: sub.plot(ax=map_ax, color=color_of[cls], edgecolor=MAP_EDGE, linewidth=0.6)  # 圖卡維持白底,只把白色界線改深灰
    bx0, by0, bx1, by1 = main.total_bounds
    map_ax.set_xlim(bx0 - 0.02, bx1 + 0.02); map_ax.set_ylim(by0 - 0.02, by1 + 0.02)
    map_ax.set_axis_off()
    map_ax.apply_aspect()

    ov = fig.add_axes([0, 0, 1, 1])
    ov.set_xlim(0, W); ov.set_ylim(0, H); ov.set_axis_off(); ov.patch.set_alpha(0)

    # 同步收集每個元素,匯出 PPTX 時畫成可編輯的原生物件
    scene = {"W": W, "H": H, "pills": [], "lines": [], "dots": [], "legend": [],
             "xf": lambda a: map_ax.transData.transform(np.asarray(a, dtype=float)) / fig.dpi,
             "regions": [(r["name"], r.geometry, color_of[r["_class"]]) for _, r in main.iterrows()],
             "unit": unit_note, "note": footnote, "title": (title or "各縣市排名", subtitle)}

    anchors = _county_anchors()
    def to_in(lonlat):
        px = map_ax.transData.transform(lonlat)
        return px[0] / fig.dpi, px[1] / fig.dpi

    def label_of(n):
        raw = entries[n][0] if n in entries else "—"
        rank = str(rank_no[n]) if n in rank_no else "–"
        return rank, raw

    def put(n, x, y):
        k = klass(n)
        rank, raw = label_of(n)
        # 灰色(其他)膠囊的名次數字用較深的灰,白圈裡才看得清楚
        pill_color = color_of[k] if k != "none" else "#d1d5db"
        text_color = _contrast_text(pill_color)
        rank_color = color_of[k] if k in ("top", "bottom") and text_color == "#ffffff" else "#374151"
        _draw_pill(ov, x, y, pill_w, pill_h, n, rank, raw, pill_color, k != "none", 15, rank_color=rank_color,
                   text_color=text_color)
        scene["pills"].append(dict(x=x, y=y, w=pill_w, h=pill_h, name=n, rank=rank, value=raw, color=pill_color,
                                   rank_color=rank_color, text_color=text_color, ranked=k != "none", fs=15))

    left, right = _rank_columns(anchors)
    line_kw = dict(color="#8a8f98", lw=0.9, zorder=3, solid_capstyle="round")
    for col, x in ((left, x_left), (right, x_right)):
        for i, n in enumerate(col):
            y = y_first - i * pitch
            put(n, x, y)
            ax_, ay_ = to_in(anchors[n])
            edge_x = x + pill_w if x == x_left else x
            ov.plot([edge_x, ax_, ax_], [y, y, ay_], **line_kw)        # 先水平、再垂直接到縣市
            ov.plot([ax_], [ay_], "o", ms=3.2, color="#111827", zorder=4)
            scene["lines"] += [((edge_x, y), (ax_, y)), ((ax_, y), (ax_, ay_))]
            scene["dots"].append((ax_, ay_))

    # 臺北市:上方中間,垂直引線
    tx, ty = to_in(anchors["臺北市"])
    top_y = y_first
    put("臺北市", tx - pill_w / 2, top_y)
    ov.plot([tx, tx], [top_y - pill_h / 2, ty], **line_kw)
    ov.plot([tx], [ty], "o", ms=3.2, color="#111827", zorder=4)
    scene["lines"].append(((tx, top_y - pill_h / 2), (tx, ty)))
    scene["dots"].append((tx, ty))

    # 離島:最下排,只列標籤
    bottom_y = y_last
    put("澎湖縣", x_left, bottom_y)
    put("金門縣", W / 2 - pill_w / 2, bottom_y)
    put("連江縣", x_right, bottom_y)

    # --- 標題、圖例、說明 ---
    renderer = fig.canvas.get_renderer()
    def width_in(t): return t.get_window_extent(renderer).width / fig.dpi
    t_main = ov.text(0, H - 0.75, title or "各縣市排名", ha="left", va="center", fontsize=27, fontweight="bold",
                     color="#111827", **font_kw)
    t_sub = ov.text(0, H - 0.78, subtitle, ha="left", va="center", fontsize=15, color="#111827", **font_kw) if subtitle else None
    w1, w2 = width_in(t_main), (width_in(t_sub) + 0.15 if t_sub else 0)
    start = (W - (w1 + w2)) / 2
    t_main.set_x(start)
    if t_sub: t_sub.set_x(start + w1 + 0.15)

    legend = ([(c_top, f"排名前{top_k}")] if top_k else []) + ([(c_bottom, f"排名後{bottom_k}")] if bottom_k else []) \
        + [(c_other, "其他")]
    lx = W / 2 - (len(legend) * 2.2 - 0.7) / 2                   # 圖例項目數不固定,置中排列
    for color, text in legend:
        ov.add_patch(FancyBboxPatch((lx, H - 1.28), 1.5, 0.1, boxstyle="round,pad=0,rounding_size=0.05", fc=color,
                                    ec=color, zorder=5))
        ov.text(lx + 0.75, H - 1.55, text, ha="center", va="center", fontsize=15, color="#111827", **font_kw)
        scene["legend"].append((color, text, lx))
        lx += 2.2
    if unit_note:
        ov.text(W - 0.45, H - 1.6, unit_note, ha="right", va="center", fontsize=9, color="#4b5563", **font_kw)
    if footnote:
        ov.text(W - 0.45, 0.28, footnote, ha="right", va="center", fontsize=11, color="#374151", **font_kw)
    return fig, scene

def build_rank_pptx(scene, path):
    """圖解排名 → 單頁 PPTX。地圖區塊是向量圖形;標題、圖例、膠囊標籤(名次、縣市、數值)、說明都是文字方塊或圖形。"""
    from pptx import Presentation
    from pptx.util import Inches, Pt
    from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
    W, H = scene["W"], scene["H"]
    s = 13.333 / W                                            # 圖的英吋 → 投影片英吋
    prs = Presentation()
    prs.slide_width, prs.slide_height = Inches(13.333), Inches(H * s)
    slide = prs.slides.add_slide(prs.slide_layouts[6])
    X = lambda x: x * s
    Y = lambda y: (H - y) * s                                 # 圖的 y 向上、投影片 y 向下
    to_slide = lambda a: np.column_stack([scene["xf"](a)[:, 0] * s, (H - scene["xf"](a)[:, 1]) * s])

    grp = slide.shapes.add_group_shape()
    grp.name = "臺灣地圖"
    for name, geom, color in scene["regions"]:
        _pp_polygon(grp.shapes, geom, to_slide, color, "#ffffff", 0.9, name)
    for p1, p2 in scene["lines"]:
        _pp_line(slide.shapes, (X(p1[0]), Y(p1[1])), (X(p2[0]), Y(p2[1])), "#8a8f98", 0.9)
    for x, y in scene["dots"]:
        _pp_shape(slide.shapes, "oval", X(x) - 0.03, Y(y) - 0.03, 0.06, 0.06, fill="#111827")

    for pl in scene["pills"]:
        x, y, w, h, fs = pl["x"] * s, Y(pl["y"]), pl["w"] * s, pl["h"] * s, pl["fs"] * s
        wl = w * 0.64
        g = slide.shapes.add_group_shape()
        g.name = f"標籤 {pl['name']}"
        _pp_shape(g.shapes, "round", x, y - h / 2, w, h, fill="#ffffff", line=pl["color"], line_pt=1.3, name="外框")
        name_box = _pp_shape(g.shapes, "round", x, y - h / 2, wl, h, fill=pl["color"], line=pl["color"], line_pt=1.3,
                             name="縣市")
        _pp_fill_text(name_box.text_frame, pl["name"], fs, True, pl["text_color"], "l", "m", margins=(h * 1.05, 0, 0.02, 0))
        circle = _pp_shape(g.shapes, "oval", x + h / 2 - h * 0.36, y - h * 0.36, h * 0.72, h * 0.72, fill="#ffffff",
                           name="名次")
        _pp_fill_text(circle.text_frame, pl["rank"], fs * 0.72, True, pl["rank_color"], "c", "m")
        _pp_text(g.shapes, x + wl, y - h / 2, w - wl, h, pl["value"], fs, True,
                 "#111827" if pl["ranked"] else "#9ca3af", "c", "m", name="數值")

    title, sub = scene["title"]                               # 標題與副標放同一個文字方塊(兩個 run),方便整段修改
    tb = slide.shapes.add_textbox(Inches(X(0.3)), Inches(Y(H - 0.75) - 0.35), Inches(X(W - 0.6)), Inches(0.7))
    tb.name = "標題"
    tf = tb.text_frame
    tf.word_wrap = False
    tf.vertical_anchor = MSO_ANCHOR.MIDDLE
    para = tf.paragraphs[0]
    para.alignment = PP_ALIGN.CENTER
    for text, size, bold in ((title, 27 * s, True), ("  " + sub if sub else "", 15 * s, False)):
        if not text: continue
        run = para.add_run()
        run.text = text
        run.font.size, run.font.bold, run.font.name = Pt(size), bold, PPT_FONT
        run.font.color.rgb = _pp_rgb("#111827")

    for color, text, lx in scene["legend"]:
        _pp_shape(slide.shapes, "round", X(lx), Y(H - 1.23) - 0.05 * s, 1.5 * s, 0.1 * s, fill=color, name=f"圖例色條 {text}")
        _pp_text(slide.shapes, X(lx), Y(H - 1.55) - 0.15, 1.5 * s, 0.3, text, 15 * s, name=f"圖例 {text}")
    if scene["unit"]:
        _pp_text(slide.shapes, X(W - 0.45) - 4.0, Y(H - 1.6) - 0.15, 4.0, 0.3, scene["unit"], 9 * s, False, "#4b5563",
                 "r", name="單位說明")
    if scene["note"]:
        _pp_text(slide.shapes, X(W - 0.45) - 6.0, Y(0.28) - 0.15, 6.0, 0.3, scene["note"], 11 * s, False, "#374151",
                 "r", name="註解")
    prs.save(path)

def _rank_figure(input_df, store, title, subtitle, unit_note, footnote, order, top_n, bottom_n,
                 c_top, c_bottom, c_other):
    """回傳 (matplotlib 圖, scene);scene 供匯出原生 PPTX 使用"""
    store = merge_table_into_store(input_df, store)
    entries = _county_numeric_entries(store)
    return render_rank_infographic(
        entries, title, subtitle, unit_note, footnote, descending=(order == INFO_ORDERS[0]), top_n=int(top_n), bottom_n=int(bottom_n),
        colors=(c_top or INFO_DEFAULT_COLORS[0], c_bottom or INFO_DEFAULT_COLORS[1], c_other or INFO_DEFAULT_COLORS[2]))

def preview_rank_infographic(*args):
    fig, _ = _rank_figure(*args)
    path = _tmp_path(".png")
    fig.savefig(path, dpi=110, facecolor="white")
    return path

def export_rank_infographic(*args, fmt="png"):
    """args = 預覽用的參數 + [透明背景];PNG/SVG/PPTX(單頁,頁面比例與圖相同)"""
    *render_args, transparent = args
    fig, scene = _rank_figure(*render_args)
    rank_title = (render_args[2] or "").strip() or "各縣市排名圖"   # args[2] = 標題欄
    path = _named_path(rank_title, f".{fmt}")
    if fmt == "pptx":
        build_rank_pptx(scene, path)
    else:
        fig.savefig(path, format=fmt, dpi=200, transparent=bool(transparent),
                    facecolor="none" if transparent else "white")
    return gr.update(value=path, visible=True)

# ===============================================
# 8. Gradio 介面
# ===============================================

# 注意:事件上的 js 會先於 fn 執行,且它的回傳值就是 fn 的輸入。
# 所以這裡必須把收到的參數原封不動回傳,否則 fn 會拿到全部 None(下拉選單的選擇都會失效)。
resize_js = """
(...args) => {
    const trigger = () => window.dispatchEvent(new Event('resize'));
    trigger();
    setTimeout(trigger, 100);
    setTimeout(trigger, 300);
    setTimeout(trigger, 600);
    setTimeout(trigger, 1000);
    return args;
}
"""

custom_css = """
/* ── Google Fonts ── */
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;500;600;700&family=Space+Mono:wght@400;700&display=swap');

/* ── CSS Variables ── */
:root {
    --bg:        #f4f6fb;
    --surface:   #ffffff;
    --surface2:  #f8f9fc;
    --border:    #e2e6f0;
    --accent:    #3b72f6;
    --accent2:   #6c47e8;
    --success:   #059669;
    --warn:      #d97706;
    --danger:    #dc2626;
    --text:      #1e2435;
    --text-dim:  #6b7a99;
    --radius:    10px;
    --radius-lg: 16px;
    --font:      'Noto Sans TC', 'Microsoft JhengHei', sans-serif;
    --mono:      'Space Mono', monospace;
}

/* ── Global Reset ── */
*, *::before, *::after { box-sizing: border-box; }

body {
    font-family: var(--font);
    background: var(--bg) !important;
    color: var(--text) !important;
    margin: 0;
}

/* ── Gradio container ── */
.gradio-container {
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 auto !important;
    background: transparent !important;
    padding: 0 16px 32px !important;
}

/* ── Hero Banner ── */
.tw-hero {
    background: linear-gradient(135deg, #2b6cb0 0%, #3182ce 100%);
    color: #ffffff;
    padding: 18px 28px;
    text-align: center;
    border-radius: 12px;
    margin-bottom: 16px;
}
.tw-hero h1 {
    font-size: 1.4rem;
    font-weight: 700;
    margin: 0 0 6px;
    color: #fff;
}
.tw-hero p {
    color: rgba(255,255,255,0.88);
    margin: 0;
    font-size: 0.88rem;
}
.tw-formats {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    justify-content: center;
    margin-top: 10px;
}
.tw-fmt {
    background: rgba(72, 187, 120, 0.2);
    border: 1px solid #68d391;
    color: #68d391;
    padding: 2px 10px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.78rem;
    font-family: var(--mono);
}

/* ── Section Labels ── */
.tw-section-label {
    font-size: 0.7rem;
    font-weight: 700;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    color: var(--accent);
    margin: 20px 0 8px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.tw-section-label::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--border);
}

/* ── Status Badge ── */
.tw-status {
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 10px 14px;
    font-size: 0.82rem;
    color: var(--text-dim);
    font-family: var(--mono);
    min-height: 40px;
    display: flex;
    align-items: center;
}

/* ── Gradio overrides – Inputs ── */
.gradio-container input,
.gradio-container select,
.gradio-container textarea,
.gradio-container .gr-input,
.gradio-container .gr-dropdown {
    background: #fff !important;
    border: 1px solid var(--border) !important;
    border-radius: var(--radius) !important;
    color: var(--text) !important;
    font-family: var(--font) !important;
}
.gradio-container label,
.gradio-container .gr-form > label,
.gradio-container span.svelte-1gfkn6j {
    color: var(--text-dim) !important;
    font-size: 0.8rem !important;
    font-weight: 500 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.6px !important;
}

/* ── Accordion ── */
.gradio-container details,
.gradio-container .gr-accordion {
    background: #fff !important;
    border: 1px solid var(--border) !important;
    border-radius: var(--radius) !important;
    margin-bottom: 8px !important;
    overflow: hidden !important;
    box-shadow: 0 1px 4px rgba(0,0,0,0.05) !important;
}
.gradio-container details > summary,
.gradio-container .gr-accordion > summary {
    padding: 12px 16px !important;
    font-weight: 600 !important;
    font-size: 0.85rem !important;
    color: var(--text) !important;
    cursor: pointer !important;
    background: transparent !important;
    border-bottom: 1px solid transparent !important;
    transition: background 0.15s !important;
}
.gradio-container details[open] > summary {
    border-bottom-color: var(--border) !important;
    background: rgba(255,255,255,0.02) !important;
}
.gradio-container details > .gr-form,
.gradio-container details > div {
    padding: 14px 16px !important;
}

/* ── Buttons ── */
.gradio-container button.primary,
.gradio-container .gr-button-primary {
    background: linear-gradient(135deg, var(--accent) 0%, var(--accent2) 100%) !important;
    border: none !important;
    border-radius: var(--radius) !important;
    color: #fff !important;
    font-weight: 600 !important;
    font-family: var(--font) !important;
    font-size: 0.85rem !important;
    transition: opacity 0.2s, transform 0.1s !important;
    box-shadow: 0 2px 12px rgba(79,142,247,0.3) !important;
}
.gradio-container button.primary:hover { opacity: 0.88 !important; transform: translateY(-1px) !important; }
.gradio-container button.secondary,
.gradio-container .gr-button-secondary {
    background: #fff !important;
    border: 1px solid var(--border) !important;
    border-radius: var(--radius) !important;
    color: var(--text-dim) !important;
    font-weight: 500 !important;
    font-family: var(--font) !important;
    font-size: 0.85rem !important;
    transition: border-color 0.2s, color 0.2s !important;
}
.gradio-container button.secondary:hover {
    border-color: var(--accent) !important;
    color: var(--accent) !important;
}

/* ── Tabs ── */
.gradio-container .tab-nav {
    background: #fff !important;
    border-bottom: 1px solid var(--border) !important;
    padding: 0 8px !important;
    gap: 2px !important;
}
.gradio-container .tab-nav button {
    border-radius: 8px 8px 0 0 !important;
    border: none !important;
    padding: 10px 16px !important;
    font-size: 0.82rem !important;
    font-weight: 500 !important;
    color: var(--text-dim) !important;
    background: transparent !important;
    transition: color 0.15s, background 0.15s !important;
}
.gradio-container .tab-nav button.selected {
    color: var(--accent) !important;
    background: rgba(79,142,247,0.1) !important;
    border-bottom: 2px solid var(--accent) !important;
}
.gradio-container .tabitem {
    background: #fff !important;
    border: 1px solid var(--border) !important;
    border-top: none !important;
    border-radius: 0 0 var(--radius-lg) var(--radius-lg) !important;
    padding: 16px !important;
}

/* ── File Upload ── */
.gradio-container .upload-container,
.gradio-container .file-preview {
    background: var(--surface2) !important;
    border: 2px dashed var(--border) !important;
    border-radius: var(--radius-lg) !important;
    transition: border-color 0.2s !important;
}
.gradio-container .upload-container:hover {
    border-color: var(--accent) !important;
}

/* ── 核取方塊/選項鈕:全域 input 樣式會把勾選記號蓋掉,看起來永遠是空的,這裡補回 ── */
.gradio-container input[type=checkbox],
.gradio-container input[type=radio] {
    accent-color: var(--accent);
}
.gradio-container input[type=checkbox]:checked {
    background-color: var(--accent) !important;
    border-color: var(--accent) !important;
    background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.2 4.2 6.5 9.9 3.8 7.2 2.7 8.3l3.8 3.8 6.8-6.8z'/%3E%3C/svg%3E") !important;
    background-size: 100% 100% !important;
}
.gradio-container input[type=radio]:checked {
    background-color: var(--accent) !important;
    border-color: var(--accent) !important;
    background-image: radial-gradient(circle, #fff 0 32%, transparent 36%) !important;
}

/* ── Radio Buttons ── */
.gradio-container .gr-radio-row label {
    background: var(--surface2) !important;
    border: 1px solid var(--border) !important;
    border-radius: 8px !important;
    padding: 6px 12px !important;
    cursor: pointer !important;
    font-size: 0.82rem !important;
    text-transform: none !important;
    letter-spacing: 0 !important;
}
.gradio-container .gr-radio-row input:checked + label,
.gradio-container .gr-radio-row label:has(input:checked) {
    border-color: var(--accent) !important;
    background: rgba(79,142,247,0.1) !important;
    color: var(--accent) !important;
}

/* ── Dataframe ── */
.gradio-container .gr-dataframe table {
    background: var(--surface2) !important;
}
.gradio-container .gr-dataframe th {
    background: var(--surface) !important;
    color: var(--text-dim) !important;
    font-size: 0.78rem !important;
    font-weight: 600 !important;
    letter-spacing: 0.5px !important;
    text-transform: uppercase !important;
    border-bottom: 1px solid var(--border) !important;
}
.gradio-container .gr-dataframe td {
    color: var(--text) !important;
    border-bottom: 1px solid var(--border) !important;
    font-size: 0.84rem !important;
}

/* ── Slider ── */
.gradio-container .gr-slider input[type=range]::-webkit-slider-thumb {
    background: var(--accent) !important;
}
.gradio-container .gr-slider input[type=range]::-webkit-slider-runnable-track {
    background: var(--border) !important;
}

/* ── Quick Help Cards ── */
.tw-help-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-top: 10px;
}
.tw-help-card {
    background: #fff;
    border: 1px solid var(--border);
    box-shadow: 0 1px 4px rgba(0,0,0,0.05);
    border-radius: 8px;
    padding: 10px 12px;
}
.tw-help-card .icon { font-size: 1.1rem; margin-bottom: 4px; }
.tw-help-card .title { font-size: 0.72rem; font-weight: 700; color: var(--text); margin-bottom: 2px; }
.tw-help-card .desc  { font-size: 0.68rem; color: var(--text-dim); line-height: 1.4; }

/* ── Stats placeholder ── */
.tw-stats-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 4px 12px;
    padding: 10px 16px;
    color: #9baabf;
    text-align: center;
}
.tw-stats-placeholder .icon { font-size: 1.1rem; opacity: 0.6; }
.tw-stats-placeholder .msg  { font-size: 0.88rem; }
.tw-stats-placeholder .sub  { font-size: 0.78rem; opacity: 0.7; }

/* ── Misc ── */
.gradio-container .gr-markdown p { color: var(--text-dim) !important; font-size: 0.85rem !important; }
.gradio-container .gr-markdown strong { color: var(--text) !important; }
.gradio-container .gr-markdown h3 { color: var(--text) !important; font-size: 0.95rem !important; }
.gradio-container .gr-textbox textarea { background: #fff !important; color: var(--text) !important; border: 1px solid var(--border) !important; border-radius: var(--radius) !important; font-family: var(--mono) !important; font-size: 0.8rem !important; }
.gradio-container .gr-plot { background: transparent !important; border: none !important; }
.gradio-container .block { background: transparent !important; border: none !important; }

/* ── Desktop: 側欄跟著捲動,切到下方圖表時仍能換指標 ── */
@media (min-width: 769px) {
    .tw-sidebar { position: sticky; top: 12px; align-self: flex-start; }
}

/* ── 下載檔案區塊緊湊顯示 ── */
.tw-download { margin-top: 4px; }

/* ── Mobile: stack sidebar above main area ── */
@media (max-width: 768px) {
    .gradio-container .tw-main-row {
        flex-direction: column !important;
    }
    .gradio-container .tw-main-row > div {
        min-width: 100% !important;
    }
}

/* ── Footer ── */
.tw-footer {
    text-align: center;
    padding: 24px 0 8px;
    border-top: 1px solid var(--border);
    margin-top: 20px;
    color: var(--text-dim);
    font-size: 0.78rem;
}
"""


with gr.Blocks(title="臺灣 Open Data 視覺化儀表板", css=custom_css, fill_width=True) as demo:

    # ── Hero Header ──────────────────────────────────────
    gr.HTML("""
    <div class="tw-hero">
        <h1>🇹🇼 臺灣開放資料視覺化平台</h1>
        <p>上傳資料,一鍵生成互動地圖、趨勢分析、排行榜與動態 GIF</p>
        <div class="tw-formats">
            <span class="tw-fmt">.csv</span>
            <span class="tw-fmt">.xlsx</span>
            <span class="tw-fmt">.json</span>
            <span class="tw-fmt">.xml</span>
        </div>
    </div>
    """)

    current_df = gr.State()
    map_level_state = gr.State(value="county")
    all_numeric_cols_state = gr.State(value=[])

    with gr.Row(equal_height=False, elem_classes="tw-main-row"):

        # ── LEFT SIDEBAR:上傳與全域指標(桌面版固定在視窗內)──
        with gr.Column(scale=1, min_width=300, elem_classes="tw-sidebar"):

            gr.HTML('<div class="tw-section-label">① 資料上傳</div>')
            file_input = gr.File(
                label="拖曳或點擊上傳檔案",
                file_types=[".csv", ".xlsx", ".json", ".xml"],
                file_count="single"
            )
            status_box = gr.Textbox(
                label="系統狀態",
                interactive=False,
                placeholder="⏳ 等待上傳資料檔案...",
                max_lines=4
            )
            if os.path.exists("sample_data.csv"):
                gr.Examples(
                    examples=[["sample_data.csv"]],
                    inputs=file_input,
                    label="👇 沒有資料?點擊載入範例(縣市出生死亡統計)"
                )

            gr.HTML('<div class="tw-section-label">② 主要分析指標</div>')
            col_selector = gr.Dropdown(label="指標(所有分頁共用)", interactive=True)

            with gr.Accordion("💡 快速說明", open=False):
                gr.HTML("""
                <div class="tw-help-grid">
                    <div class="tw-help-card">
                        <div class="icon">📍</div>
                        <div class="title">地區欄位</div>
                        <div class="desc">支援縣市名稱或鄉鎮區,系統自動偵測層級;對不上地圖的名稱會在狀態列提示</div>
                    </div>
                    <div class="tw-help-card">
                        <div class="icon">📅</div>
                        <div class="title">時間格式</div>
                        <div class="desc">民國年 112/01、西元年 2023-01、季度 2023Q1</div>
                    </div>
                    <div class="tw-help-card">
                        <div class="icon">🎨</div>
                        <div class="title">分級方式</div>
                        <div class="desc">數值差距大時選「分位數」,避免少數縣市把其他地區壓成同一色</div>
                    </div>
                    <div class="tw-help-card">
                        <div class="icon">💡</div>
                        <div class="title">互動操作</div>
                        <div class="desc">所有圖表可縮放、點選圖例切換顯示</div>
                    </div>
                </div>
                """)

        # ── RIGHT MAIN AREA:各功能控制項直接放在對應分頁 ──
        with gr.Column(scale=5):

            with gr.Accordion("📊 數據總覽", open=True):
                stats_year_selector = gr.Dropdown(
                    label="統計年份", choices=["全部"], value="全部", interactive=True
                )
                stats_output = gr.HTML(
                    value="""
                    <div class="tw-stats-placeholder">
                        <div class="icon">📊</div>
                        <div class="msg">上傳資料後將自動顯示統計摘要</div>
                        <div class="sub">支援縣市層級、鄉鎮市區層級資料集</div>
                    </div>
                    """
                )

            with gr.Tabs() as tabs:
                with gr.Tab("🗺️ 互動地圖", id="tab_map"):
                    with gr.Row():
                        time_selector = gr.Dropdown(label="時間點", choices=["全部"], value="全部", interactive=True)
                        agg_method = gr.Radio(["加總", "平均", "最大值"], label="聚合方式", value="加總")
                    with gr.Row():
                        color_scheme = gr.Dropdown(
                            ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"],
                            label="地圖配色", value="紅色系 🔴"
                        )
                        class_mode = gr.Dropdown(CLASS_MODES, label="分級方式", value=CLASS_MODES[0])
                    show_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)— 關閉後本島會放大", value=True)
                    with gr.Row():
                        btn_map = gr.Button("🔄 更新地圖", variant="primary", scale=2)
                        btn_export_map = gr.Button("💾 匯出 PNG", variant="secondary")
                        btn_export_html = gr.Button("🌐 匯出互動 HTML", variant="secondary")
                    map_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download")
                    map_output = gr.Plot()

                with gr.Tab("📝 手動填寫", id="tab_manual"):
                    gr.HTML('<div style="margin-bottom:12px; color: var(--text-dim, #8892a4); font-size:0.85rem;">✍️ 做簡報用的縣市/鄉鎮地圖:選層級與範圍,在表格填寫或從 Excel 整批貼上。<b>全部填數字</b>→漸層色階;<b>填文字</b>→相同文字同一顏色並附圖例。匯出可選透明背景,直接貼進 PPT。</div>')
                    manual_store = gr.State({})
                    with gr.Row():
                        with gr.Column(scale=1, min_width=300):
                            with gr.Row():
                                manual_level = gr.Radio(MANUAL_LEVELS, label="層級", value=MANUAL_LEVELS[0])
                                manual_scope = gr.Dropdown([MANUAL_NATIONAL] + DEFAULT_COUNTIES, label="鄉鎮範圍(鄉鎮市區層級才有作用:全國 或 單一縣市)",
                                                           value="臺北市")
                            manual_input_df = gr.Dataframe(
                                value=manual_table("縣市", MANUAL_NATIONAL, {}),
                                headers=[MANUAL_COL_NAME, MANUAL_COL_CONTENT],
                                col_count=(2, "fixed"), static_columns=[0], interactive=True, max_height=520
                            )
                            with gr.Accordion("📋 從 Excel 批次貼上", open=False):
                                manual_paste = gr.Textbox(
                                    label="每行一個:「名稱 內容」(Tab、逗號、空白皆可;選了單一縣市可只寫鄉鎮名)",
                                    placeholder="臺北市\t85\n高雄市\t66\n花蓮縣\t10", lines=6
                                )
                                btn_paste = gr.Button("⬆️ 匯入到表格", variant="secondary")
                            with gr.Row():
                                btn_ex_cat = gr.Button("縣市範例:分區", size="sm", variant="secondary")
                                btn_ex_num = gr.Button("縣市範例:數值", size="sm", variant="secondary")
                            with gr.Row():
                                btn_ex_town_num = gr.Button("鄉鎮範例:數值", size="sm", variant="secondary")
                                btn_ex_town_cat = gr.Button("鄉鎮範例:分類", size="sm", variant="secondary")
                                btn_clear = gr.Button("🗑️ 清空目前範圍", size="sm", variant="secondary")
                        with gr.Column(scale=2, min_width=340):
                            with gr.Row():
                                manual_title = gr.Textbox(label="圖表標題(留空自動命名)", placeholder="臺灣各縣市")
                                manual_color = gr.Dropdown(MANUAL_COLORS, label="數值模式配色", value=MANUAL_COLORS[1])
                            with gr.Row():
                                manual_label_mode = gr.Dropdown(MANUAL_LABEL_MODES, label="標籤內容", value=MANUAL_LABEL_MODES[0])
                                manual_label_size = gr.Slider(6, 24, value=12, step=1, label="標籤字級")
                            with gr.Row():
                                manual_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)", value=True,
                                                             info="更改後地圖會自動更新")
                                manual_transparent = gr.Checkbox(label="匯出透明背景(PNG/SVG)", value=False,
                                                                 info="只影響下載的檔案;匯出 PNG 後下方會用棋盤格預覽")
                            with gr.Row():
                                btn_manual_map = gr.Button("🗺️ 生成分布圖", variant="primary", scale=2)
                                btn_manual_png = gr.Button("💾 匯出 PNG", variant="secondary")
                                btn_manual_svg = gr.Button("📥 匯出 SVG", variant="secondary")
                            with gr.Row():
                                btn_manual_pptx = gr.Button("📊 匯出 PPTX(一頁一個縣市)", variant="primary", scale=2)
                                manual_ppt_overview = gr.Checkbox(label="含縣市總覽頁", value=True)
                                manual_ppt_table = gr.Checkbox(label="附資料表", value=True)
                            with gr.Accordion("🖼️ 標註框版型(一頁總覽)", open=False):
                                gr.HTML('<div style="color:var(--text-dim,#8892a4);font-size:0.82rem;margin-bottom:6px;">地圖放中間,有填內容的地區上色、左右長出標註框(像簡報上「各縣市主要受損作物」那種)。<b>一格可以寫好幾行</b>:用換行或「;」分隔,例如「農糧:茶;畜牧:豬」。離島會畫成地圖下方的小圖;同一個縣市的多項資訊請寫在同一格。標註框只取表格<b>前幾個</b>(預設 12 個,可在下面調整),多的會在右下角列出。</div>')
                                with gr.Row():
                                    anno_sub = gr.Textbox(label="副標(大字,可留空)", placeholder="農業產物及民間設施損失累計 4 億 4,623 萬元")
                                    anno_note = gr.Textbox(label="註記(左下角,可留空)", placeholder="資料來源:農業部農業統計年報(2025 年)")
                                with gr.Row():
                                    anno_color = gr.ColorPicker(label="標註主色", value="#2F5D8A")
                                    anno_max = gr.Slider(4, 16, value=12, step=1, label="最多標註幾個地區")
                                    btn_anno_pptx = gr.Button("📊 匯出 PPTX(標註框版型)", variant="primary", scale=2)
                                anno_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download")
                            manual_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download")
                            manual_preview = gr.Image(label="匯出預覽(棋盤格=透明)", visible=False, interactive=False,
                                                      type="filepath")
                            manual_map_output = gr.Plot()

                with gr.Tab("🏅 圖解排名", id="tab_rank"):
                    gr.HTML('<div style="margin-bottom:12px; color: var(--text-dim, #8892a4); font-size:0.85rem;">📰 資訊圖表風格的縣市排名圖(臺灣本島依名次著色、兩側膠囊標籤附名次與數值)。資料取自「手動填寫」分頁的<b>縣市數值</b>。</div>')
                    with gr.Row():
                        with gr.Column(scale=1, min_width=300):
                            rk_title = gr.Textbox(label="標題", value="各縣市出生率排名")
                            rk_sub = gr.Textbox(label="副標(例如年份,會接在標題後面)", value="(2023年)")
                            rk_unit = gr.Textbox(label="單位說明(圖例右側的小字)", value="每千人的新生人口數(‰)")
                            rk_note = gr.Textbox(label="註解(右下角)", value="")
                            rk_order = gr.Radio(INFO_ORDERS, label="名次排序", value=INFO_ORDERS[0])
                            with gr.Row():
                                rk_topn = gr.Slider(0, 11, value=5, step=1, label="標示前幾名(0=不標)")
                                rk_botn = gr.Slider(0, 11, value=5, step=1, label="標示後幾名(0=不標)")
                            with gr.Row():
                                rk_c1 = gr.ColorPicker(label="排名前段", value=INFO_DEFAULT_COLORS[0])
                                rk_c2 = gr.ColorPicker(label="排名後段", value=INFO_DEFAULT_COLORS[1])
                                rk_c3 = gr.ColorPicker(label="其他", value=INFO_DEFAULT_COLORS[2])
                            rk_transparent = gr.Checkbox(label="匯出透明背景(PNG/SVG)", value=False)
                            btn_rk_example = gr.Button("載入範例數值(取自出生率圖,未查證)", size="sm", variant="secondary")
                        with gr.Column(scale=2, min_width=340):
                            with gr.Row():
                                btn_rk = gr.Button("🏅 生成圖解", variant="primary", scale=2)
                                btn_rk_png = gr.Button("💾 PNG", variant="secondary")
                                btn_rk_svg = gr.Button("📥 SVG", variant="secondary")
                                btn_rk_pptx = gr.Button("📊 PPTX", variant="secondary")
                            rk_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download")
                            rk_preview = gr.Image(label="預覽", interactive=False, type="filepath")

                with gr.Tab("🆚 雙指標對比", id="tab_dual"):
                    with gr.Row():
                        dual_time_selector = gr.Dropdown(label="時間點", choices=["全部"], value="全部", interactive=True)
                        col_selector_2 = gr.Dropdown(label="第二個分析指標(搭配主要指標)")
                    btn_dual = gr.Button("🆚 產生雙指標地圖", variant="primary")
                    dual_map_output = gr.Plot()

                with gr.Tab("⚖️ 時間差異", id="tab_compare"):
                    with gr.Row():
                        comp_time1 = gr.Dropdown(label="基準年份(舊)")
                        comp_time2 = gr.Dropdown(label="比較年份(新)")
                        diff_mode = gr.Radio(DIFF_MODES, label="差異呈現", value=DIFF_MODES[0])
                    btn_compare = gr.Button("📊 產生差異地圖", variant="primary")
                    compare_output = gr.Plot()

                with gr.Tab("🏆 排行榜", id="tab_ranking") as tab_ranking:
                    with gr.Row():
                        top_n_selector = gr.Dropdown(choices=["10", "20", "50", "全部"], value="10", label="顯示名次數")
                        rank_order = gr.Radio(RANK_ORDERS, label="排序", value=RANK_ORDERS[0])
                    btn_ranking = gr.Button("🔄 更新排行榜", variant="primary")
                    ranking_output = gr.Plot()

                with gr.Tab("📈 趨勢分析", id="tab_trend") as tab_trend:
                    with gr.Row():
                        trend_region = gr.Dropdown(
                            label="觀察地區(可多選比較)",
                            choices=["全國總計"], value=["全國總計"],
                            multiselect=True, interactive=True
                        )
                        line_metric = gr.Dropdown(
                            label="輔助分析線(單一地區時顯示)",
                            choices=["年增率 (%)", "3年移動平均"], value="3年移動平均"
                        )
                    btn_trend = gr.Button("🔄 更新趨勢圖", variant="primary")
                    trend_output = gr.Plot()

                with gr.Tab("🎬 動畫", id="tab_gif"):
                    with gr.Row():
                        start_time = gr.Dropdown(label="▶ 起始時間", interactive=True)
                        end_time = gr.Dropdown(label="⏸ 結束時間", interactive=True)
                    with gr.Row():
                        sort_order = gr.Radio(
                            ["時間正序 (舊 → 新)", "時間反序 (新 → 舊)"],
                            label="播放順序", value="時間正序 (舊 → 新)"
                        )
                        fps_slider = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="播放速度(FPS)")
                    btn_gif = gr.Button("🎬 開始產生 GIF(配色、分級、離島設定沿用互動地圖分頁)", variant="primary")
                    gif_output = gr.Image(label="GIF 動畫預覽")

                with gr.Tab("📋 原始資料", id="tab_data"):
                    with gr.Row():
                        btn_export_csv = gr.Button("📥 匯出為 CSV", size="sm", variant="secondary", scale=0)
                        csv_output = gr.File(label="下載 CSV 檔案", visible=False, elem_classes="tw-download")
                    data_preview = gr.Dataframe(wrap=True)

    # ── Footer ───────────────────────────────────────────
    gr.HTML("""
    <div class="tw-footer">
        <p>💡 所有圖表皆可互動操作,點擊圖例可隱藏/顯示資料系列 &nbsp;·&nbsp; 地圖可拖曳縮放 &nbsp;·&nbsp; 灰色地區代表資料中沒有該地區</p>
        <p style="margin-top:6px; opacity:0.5;">Made with ❤️ for Taiwan Open Data Community &nbsp;·&nbsp; 資料來源請自行確認授權</p>
    </div>
    """)

    # ── Event Bindings ────────────────────────────────────
    # 樣式是照淺色主題設計的;使用者系統為深色模式時會變成深底+白卡片的混搭,所以固定成淺色
    demo.load(fn=None, js="""() => {
        const force = () => document.body.classList.remove('dark');
        force();
        new MutationObserver(force).observe(document.body, {attributes: true, attributeFilter: ['class']});
    }""")

    map_inputs = [current_df, col_selector, time_selector, agg_method, color_scheme, class_mode,
                  show_islands, map_level_state, all_numeric_cols_state]

    file_input.change(
        fn=process_uploaded_file, inputs=file_input,
        outputs=[current_df, status_box, col_selector, time_selector, trend_region, data_preview,
                 start_time, end_time, map_level_state, stats_year_selector,
                 stats_output, comp_time1, comp_time2, col_selector_2, all_numeric_cols_state,
                 top_n_selector, fps_slider, dual_time_selector]
    ).then(
        fn=auto_render_map, inputs=[current_df, all_numeric_cols_state, map_level_state],
        outputs=map_output, js=resize_js
    )
    stats_year_selector.change(
        fn=generate_stats_summary,
        inputs=[current_df, all_numeric_cols_state, stats_year_selector],
        outputs=stats_output
    )
    btn_map.click(fn=generate_map, inputs=map_inputs, outputs=[map_output, tabs], js=resize_js)
    btn_export_map.click(fn=export_static_map, inputs=map_inputs, outputs=map_file)
    btn_export_html.click(fn=export_html_map, inputs=map_inputs, outputs=map_file)
    btn_trend.click(
        fn=generate_trend_chart,
        inputs=[current_df, col_selector, trend_region, line_metric, all_numeric_cols_state],
        outputs=[trend_output, tabs], js=resize_js
    )
    btn_ranking.click(
        fn=generate_ranking,
        inputs=[current_df, col_selector, time_selector, top_n_selector, rank_order, all_numeric_cols_state],
        outputs=[ranking_output, tabs], js=resize_js
    )
    btn_compare.click(
        fn=generate_comparison_map,
        inputs=[current_df, col_selector, comp_time1, comp_time2, diff_mode, map_level_state, all_numeric_cols_state],
        outputs=[compare_output, tabs], js=resize_js
    )
    btn_dual.click(
        fn=generate_dual_map,
        inputs=[current_df, col_selector, col_selector_2, dual_time_selector, map_level_state, all_numeric_cols_state],
        outputs=[dual_map_output, tabs], js=resize_js
    )
    btn_gif.click(
        fn=generate_map_gif,
        inputs=[current_df, col_selector, color_scheme, class_mode, fps_slider, start_time, end_time,
                sort_order, show_islands, map_level_state, all_numeric_cols_state],
        outputs=[gif_output, tabs]
    )
    btn_export_csv.click(fn=export_csv, inputs=current_df, outputs=csv_output)
    col_selector.change(fn=lambda c: gr.update(value=default_agg(c)), inputs=col_selector, outputs=agg_method)

    def _quiet(fn):
        """切換分頁時自動出圖;還沒上傳資料或條件不足就保持原樣,不跳錯誤視窗"""
        def run(df, *args):
            if df is None: return gr.update(), gr.update()
            try: return fn(df, *args)
            except gr.Error: return gr.update(), gr.update()
        return run
    tab_ranking.select(
        fn=_quiet(generate_ranking),
        inputs=[current_df, col_selector, time_selector, top_n_selector, rank_order, all_numeric_cols_state],
        outputs=[ranking_output, tabs], js=resize_js
    )
    tab_trend.select(
        fn=_quiet(generate_trend_chart),
        inputs=[current_df, col_selector, trend_region, line_metric, all_numeric_cols_state],
        outputs=[trend_output, tabs], js=resize_js
    )
    manual_opts = [manual_input_df, manual_level, manual_scope, manual_title, manual_color,
                   manual_label_mode, manual_label_size, manual_islands]
    btn_manual_map.click(fn=generate_manual_distribution_map, inputs=manual_opts, outputs=manual_map_output)
    btn_manual_png.click(fn=lambda *a: export_manual_with_preview(*a, fmt="png"),
                         inputs=manual_opts + [manual_transparent], outputs=[manual_file, manual_preview])
    btn_manual_svg.click(fn=lambda *a: export_manual_with_preview(*a, fmt="svg"),
                         inputs=manual_opts + [manual_transparent], outputs=[manual_file, manual_preview])
    # 顯示選項一改就重畫(不用再按「生成分布圖」)
    for comp in (manual_islands, manual_label_mode, manual_color):
        comp.change(fn=regenerate_manual_map, inputs=manual_opts, outputs=manual_map_output)
    manual_label_size.release(fn=regenerate_manual_map, inputs=manual_opts, outputs=manual_map_output)
    btn_manual_pptx.click(
        fn=export_manual_pptx,
        inputs=[manual_input_df, manual_store, manual_title, manual_color, manual_label_mode, manual_label_size,
                manual_ppt_overview, manual_ppt_table],
        outputs=manual_file)
    btn_anno_pptx.click(
        fn=export_annotation_pptx,
        inputs=[manual_input_df, manual_level, manual_scope, manual_title, anno_sub, anno_note, anno_color,
                anno_max, manual_islands],
        outputs=anno_file)
    rank_opts = [manual_input_df, manual_store, rk_title, rk_sub, rk_unit, rk_note, rk_order, rk_topn, rk_botn,
                 rk_c1, rk_c2, rk_c3]
    btn_rk.click(fn=preview_rank_infographic, inputs=rank_opts, outputs=rk_preview)
    for btn, fmt in ((btn_rk_png, "png"), (btn_rk_svg, "svg"), (btn_rk_pptx, "pptx")):
        btn.click(fn=lambda *a, f=fmt: export_rank_infographic(*a, fmt=f), inputs=rank_opts + [rk_transparent],
                  outputs=rk_file)
    btn_rk_example.click(fn=load_rank_example, inputs=manual_store,
                         outputs=[manual_store, manual_level, manual_scope, manual_input_df]
                         ).then(fn=preview_rank_infographic, inputs=rank_opts, outputs=rk_preview)
    # 範圍選單一直顯示、不再用 visible 切換:Gradio 6 前端在元件由隱藏變可見時不會清掉它的載入狀態,
    # 選單會一直蓋著「processing」不能點。層級/範圍改變都只更新表格(若回頭更新 manual_scope 本身,還會無限觸發 change)
    for trigger in (manual_level.change, manual_scope.change):
        trigger(fn=manual_table, inputs=[manual_level, manual_scope, manual_store], outputs=manual_input_df)
    manual_input_df.input(fn=on_manual_table_input, inputs=[manual_input_df, manual_store], outputs=manual_store)
    btn_paste.click(fn=import_pasted_text, inputs=[manual_paste, manual_level, manual_scope, manual_store],
                    outputs=[manual_store, manual_input_df])
    for btn, kind in ((btn_ex_cat, "分區"), (btn_ex_num, "數值")):
        btn.click(fn=lambda store, k=kind: load_manual_example(k, store), inputs=manual_store,
                  outputs=[manual_store, manual_level, manual_scope, manual_input_df])
    for btn, kind in ((btn_ex_town_num, "數值"), (btn_ex_town_cat, "分類")):
        btn.click(fn=lambda store, k=kind: load_town_example(k, store), inputs=manual_store,
                  outputs=[manual_store, manual_level, manual_scope, manual_input_df])
    btn_clear.click(fn=clear_manual, inputs=[manual_level, manual_scope, manual_store],
                    outputs=[manual_store, manual_input_df])

if __name__ == "__main__":
    demo.queue().launch()