import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { apiGet, apiPatch, apiUpload } from "../../lib/api";
import { ModelSelector } from "../ModelSelector";

interface ParserOption {
  id: string;
  name: string;
  description: string;
}

interface FileUploadPanelProps {
  sessionId: number;
  parsedData: Record<string, unknown>;
  onParsedDataUpdate: (dataType: string, data: unknown) => void;
  onGoToStep2: () => void;
  onSessionExpired: () => Promise<number>;
}

interface UploadZone {
  type: "questions" | "answers";
  label: string;
  description: string;
  placeholder: string;
  icon: ReactNode;
}

function IconQuestions() {
  return (
    <svg width="46" height="50" viewBox="0 0 978 1074" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g transform="translate(0,1074) scale(0.1,-0.1)" fill="var(--color-primary)" stroke="none">
        <path d="M1250 9981 c-47 -4 -95 -12 -107 -19 -12 -7 -31 -12 -43 -12 -30 0 -214 -93 -285 -143 -58 -42 -138 -129 -193 -212 -62 -93 -102 -176 -136 -280 -15 -46 -16 -393 -16 -4035 1 -3444 3 -3990 15 -4025 8 -22 15 -46 15 -52 0 -12 58 -136 83 -178 77 -129 166 -230 259 -291 83 -56 199 -114 225 -114 11 0 24 -5 30 -11 6 -6 42 -16 80 -22 103 -15 6212 -22 6358 -7 127 13 182 29 283 79 79 39 87 43 147 83 87 57 217 215 275 335 18 37 37 76 41 85 5 10 13 34 18 55 6 21 15 56 20 78 13 51 15 2541 2 2549 -11 7 -21 -17 -21 -48 0 -12 -4 -26 -9 -31 -4 -6 -13 -28 -19 -50 -10 -38 -17 -60 -47 -145 -7 -19 -34 -102 -60 -185 -27 -82 -54 -164 -62 -182 -7 -17 -13 -36 -13 -42 0 -33 -69 -147 -124 -203 -89 -93 -1239 -951 -1291 -964 -74 -19 -153 18 -181 84 -8 20 -25 66 -36 102 -69 218 -82 258 -93 290 -27 77 -75 230 -75 241 0 6 -6 25 -13 42 -8 18 -22 59 -31 92 -10 33 -24 75 -32 93 -8 18 -14 40 -14 50 0 9 -7 30 -15 46 -8 15 -15 38 -15 50 -1 11 -7 32 -15 46 -8 14 -14 34 -15 45 0 11 -7 33 -15 49 -8 15 -15 34 -15 42 0 7 -6 28 -14 46 -7 18 -22 60 -31 93 -10 33 -24 74 -31 90 -7 17 -17 64 -23 106 -12 89 -2 166 36 274 13 39 28 84 33 100 4 17 18 57 30 90 12 33 24 74 27 90 3 17 9 35 13 40 4 6 17 44 30 85 13 41 28 89 35 105 6 17 20 57 30 90 10 33 24 74 32 92 7 17 13 38 13 46 0 8 7 28 15 43 8 16 15 36 15 44 0 8 12 47 26 85 14 39 29 84 33 100 5 17 13 41 19 55 5 14 38 113 73 220 34 107 68 209 76 227 7 17 13 38 13 46 0 8 7 28 15 43 8 16 15 39 15 51 0 12 4 24 9 28 5 3 13 20 16 38 7 32 36 124 54 169 5 12 51 151 102 308 50 157 98 299 106 317 7 17 13 38 13 46 0 8 7 28 15 43 8 16 15 36 15 45 0 9 7 30 15 45 8 16 15 39 15 51 0 12 4 24 9 27 5 3 12 22 16 42 3 20 12 50 19 68 8 17 21 56 31 86 9 30 23 71 30 90 7 19 41 123 75 230 34 107 69 210 76 228 8 18 14 41 14 50 0 10 4 22 9 28 6 5 14 27 20 49 5 22 15 56 22 75 6 19 17 51 24 70 7 19 18 51 24 70 7 19 16 49 21 65 8 28 23 74 41 120 4 11 31 94 59 185 29 91 59 179 66 197 8 17 14 38 14 46 0 8 7 28 15 43 8 16 15 36 15 45 0 9 7 30 15 45 8 16 15 36 15 44 0 8 12 47 26 85 14 39 28 79 31 90 3 11 26 50 51 87 116 175 344 252 537 182 108 -39 100 -49 103 111 1 77 -2 158 -7 180 -23 96 -32 127 -40 143 -4 9 -16 35 -27 57 -66 142 -238 343 -339 397 -114 61 -196 98 -217 98 -7 0 -33 8 -58 18 -42 16 -229 17 -3175 18 -1722 1 -3168 -2 -3215 -5z m5477 -1517 c44 -28 67 -60 87 -118 16 -46 16 -52 -1 -95 -21 -57 -44 -89 -86 -115 l-32 -21 -2315 -3 c-1273 -2 -2335 0 -2359 3 -34 5 -53 17 -91 54 -40 40 -48 54 -53 98 -3 28 -1 68 4 88 12 42 87 121 122 128 12 2 1073 4 2357 3 l2335 -1 32 -21z m-955 -2046 c167 -36 188 -272 31 -352 -29 -15 -191 -16 -1903 -16 -1816 0 -1872 1 -1908 19 -20 10 -45 28 -55 39 -30 33 -57 94 -57 129 0 64 56 148 118 176 21 9 450 13 1847 17 1001 3 1834 4 1850 2 17 -2 51 -8 77 -14z m-635 -2035 c57 -27 101 -80 109 -130 11 -75 -3 -127 -46 -171 -74 -77 31 -72 -1611 -72 -1598 0 -1540 -2 -1603 56 -78 73 -83 191 -12 269 64 69 -58 64 1613 65 1420 0 1515 -1 1550 -17z m512 -1926 c25 -12 59 -39 75 -60 28 -35 31 -46 31 -105 -1 -73 -19 -114 -68 -152 -66 -52 11 -50 -1868 -50 -1599 0 -1750 1 -1794 17 -148 50 -190 206 -84 312 63 64 -72 59 1879 60 l1785 0 44 -22z"/>
        <path d="M7977 8628 c-28 -28 -45 -70 -111 -273 -44 -132 -85 -254 -93 -272 -7 -17 -13 -38 -13 -46 0 -8 -7 -28 -15 -43 -8 -16 -15 -38 -15 -50 0 -11 -4 -24 -9 -30 -6 -5 -14 -27 -20 -49 -10 -43 -26 -91 -48 -142 -7 -17 -13 -38 -13 -47 0 -8 -6 -30 -14 -48 -7 -18 -21 -58 -31 -88 -9 -30 -22 -71 -29 -90 -8 -19 -21 -60 -30 -90 -10 -30 -24 -71 -31 -90 -7 -19 -34 -102 -60 -185 -26 -82 -54 -165 -61 -183 -8 -18 -14 -39 -14 -46 0 -8 -7 -27 -15 -42 -8 -16 -15 -39 -15 -51 0 -12 -4 -24 -9 -28 -5 -3 -13 -20 -16 -38 -7 -32 -36 -124 -54 -169 -5 -12 -57 -171 -117 -353 -59 -181 -113 -344 -121 -362 -7 -17 -13 -36 -13 -42 0 -6 -16 -57 -35 -113 -19 -57 -40 -119 -46 -138 -7 -19 -17 -51 -24 -70 -7 -19 -28 -82 -45 -140 -18 -58 -38 -118 -45 -135 -6 -16 -20 -57 -30 -90 -10 -33 -24 -74 -32 -92 -7 -17 -13 -38 -13 -46 0 -8 -7 -28 -15 -43 -8 -16 -15 -36 -15 -45 0 -9 -7 -30 -15 -45 -8 -16 -15 -37 -15 -47 0 -9 -4 -25 -9 -35 -9 -17 -34 -89 -51 -147 -8 -29 -18 -59 -45 -135 -7 -19 -41 -123 -75 -230 -35 -107 -69 -209 -77 -227 -7 -17 -13 -38 -13 -46 0 -8 -7 -28 -15 -43 -8 -16 -15 -37 -15 -46 0 -10 -6 -32 -14 -50 -7 -18 -22 -57 -31 -87 l-18 -54 23 -19 c12 -10 34 -21 49 -24 14 -3 42 -11 61 -19 19 -7 62 -21 95 -30 33 -10 69 -21 80 -25 11 -5 74 -25 140 -45 66 -21 134 -44 152 -51 17 -8 36 -14 43 -14 6 0 53 -14 103 -30 51 -17 115 -38 142 -46 28 -9 64 -22 82 -30 17 -8 36 -14 43 -14 15 0 102 -28 147 -47 17 -7 37 -13 45 -13 7 0 51 -14 98 -30 46 -17 94 -30 105 -30 29 0 53 28 61 71 4 19 10 39 14 44 4 6 17 44 30 85 13 41 29 89 36 107 8 17 14 38 14 46 0 8 7 28 15 43 8 16 15 36 15 45 0 9 7 30 15 45 8 16 15 38 15 49 0 12 4 25 9 30 4 6 13 28 19 50 5 22 16 56 23 75 6 19 17 51 24 70 7 19 18 51 24 70 7 19 16 49 21 65 8 28 17 55 45 135 7 19 28 82 45 140 18 58 39 119 47 137 7 17 13 40 13 50 0 10 4 23 9 28 6 6 14 28 20 50 10 43 26 91 48 142 7 17 13 37 13 45 0 7 12 45 26 83 14 39 29 84 34 100 4 17 31 98 60 180 28 83 54 164 57 180 3 17 9 35 13 40 4 6 24 64 45 130 21 66 44 134 51 152 8 17 14 40 14 50 0 10 4 23 9 29 4 5 13 27 19 49 5 22 16 56 23 75 6 19 17 51 24 70 7 19 20 60 29 90 10 30 24 71 31 90 7 19 34 103 60 185 27 83 54 164 62 182 7 17 13 40 13 50 0 10 4 23 9 29 6 5 14 27 20 49 10 45 29 101 42 127 5 10 13 34 18 55 10 41 27 90 48 140 7 17 13 38 13 47 0 8 6 30 14 48 7 18 21 58 31 88 9 30 23 71 30 90 7 19 34 103 60 185 27 83 54 164 62 182 7 17 13 38 13 46 0 8 7 28 15 43 8 16 15 36 15 45 0 9 7 30 15 45 8 16 15 39 15 51 0 12 4 24 9 27 5 3 12 22 16 42 3 20 12 50 19 68 31 73 46 134 46 187 0 49 -3 58 -32 86 -19 18 -60 41 -95 52 -33 11 -72 25 -85 30 -12 5 -70 24 -128 41 -58 18 -114 36 -125 41 -11 4 -31 11 -45 14 -14 3 -41 12 -60 20 -19 7 -82 28 -140 45 -58 18 -119 39 -137 47 -17 7 -38 13 -46 13 -8 0 -28 7 -43 15 -16 8 -37 15 -46 15 -10 0 -32 6 -50 14 -97 41 -200 70 -266 73 -71 5 -73 4 -105 -29z"/>
        <path d="M6465 3218 c4 -24 14 -55 21 -70 8 -15 14 -34 14 -42 0 -9 6 -30 14 -48 19 -46 76 -225 76 -239 0 -6 6 -25 13 -42 16 -37 74 -218 83 -260 3 -15 10 -30 15 -33 5 -3 9 -16 9 -29 0 -45 25 -39 104 27 22 18 57 43 141 102 28 19 64 47 80 62 17 14 42 33 58 42 15 9 27 20 27 24 0 4 4 8 9 8 13 0 294 213 295 224 1 4 -28 17 -64 29 -36 11 -79 26 -97 33 -17 8 -36 14 -42 14 -14 0 -194 58 -238 77 -17 7 -38 13 -47 13 -8 0 -30 6 -48 14 -18 8 -80 29 -138 47 -58 17 -119 38 -137 46 -17 7 -39 13 -50 13 -10 1 -29 7 -43 15 -14 8 -33 14 -43 15 -16 0 -18 -5 -12 -42z"/>
      </g>
    </svg>
  );
}

function IconAnswers() {
  return (
    <svg width="50" height="50" viewBox="0 0 1038 1056" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g transform="translate(0,1056) scale(0.1,-0.1)" fill="var(--color-primary)" stroke="none">
        <path d="M3175 10349 c-78 -9 -172 -22 -285 -39 -77 -11 -199 -41 -310 -75 -25 -7 -62 -17 -83 -20 -20 -4 -40 -11 -43 -16 -3 -5 -13 -9 -22 -9 -9 0 -29 -6 -44 -14 -15 -8 -40 -17 -57 -21 -17 -4 -33 -11 -36 -16 -4 -5 -13 -9 -20 -9 -30 0 -331 -147 -426 -208 -15 -9 -50 -30 -78 -47 -28 -16 -51 -33 -51 -37 0 -5 -5 -8 -10 -8 -9 0 -70 -43 -165 -115 -144 -111 -360 -318 -461 -444 -72 -90 -164 -218 -207 -290 -18 -29 -40 -65 -49 -80 -27 -41 -178 -347 -178 -360 0 -6 -4 -19 -10 -29 -10 -18 -35 -84 -50 -137 -5 -16 -17 -55 -26 -85 -9 -30 -22 -83 -30 -116 -8 -34 -18 -74 -24 -89 -5 -14 -10 -41 -10 -58 0 -18 -6 -63 -14 -102 -21 -99 -30 -413 -17 -585 10 -136 19 -202 42 -310 6 -25 14 -63 18 -85 17 -82 84 -299 112 -365 6 -14 17 -38 24 -55 14 -34 145 -298 160 -323 46 -77 173 -266 192 -287 10 -11 45 -54 78 -95 91 -115 338 -355 435 -423 l25 -17 -4 -573 -4 -572 29 -34 c36 -43 98 -72 139 -64 29 6 82 37 170 100 22 15 42 31 43 36 2 4 8 7 13 7 5 0 51 31 102 68 50 38 139 102 197 142 125 88 221 156 235 168 6 4 33 23 60 42 28 18 76 53 108 78 53 40 62 44 105 39 46 -4 120 -18 212 -38 195 -44 801 -44 1002 0 46 10 134 28 208 41 25 5 51 10 59 12 21 5 25 -29 8 -66 -62 -131 -146 -420 -168 -579 -4 -34 -13 -91 -18 -127 -6 -36 -11 -177 -11 -314 0 -242 6 -315 41 -491 6 -27 14 -70 19 -95 5 -25 18 -76 30 -115 11 -38 25 -87 31 -108 5 -21 13 -45 18 -55 5 -9 23 -55 41 -102 38 -97 125 -282 170 -355 16 -27 33 -57 37 -65 22 -46 168 -250 248 -345 291 -345 655 -616 1080 -805 89 -40 116 -50 129 -50 8 0 17 -4 21 -9 3 -5 19 -12 36 -16 17 -4 42 -13 57 -21 15 -8 34 -14 43 -14 9 0 30 -7 45 -15 16 -8 37 -15 48 -15 10 0 39 -7 65 -15 104 -32 155 -45 181 -45 15 0 47 -7 70 -15 23 -8 63 -15 89 -15 25 0 62 -5 81 -11 92 -28 667 -27 850 1 97 14 265 48 360 72 94 24 117 19 230 -52 38 -24 267 -157 280 -163 8 -4 29 -16 45 -27 17 -11 37 -23 45 -27 8 -3 33 -18 55 -32 58 -37 78 -49 95 -58 8 -4 69 -39 135 -78 167 -98 188 -107 232 -99 43 8 117 77 125 117 6 30 2 165 -12 415 -6 95 -10 275 -10 399 l0 226 129 126 c205 199 320 342 462 571 25 41 96 169 111 200 15 31 39 84 92 202 9 20 16 42 16 50 0 8 4 18 8 23 11 13 48 130 93 295 7 25 16 65 20 90 4 25 12 72 18 105 34 195 47 442 32 585 -35 330 -23 263 -112 625 -6 22 -14 44 -20 50 -5 5 -9 17 -9 27 0 9 -6 32 -14 50 -8 18 -22 53 -32 78 -21 55 -135 288 -170 350 -47 82 -154 238 -221 325 -5 6 -18 23 -30 38 -26 33 -156 178 -194 216 -56 56 -218 200 -274 244 -87 67 -256 182 -317 215 -27 15 -75 42 -106 59 -56 32 -63 36 -92 47 -8 3 -22 10 -30 15 -30 19 -150 71 -164 71 -8 0 -17 4 -20 9 -3 4 -36 18 -73 30 -37 13 -82 29 -100 37 -17 8 -40 14 -50 14 -10 0 -23 4 -29 10 -5 5 -30 14 -54 19 -56 12 -125 30 -168 43 -19 5 -57 14 -85 18 -29 4 -79 13 -112 19 -319 57 -699 57 -1040 0 -33 -5 -89 -14 -124 -20 -36 -6 -73 -15 -82 -20 -22 -11 -66 -12 -73 -1 -3 5 6 30 19 58 26 55 53 124 64 169 4 17 13 40 19 52 7 12 12 32 12 45 0 13 4 28 9 33 5 6 14 33 19 60 5 28 14 70 20 95 44 180 57 312 57 560 0 248 -13 380 -57 560 -6 25 -15 68 -20 95 -5 28 -14 54 -19 60 -5 5 -9 20 -9 33 0 13 -6 38 -14 55 -8 18 -16 41 -19 52 -8 27 -35 105 -47 130 -5 11 -16 38 -26 60 -154 366 -419 730 -729 1005 -215 192 -546 397 -830 516 -16 7 -46 20 -67 28 -20 9 -41 16 -47 16 -6 0 -19 4 -29 10 -24 14 -100 40 -142 49 -19 4 -45 13 -57 19 -12 7 -34 12 -48 12 -14 0 -35 5 -46 11 -11 6 -41 14 -67 19 -26 5 -67 13 -92 18 -112 24 -182 35 -275 44 -140 13 -544 18 -640 7z m534 -299 c172 -15 344 -46 491 -87 95 -26 244 -74 277 -89 17 -8 36 -14 41 -14 6 0 23 -7 39 -15 15 -8 54 -26 86 -40 126 -55 213 -101 295 -156 24 -16 46 -29 50 -29 4 0 23 -13 42 -30 19 -16 39 -29 43 -30 11 0 159 -113 217 -164 88 -78 266 -262 326 -336 148 -183 277 -400 359 -600 14 -36 30 -74 34 -85 31 -72 87 -270 111 -390 46 -231 46 -638 0 -870 -23 -115 -85 -329 -115 -400 -7 -16 -28 -66 -46 -110 -38 -91 -77 -168 -121 -237 -24 -39 -42 -53 -106 -84 -261 -125 -413 -215 -577 -341 -157 -122 -200 -159 -305 -263 -109 -110 -205 -220 -293 -342 -87 -118 -88 -118 -241 -168 -78 -25 -256 -67 -361 -86 -112 -20 -382 -43 -495 -43 -112 0 -390 22 -475 39 -142 27 -212 41 -241 50 -82 26 -101 18 -369 -175 -49 -36 -112 -80 -140 -99 -62 -42 -186 -132 -202 -145 -46 -40 -164 -111 -174 -105 -9 5 -10 98 -4 398 5 215 8 408 8 428 -2 70 -21 105 -86 155 -122 93 -164 130 -302 268 -238 237 -437 536 -546 820 -13 33 -27 64 -31 70 -4 5 -8 18 -8 28 0 10 -6 33 -13 50 -27 62 -50 155 -93 377 -13 66 -17 144 -18 345 0 265 10 370 50 511 8 28 14 59 14 69 0 19 25 100 47 152 7 17 13 40 13 51 0 12 4 23 9 26 5 3 12 18 15 33 7 31 12 42 83 188 274 569 757 1017 1368 1270 22 9 55 23 73 31 18 8 37 14 43 14 6 0 25 6 42 13 18 8 57 21 87 30 30 9 78 23 107 31 28 9 60 16 69 16 9 0 40 6 68 14 189 54 587 80 855 56z m3711 -3813 c198 -29 383 -73 535 -127 33 -12 69 -24 80 -26 19 -6 33 -11 115 -47 19 -9 67 -30 105 -47 39 -17 77 -35 85 -40 8 -5 47 -26 85 -46 39 -20 77 -43 86 -50 8 -8 18 -14 22 -14 3 0 36 -21 74 -46 257 -176 476 -383 643 -609 47 -64 130 -185 130 -190 0 -2 11 -20 24 -39 20 -30 119 -226 146 -291 56 -133 115 -330 143 -480 22 -113 47 -347 47 -428 0 -93 -27 -345 -47 -437 -32 -150 -69 -289 -91 -343 -7 -16 -12 -33 -12 -38 0 -5 -4 -17 -10 -27 -5 -9 -21 -46 -36 -82 -74 -184 -208 -408 -345 -578 -65 -80 -305 -323 -372 -376 -82 -65 -80 -56 -78 -319 0 -127 4 -316 7 -418 6 -156 5 -187 -8 -191 -7 -3 -54 19 -103 49 -50 29 -126 74 -170 99 -100 56 -115 65 -305 179 -85 51 -170 96 -188 100 -36 7 -159 -12 -168 -26 -3 -5 -15 -9 -26 -9 -12 0 -44 -6 -72 -14 -71 -20 -182 -42 -313 -61 -159 -24 -576 -25 -734 -1 -232 35 -479 96 -631 155 -87 34 -119 47 -165 68 -91 40 -156 72 -218 108 -33 19 -69 39 -80 45 -79 40 -274 182 -380 276 -265 234 -475 504 -617 794 -48 99 -88 190 -88 202 0 6 -6 24 -14 41 -33 75 -90 280 -102 367 -3 19 -12 73 -20 120 -20 111 -14 560 10 690 63 347 163 603 360 922 169 271 466 565 767 759 112 72 116 74 174 104 28 14 57 29 65 34 38 22 121 61 180 85 36 15 74 31 85 36 11 4 29 11 40 14 11 3 47 15 80 26 144 52 343 100 497 120 42 5 101 14 130 19 82 14 555 6 678 -12z"/>
        <path d="M3274 8781 c-49 -4 -95 -11 -101 -14 -7 -4 -31 -11 -55 -16 -181 -38 -386 -169 -522 -334 -66 -79 -176 -280 -176 -320 0 -9 -6 -31 -14 -49 -25 -59 -38 -131 -46 -258 -9 -131 2 -386 18 -417 5 -10 13 -39 16 -65 4 -26 11 -50 17 -53 5 -4 9 -15 9 -25 0 -32 111 -254 139 -280 4 -3 24 -27 45 -53 191 -239 483 -367 832 -367 106 0 164 5 205 16 32 9 65 14 73 11 14 -6 101 -134 180 -264 31 -52 42 -63 64 -64 118 -2 477 3 484 7 4 3 -17 41 -47 85 -30 44 -55 81 -55 83 0 4 -128 199 -140 213 -5 7 -10 15 -10 18 0 8 -44 69 -52 73 -5 2 -8 14 -8 26 0 15 26 50 74 98 110 113 198 257 240 393 10 33 23 71 29 85 10 27 21 98 36 251 12 121 -11 396 -37 446 -7 12 -12 31 -12 42 0 32 -74 196 -122 269 -15 24 -28 45 -28 48 0 18 -218 234 -236 234 -7 0 -14 4 -16 9 -4 13 -170 99 -228 118 -143 49 -357 70 -556 54z m351 -405 c17 -8 41 -19 55 -24 83 -35 110 -53 179 -121 73 -72 151 -184 151 -217 0 -9 5 -25 11 -36 6 -11 19 -51 30 -89 25 -90 27 -372 4 -446 -9 -26 -23 -73 -33 -103 -9 -30 -28 -73 -42 -95 -13 -22 -30 -49 -37 -60 -7 -11 -16 -28 -19 -37 -4 -11 -17 -18 -33 -18 -19 0 -32 10 -49 38 -29 49 -39 64 -89 140 -24 35 -43 65 -43 68 0 5 -35 56 -60 86 -13 16 -35 18 -252 18 -226 0 -238 -1 -238 -19 0 -10 8 -29 18 -42 10 -13 42 -62 71 -109 29 -47 74 -119 101 -160 91 -140 131 -210 125 -220 -10 -16 -156 -12 -211 6 -156 51 -267 132 -345 251 -76 115 -100 187 -128 390 -18 124 13 323 71 459 77 182 275 335 458 355 90 10 269 1 305 -15z"/>
        <path d="M6750 4921 c-5 -11 -10 -29 -10 -40 0 -11 -4 -22 -9 -26 -5 -3 -12 -19 -16 -36 -4 -17 -13 -42 -21 -57 -8 -15 -14 -34 -14 -42 0 -9 -4 -20 -9 -25 -5 -6 -14 -26 -19 -45 -6 -19 -24 -71 -41 -115 -16 -44 -35 -96 -42 -115 -7 -19 -18 -49 -26 -67 -7 -17 -13 -37 -13 -45 0 -8 -4 -18 -9 -24 -5 -5 -14 -25 -20 -44 -11 -38 -61 -178 -79 -223 -7 -16 -12 -34 -12 -41 0 -6 -4 -16 -9 -21 -5 -6 -14 -26 -19 -45 -6 -19 -20 -60 -32 -90 -11 -30 -30 -82 -41 -115 -11 -33 -25 -69 -30 -80 -5 -11 -13 -33 -18 -50 -5 -16 -19 -55 -31 -85 -41 -106 -51 -135 -57 -155 -3 -11 -11 -34 -19 -52 -8 -17 -14 -38 -14 -46 0 -9 -4 -18 -9 -22 -5 -3 -12 -19 -16 -36 -4 -17 -13 -42 -21 -57 -8 -15 -14 -34 -14 -43 0 -8 -4 -19 -9 -25 -5 -5 -14 -25 -19 -44 -6 -19 -20 -60 -32 -90 -12 -30 -24 -64 -27 -75 -2 -11 -9 -30 -15 -42 -6 -12 -8 -29 -5 -37 6 -14 35 -16 216 -16 228 0 235 1 247 58 3 15 10 36 15 47 11 25 39 104 46 130 3 11 11 34 19 52 8 17 14 40 14 51 0 12 4 23 9 26 5 3 14 25 20 49 6 25 19 54 28 65 18 21 25 21 405 23 347 2 389 0 412 -15 14 -9 26 -21 26 -27 0 -6 6 -25 14 -42 8 -18 16 -41 19 -52 9 -31 66 -197 76 -220 5 -11 12 -29 15 -40 2 -11 11 -38 19 -60 l15 -40 219 0 218 0 -1 35 c-1 34 -24 107 -44 142 -6 10 -10 23 -10 29 0 6 -6 25 -14 42 -8 18 -24 61 -37 97 -44 128 -50 145 -58 165 -5 11 -19 49 -32 85 -12 36 -25 70 -29 75 -4 6 -10 21 -13 35 -3 14 -15 50 -27 80 -12 30 -26 69 -31 85 -5 17 -13 39 -18 50 -5 11 -19 47 -30 80 -11 33 -30 85 -41 115 -12 30 -26 71 -32 90 -5 19 -14 39 -19 45 -5 5 -9 18 -9 30 0 11 -6 29 -14 40 -7 11 -16 31 -19 45 -3 14 -15 50 -27 80 -12 30 -26 71 -32 90 -5 19 -14 39 -19 45 -5 5 -9 15 -9 23 0 8 -6 28 -14 45 -8 18 -16 41 -19 52 -3 11 -15 45 -27 75 -12 30 -26 71 -32 90 -5 19 -14 39 -19 45 -5 5 -9 15 -9 23 0 8 -6 28 -14 45 -8 18 -16 41 -19 52 -10 39 -46 127 -58 141 -9 11 -56 14 -250 14 -225 0 -239 -1 -249 -19z m293 -590 c5 -24 27 -90 46 -136 15 -38 33 -90 41 -124 5 -18 13 -38 19 -44 6 -6 11 -20 11 -30 0 -10 6 -33 14 -50 8 -18 16 -41 19 -52 11 -38 67 -200 78 -220 5 -11 11 -33 12 -50 l2 -30 -287 -3 c-273 -2 -288 -1 -288 16 0 10 5 23 11 29 6 6 14 26 19 44 9 38 27 88 47 136 7 17 13 35 13 41 0 5 7 23 15 38 8 16 15 38 15 50 0 11 4 24 9 30 4 5 20 45 34 89 31 96 47 143 58 170 5 11 18 49 29 85 12 36 24 72 27 80 6 20 49 -32 56 -69z"/>
      </g>
    </svg>
  );
}

// ── Custom date picker ────────────────────────────────────────────────────────

const MONTH_NAMES = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const DAY_ABBR = ["Su","Mo","Tu","We","Th","Fr","Sa"];

function DatePicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
  const parsed = value ? value.split("-").map(Number) : null;
  const now = new Date();

  const [open, setOpen] = useState(false);
  const [viewYear, setViewYear] = useState(parsed ? parsed[0] : now.getFullYear());
  const [viewMonth, setViewMonth] = useState(parsed ? parsed[1] - 1 : now.getMonth());
  const ref = useRef<HTMLDivElement>(null);

  // Sync calendar view when value changes externally
  useEffect(() => {
    if (value) {
      const [y, m] = value.split("-").map(Number);
      setViewYear(y);
      setViewMonth(m - 1);
    }
  }, [value]);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const todayMs = (() => { const d = new Date(); d.setHours(0,0,0,0); return d.getTime(); })();
  const selectedMs = value ? new Date(value + "T00:00:00").getTime() : null;

  const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
  const startDow = new Date(viewYear, viewMonth, 1).getDay();
  const cells: (number | null)[] = [
    ...Array(startDow).fill(null),
    ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
  ];
  while (cells.length % 7 !== 0) cells.push(null);

  const fmt = () => {
    if (!value) return "選擇日期";
    const [y, m, d] = value.split("-");
    return `${y}年${+m}月${+d}日`;
  };

  const selectDay = (day: number) => {
    const v = `${viewYear}-${String(viewMonth + 1).padStart(2,"0")}-${String(day).padStart(2,"0")}`;
    onChange(v);
    setOpen(false);
  };

  const prevMonth = () => {
    if (viewMonth === 0) { setViewMonth(11); setViewYear(y => y - 1); }
    else setViewMonth(m => m - 1);
  };

  const nextMonth = () => {
    if (viewMonth === 11) { setViewMonth(0); setViewYear(y => y + 1); }
    else setViewMonth(m => m + 1);
  };

  const goToday = () => {
    const t = new Date();
    const v = `${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;
    onChange(v);
    setOpen(false);
  };

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => setOpen(v => !v)}
        className={`flex items-center gap-2 px-3 py-1.5 rounded-xl border text-sm transition-all ${
          open
            ? "border-[var(--color-primary)] shadow-sm bg-[var(--color-surface)]"
            : "border-[var(--color-border)] bg-[var(--color-surface)] hover:border-[var(--color-primary)]/60"
        }`}
      >
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
        </svg>
        <span className={value ? "text-[var(--color-text)]" : "text-[var(--color-text-muted)]"}>{fmt()}</span>
        {value && (
          <span
            role="button"
            onClick={(e) => { e.stopPropagation(); onChange(""); }}
            className="ml-0.5 text-[var(--color-text-muted)] hover:text-[var(--color-text)] text-xs leading-none"
          >✕</span>
        )}
      </button>

      {open && (
        <div className="absolute z-50 top-full mt-2 left-0 card shadow-2xl p-3 w-60 animate-fade-in-up" style={{ animationDuration: "0.1s" }}>
          {/* Header */}
          <div className="flex items-center justify-between mb-2">
            <button type="button" onClick={prevMonth} className="p-1 rounded-lg hover:bg-[var(--color-border)] transition-colors text-[var(--color-text-muted)]">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M15 18l-6-6 6-6"/></svg>
            </button>
            <span className="text-xs font-bold text-[var(--color-text)] tracking-wide">
              {viewYear}年 {MONTH_NAMES[viewMonth]}
            </span>
            <button type="button" onClick={nextMonth} className="p-1 rounded-lg hover:bg-[var(--color-border)] transition-colors text-[var(--color-text-muted)]">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M9 18l6-6-6-6"/></svg>
            </button>
          </div>

          {/* Day headers */}
          <div className="grid grid-cols-7 mb-1">
            {DAY_ABBR.map(d => (
              <div key={d} className="text-center text-[9px] font-bold text-[var(--color-text-muted)] py-0.5">{d}</div>
            ))}
          </div>

          {/* Calendar grid */}
          <div className="grid grid-cols-7 gap-y-0.5">
            {cells.map((day, i) => {
              if (!day) return <div key={i} />;
              const ms = new Date(viewYear, viewMonth, day).getTime();
              const isSel = ms === selectedMs;
              const isTod = ms === todayMs;
              return (
                <button
                  key={i}
                  type="button"
                  onClick={() => selectDay(day)}
                  className={`w-7 h-7 mx-auto rounded-lg text-[11px] font-medium transition-all ${
                    isSel
                      ? "bg-[var(--color-primary)] text-white shadow-sm"
                      : isTod
                      ? "ring-1 ring-[var(--color-primary)] text-[var(--color-primary)] font-bold"
                      : "hover:bg-[var(--color-border)] text-[var(--color-text)]"
                  }`}
                >
                  {day}
                </button>
              );
            })}
          </div>

          {/* Today shortcut */}
          <div className="mt-2 pt-2 border-t border-[var(--color-border)] flex justify-center">
            <button type="button" onClick={goToday} className="text-[11px] font-semibold text-[var(--color-primary)] hover:underline">
              今天
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────

const zones: UploadZone[] = [
  {
    type: "questions",
    label: "Test Questions",
    description: "Upload assessment",
    placeholder: "例如：國中三年級數學期中考，共 20 題選擇題和 5 題計算題",
    icon: <IconQuestions />,
  },
  {
    type: "answers",
    label: "Answers",
    description: "Upload answers as （PDF / CSV / 圖片）",
    placeholder:
      "例如：A 卷的考生作答一覽表（CSV 第 1 列為題號標題，第 2 列為標準答案，第 3 列起為學生）",
    icon: <IconAnswers />,
  },
];

export function FileUploadPanel({
  sessionId,
  parsedData,
  onParsedDataUpdate,
  onGoToStep2,
  onSessionExpired,
}: FileUploadPanelProps) {
  const [files, setFiles] = useState<Record<string, File[]>>({
    questions: [],
    answers: [],
  });
  const [descriptions, setDescriptions] = useState<Record<string, string>>({
    questions: "",
    answers: "",
  });
  const [analyzing, setAnalyzing] = useState<Record<string, boolean>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [model, setModel] = useState("gpt-5.4");
  const [quizDate, setQuizDate] = useState<string>("");
  const [title, setTitle] = useState<string>("");
  const [parsers, setParsers] = useState<ParserOption[]>([]);
  const [parserByZone, setParserByZone] = useState<Record<string, string>>({
    questions: "auto",
    answers: "auto",
  });
  const [advancedOpen, setAdvancedOpen] = useState<Record<string, boolean>>({
    questions: false,
    answers: false,
  });
  const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});

  useEffect(() => {
    apiGet<{ parsers: ParserOption[] }>("/api/parsers")
      .then((res) => setParsers(res.parsers))
      .catch(() => {});
  }, []);

  useEffect(() => {
    apiGet<{ title?: string; quiz_date?: string | null }>(`/api/sessions/${sessionId}`)
      .then((s) => {
        if (s.title) setTitle(s.title);
        if (s.quiz_date) setQuizDate(s.quiz_date);
      })
      .catch(() => {});
  }, [sessionId]);

  const handleFileSelect = (type: string, selected: FileList | null) => {
    if (!selected) return;
    setFiles((prev) => ({ ...prev, [type]: Array.from(selected) }));
    setErrors((prev) => ({ ...prev, [type]: "" }));
  };

  const handleDrop = (type: string, e: React.DragEvent) => {
    e.preventDefault();
    handleFileSelect(type, e.dataTransfer.files);
  };

  const handleAnalyze = async (type: string) => {
    const typeFiles = files[type];
    if (!typeFiles.length) return;

    setAnalyzing((prev) => ({ ...prev, [type]: true }));
    setErrors((prev) => ({ ...prev, [type]: "" }));

    const buildFormData = () => {
      const formData = new FormData();
      formData.append("data_type", type);
      formData.append("description", descriptions[type] || "");
      formData.append("model", model);
      formData.append("parser", parserByZone[type] || "auto");
      for (const f of typeFiles) {
        formData.append("files", f);
      }
      return formData;
    };

    try {
      let res: { data: unknown };
      try {
        res = await apiUpload<{ data: unknown }>(`/api/sessions/${sessionId}/upload`, buildFormData());
      } catch (err) {
        // The session was likely wiped server-side (e.g. a bulk delete from the
        // dashboard) — create a fresh one and retry transparently.
        if (err instanceof Error && err.message === "Session not found") {
          const newSessionId = await onSessionExpired();
          res = await apiUpload<{ data: unknown }>(`/api/sessions/${newSessionId}/upload`, buildFormData());
        } else {
          throw err;
        }
      }
      if (type === "answers") {
        const data = res.data as {
          student_answers?: unknown;
          teacher_answers?: unknown;
        };
        if (data.student_answers) onParsedDataUpdate("student_answers", data.student_answers);
        if (data.teacher_answers) onParsedDataUpdate("teacher_answers", data.teacher_answers);
        onParsedDataUpdate("answers", res.data);
      } else {
        onParsedDataUpdate(type, res.data);
      }
    } catch (err: unknown) {
      setErrors((prev) => ({
        ...prev,
        [type]: err instanceof Error ? err.message : "Analysis failed",
      }));
    } finally {
      setAnalyzing((prev) => ({ ...prev, [type]: false }));
    }
  };

  const hasAnyParsedData = Object.keys(parsedData).length > 0;
  const isAnyAnalyzing = Object.values(analyzing).some(Boolean);

  const handleDateChange = (val: string) => {
    setQuizDate(val);
    if (val) {
      apiPatch(`/api/sessions/${sessionId}`, { quiz_date: val }).catch(() => {});
    }
  };

  const handleTitleBlur = () => {
    const trimmed = title.trim();
    if (!trimmed) return;
    apiPatch(`/api/sessions/${sessionId}`, { title: trimmed }).catch(() => {});
  };

  return (
    <div className="space-y-6">
      {/* Info note */}
      <p className="text-xs text-[var(--color-text-muted)] text-center">
        支援任意格式檔案（PDF、圖片、文字檔等）。若檔案中包含圖片、圖表或示意圖，AI 會自動將其轉換為文字描述，以確保後續分析完整準確。
      </p>

      {/* Quiz name + date row */}
      <div className="flex items-center gap-4 flex-wrap">
        <div className="flex items-center gap-2">
          <label className="text-sm font-medium text-[var(--color-text)] whitespace-nowrap">
            Quiz name
          </label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onBlur={handleTitleBlur}
            onKeyDown={(e) => {
              if (e.key === "Enter") (e.target as HTMLInputElement).blur();
            }}
            placeholder="Quiz 1"
            className="input !py-1.5 text-sm w-40"
          />
        </div>
        <div className="flex items-center gap-2">
          <label className="text-sm font-medium text-[var(--color-text)] whitespace-nowrap">
            Quiz date
          </label>
          <DatePicker value={quizDate} onChange={handleDateChange} />
        </div>
      </div>

      {/* Upload zones */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {zones.map((zone) => {
          const zoneData = parsedData[zone.type] as Record<string, unknown> | undefined;
          const isAnalyzing = analyzing[zone.type];
          const hasFiles = files[zone.type].length > 0;
          const hasParsed = !!zoneData;

          return (
            <div
              key={zone.type}
              className={`card p-6 transition-all ${hasParsed ? "border-[var(--color-success)]/50" : ""}`}
              onDragOver={(e) => e.preventDefault()}
              onDrop={(e) => handleDrop(zone.type, e)}
            >
              <div className="text-center mb-3">
                <h3 className="font-display text-lg font-semibold text-[var(--color-text)]">
                  {zone.label}
                </h3>
                <p className="text-sm text-[var(--color-text-muted)]">{zone.description}</p>
              </div>

              {/* Advanced options toggle: optional AI context + parser choice,
                  collapsed by default so the empty-state card isn't dominated
                  by fields most teachers never touch. */}
              <button
                type="button"
                onClick={() =>
                  setAdvancedOpen((prev) => ({ ...prev, [zone.type]: !prev[zone.type] }))
                }
                className="flex items-center gap-1 text-xs text-[var(--color-text-muted)] hover:text-[var(--color-primary)] transition-colors mb-3"
              >
                <svg
                  width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true"
                  style={{ transform: advancedOpen[zone.type] ? "rotate(90deg)" : "none", transition: "transform 0.15s" }}
                >
                  <path d="M3 1.5l4 3.5-4 3.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                進階選項
                {descriptions[zone.type] && !advancedOpen[zone.type] && (
                  <span className="text-[var(--color-primary)]">（已填寫說明）</span>
                )}
              </button>

              {advancedOpen[zone.type] && (
                <>
                  {/* Per-zone description */}
                  <textarea
                    value={descriptions[zone.type] || ""}
                    onChange={(e) =>
                      setDescriptions((prev) => ({ ...prev, [zone.type]: e.target.value }))
                    }
                    placeholder={zone.placeholder}
                    className="w-full mb-3 px-3 py-2 text-xs bg-[var(--color-surface)] border border-[var(--color-border)] rounded-lg text-[var(--color-text)] placeholder-[var(--color-text-muted)] resize-none focus:outline-none focus:border-[var(--color-primary)] transition-colors"
                    rows={2}
                  />

                  {zone.type !== "questions" && parsers.length > 0 && (
                    <div className="mb-3">
                      <label className="block text-xs text-[var(--color-text-muted)] mb-1">
                        解析工具
                      </label>
                      <select
                        value={parserByZone[zone.type] || "auto"}
                        onChange={(e) =>
                          setParserByZone((prev) => ({ ...prev, [zone.type]: e.target.value }))
                        }
                        className="input !py-1.5 text-xs w-full"
                        title={
                          parsers.find((p) => p.id === (parserByZone[zone.type] || "auto"))
                            ?.description ?? ""
                        }
                      >
                        {parsers.map((p) => (
                          <option key={p.id} value={p.id}>
                            {p.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  )}
                </>
              )}

              <input
                ref={(el) => { fileInputRefs.current[zone.type] = el; }}
                type="file"
                multiple
                className="hidden"
                onChange={(e) => handleFileSelect(zone.type, e.target.files)}
              />

              <button
                onClick={() => fileInputRefs.current[zone.type]?.click()}
                className={`w-full py-6 border-2 border-dashed rounded-xl transition-all text-sm ${
                  hasFiles
                    ? "border-[var(--color-primary)] bg-[var(--color-primary)]/10"
                    : "border-[var(--color-primary)]/40 bg-[var(--color-primary)]/5 hover:border-[var(--color-primary)] hover:bg-[var(--color-primary)]/10"
                }`}
              >
                {hasFiles ? (
                  <div className="space-y-1">
                    {files[zone.type].map((f, i) => (
                      <p key={i} className="text-[var(--color-text)] truncate px-2">
                        {f.name}
                      </p>
                    ))}
                  </div>
                ) : (
                  <div className="flex flex-col items-center gap-2">
                    <div className="upload-bounce">{zone.icon}</div>
                    <p className="text-[var(--color-text-muted)]">
                      點擊或拖放檔案至此
                    </p>
                  </div>
                )}
              </button>

              {/* Analyze button per zone */}
              <button
                onClick={() => handleAnalyze(zone.type)}
                disabled={!hasFiles || isAnalyzing}
                className="w-full mt-3 btn btn-primary py-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isAnalyzing ? (
                  <span className="flex items-center justify-center gap-2">
                    <span className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    解析中...
                  </span>
                ) : hasParsed ? (
                  "重新解析"
                ) : (
                  "解析資料"
                )}
              </button>

              {/* Parsed status + summary */}
              {hasParsed && (
                <div className="mt-3 p-3 bg-[var(--color-background)] rounded-lg">
                  <p className="text-xs text-[var(--color-success)] font-semibold mb-1">
                    ✓ 解析完成
                    {(() => {
                      const directMeta = (zoneData as { _meta?: { parser?: string } })._meta;
                      const nestedMeta = (zoneData as {
                        student_answers?: { _meta?: { parser?: string } };
                      }).student_answers?._meta;
                      const parserName = directMeta?.parser ?? nestedMeta?.parser;
                      return parserName ? (
                        <span className="ml-2 text-[var(--color-text-muted)] font-normal">
                          (by {parserName})
                        </span>
                      ) : null;
                    })()}
                  </p>
                  <ZoneSummary type={zone.type} data={zoneData} />
                </div>
              )}

              {errors[zone.type] && (
                <p className="text-sm text-red-400 mt-2 text-center">{errors[zone.type]}</p>
              )}
            </div>
          );
        })}
      </div>

      {/* Full parsed data display */}
      {hasAnyParsedData && (
        <div className="space-y-4">
          <QuestionsTable data={parsedData.questions as Record<string, unknown> | undefined} />
          <StudentAnswersTable data={parsedData.student_answers as Record<string, unknown> | undefined} />
          <TeacherAnswersTable data={parsedData.teacher_answers as Record<string, unknown> | undefined} />
        </div>
      )}

      {/* Next step button */}
      {hasAnyParsedData && !isAnyAnalyzing && (
        <div className="text-center">
          <button
            onClick={onGoToStep2}
            className="btn btn-primary text-lg px-8 py-4"
          >
            確認資料，前往下一步 →
          </button>
        </div>
      )}

      {/* Least-necessary setting — tucked at the very bottom so it doesn't
          compete with the actual upload actions above. */}
      <div className="flex justify-end pt-2">
        <ModelSelector value={model} onChange={setModel} label="解析模型：" />
      </div>
    </div>
  );
}

/** Compact summary shown inside each zone card */
function ZoneSummary({ type, data }: { type: string; data: Record<string, unknown> }) {
  if (type === "questions") {
    const questions = (data as { questions?: unknown[] }).questions;
    if (!questions) return null;
    return (
      <p className="text-xs text-[var(--color-text-muted)]">
        共 {questions.length} 題
      </p>
    );
  }
  if (type === "answers") {
    const sa = (data as { student_answers?: { students?: unknown[] } }).student_answers;
    const ta = (data as { teacher_answers?: { answers?: unknown[] } }).teacher_answers;
    const studentCount = sa?.students?.length ?? 0;
    const keyCount = ta?.answers?.length ?? 0;
    return (
      <p className="text-xs text-[var(--color-text-muted)]">
        共 {studentCount} 位學生 / 標準答案 {keyCount} 題
      </p>
    );
  }
  return null;
}

/* ── Parsed data tables ── */

function QuestionsTable({ data }: { data?: Record<string, unknown> }) {
  if (!data) return null;
  const questions = (data as { questions?: Array<{ number: number; text: string; options?: string[] | null }> }).questions;
  if (!questions?.length) return null;

  return (
    <div className="card p-5">
      <h3 className="font-display text-base font-semibold text-[var(--color-text)] mb-5">
        考試題目（{questions.length} 題）
      </h3>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-[var(--color-border)]">
              <th className="text-left py-2 px-3 text-[var(--color-text-muted)] w-12">#</th>
              <th className="text-left py-2 px-3 text-[var(--color-text-muted)]">題目</th>
            </tr>
          </thead>
          <tbody>
            {questions.map((q, i) => {
              const isImageQuestion = q.text?.includes("[圖片描述:") && !q.options?.length;
              return (
                <tr key={i} className="border-b border-[var(--color-border)]/50">
                  <td className="py-2 px-3 text-[var(--color-primary)] font-bold">{q.number}</td>
                  <td className="py-2 px-3 text-[var(--color-text)]">
                    {isImageQuestion && (
                      <span className="inline-block mb-1 px-1.5 py-0.5 text-[10px] font-semibold rounded bg-blue-50 text-blue-700">
                        圖片題 · AI 圖片描述
                      </span>
                    )}
                    <p className={isImageQuestion ? "italic text-[var(--color-text-muted)]" : ""}>{q.text}</p>
                    {q.options && (
                      <div className="mt-1 text-xs text-[var(--color-text-muted)]">
                        {q.options.join(" | ")}
                      </div>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function StudentAnswersTable({ data }: { data?: Record<string, unknown> }) {
  if (!data) return null;
  const students = (data as { students?: Array<{ name: string; id?: string; answers: Array<{ question_number: number; answer: string | null }> }> }).students;
  if (!students?.length) return null;

  const allQNums = Array.from(
    new Set(students.flatMap((s) => s.answers.map((a) => a.question_number)))
  ).sort((a, b) => a - b);

  return (
    <div className="card p-5">
      <h3 className="font-display text-base font-semibold text-[var(--color-text)] mb-5">
        學生答案（{students.length} 位學生）
      </h3>
      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-[var(--color-border)]">
              <th className="text-left py-1.5 px-2 text-[var(--color-text-muted)] sticky left-0 bg-[var(--color-surface)]">學生</th>
              {allQNums.map((n) => (
                <th key={n} className="text-center py-1.5 px-1 text-[var(--color-text-muted)] min-w-[32px]">{n}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {students.map((s, i) => (
              <tr key={i} className="border-b border-[var(--color-border)]/40">
                <td className="py-1.5 px-2 text-[var(--color-text)] font-medium sticky left-0 bg-[var(--color-surface)] whitespace-nowrap">
                  {s.name || s.id || `學生 ${i + 1}`}
                </td>
                {allQNums.map((n) => {
                  const ans = s.answers?.find((a) => a.question_number === n);
                  return (
                    <td key={n} className="text-center py-1.5 px-1 text-[var(--color-text-muted)]">
                      {ans?.answer ?? "-"}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TeacherAnswersTable({ data }: { data?: Record<string, unknown> }) {
  if (!data) return null;
  const answers = (data as { answers?: Array<{ question_number: number; correct_answer: string }> }).answers;
  if (!answers?.length) return null;

  return (
    <div className="card p-5">
      <h3 className="font-display text-base font-semibold text-[var(--color-text)] mb-5">
        標準答案（{answers.length} 題）
      </h3>
      <div className="flex flex-wrap gap-x-3 gap-y-1.5">
        {answers.map((a) => (
          <span key={a.question_number} className="text-xs text-[var(--color-text-muted)]">
            <span className="font-medium text-[var(--color-text)]">Q{a.question_number}</span>
            <span className="ml-1 text-[var(--color-success)] font-semibold">{a.correct_answer}</span>
          </span>
        ))}
      </div>
    </div>
  );
}
