All files / src/components MatchPreview.vue

96.57% Statements 762/789
84.49% Branches 158/187
100% Functions 19/19
96.57% Lines 762/789

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 9471x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 5x 5x 5x         5x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 19x 19x 19x 19x   19x 1x   1x 1x 1x 1x 1x       1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x       2x 2x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x           1x 1x 1x             1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x       1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x   1x   34x 34x 32x 34x 34x 34x 30x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 16x 17x 17x 17x 17x   1x 34x 34x 34x   1x 17x 17x 17x   17x 17x 17x 17x 17x 1x 1x   1x 2x 2x 1x 1x   17x 17x 17x 17x 17x   4x 4x 4x 4x 4x 4x 4x 4x 4x   8x 8x 8x 8x 8x 8x 4x       1x   1x                                           1x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   10x 10x 10x 10x   1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 166x 166x 166x 166x 38x 38x 166x 166x     166x 3x 3x 166x 166x 166x 73x 73x 166x 1x   1x 1x 1x 84x 1x   1x   1x 3x 3x 3x 4x 4x 4x 4x 4x 4x   4x 3x 3x 3x 1x   1x   1x 64x 64x       64x 64x 64x 13x 64x   51x 51x 51x 64x   85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 1x 1x 85x       85x 85x 85x 82x 82x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x   85x 85x 85x     85x 82x 82x 85x   84x 84x 84x 63x 63x 63x 63x 21x 21x 21x 21x 21x 84x 16x 16x 84x 84x 1x 1x 1x 84x 3x 3x 3x 1x 1x 3x 2x 2x 84x 20x 20x 84x   1x 32x 32x 32x 32x 32x 32x   1x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x   1x 1x 1x 84x 84x 84x 84x 84x 84x 84x 1x 1x 1x 1x   1x    
<template>
  <div class="match-preview bg-card border border-line rounded-xl p-3 sm:p-5">
    <!-- Loading -->
    <div
      v-if="loading && !scoutingTab"
      class="flex flex-col items-center justify-center py-12"
      data-testid="preview-loading"
    >
      <div
        class="w-8 h-8 border-2 border-line border-t-brand-500 rounded-full animate-spin mb-3"
      ></div>
      <p class="text-fg-muted text-sm">Loading match preview...</p>
    </div>
 
    <!-- Error -->
    <div
      v-else-if="error && !scoutingTab"
      class="flex flex-col items-center justify-center py-12 text-center"
      data-testid="preview-error"
    >
      <div
        class="w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/50 flex items-center justify-center text-red-600 dark:text-red-400 font-bold mb-3"
      >
        !
      </div>
      <p class="text-fg-muted text-sm mb-3">{{ error }}</p>
      <button
        @click="fetchPreview"
        class="px-4 py-2 bg-brand-600 hover:bg-brand-700 text-white rounded-lg text-sm font-medium transition-colors"
      >
        Retry
      </button>
    </div>
 
    <!-- Content -->
    <div v-else-if="preview || scoutingTab" data-testid="preview-content">
      <!-- Tab bar -->
      <div class="border-b border-line mb-4">
        <nav class="flex space-x-1" aria-label="Match preview sections">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            @click="pickTab(tab.id)"
            :data-testid="`tab-${tab.id}`"
            :class="[
              'py-2 px-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap',
              activeTab === tab.id
                ? 'border-brand-600 text-brand-600 dark:border-brand-300 dark:text-brand-300'
                : 'border-transparent text-fg-muted hover:text-fg hover:border-line',
            ]"
          >
            {{ tab.label }}
            <span
              v-if="tab.count !== null"
              class="ml-1 text-xs px-1.5 py-0.5 rounded-full"
              :class="
                activeTab === tab.id
                  ? 'bg-brand-50 text-brand-700 dark:bg-brand-900/50 dark:text-brand-300'
                  : 'bg-surface-alt text-fg-muted'
              "
              >{{ tab.count }}</span
            >
          </button>
        </nav>
      </div>
 
      <!-- ── Scouting (SB-1782) ── -->
      <div v-if="activeTab === 'scouting'" data-testid="tab-panel-scouting">
        <div
          v-if="matchupLoading"
          class="flex flex-col items-center justify-center py-10"
          data-testid="scouting-loading"
        >
          <div
            class="w-8 h-8 border-2 border-line border-t-brand-500 rounded-full animate-spin mb-3"
          ></div>
          <p class="text-fg-muted text-sm">Loading scouting report...</p>
        </div>
        <div
          v-else-if="matchupError || !matchup"
          class="flex flex-col items-center justify-center py-10 text-center"
          data-testid="scouting-error"
        >
          <p class="text-fg-muted text-sm mb-3">
            {{ matchupError || 'The scouting report is unavailable.' }}
          </p>
          <button
            @click="fetchMatchup"
            class="px-4 py-2 bg-brand-600 hover:bg-brand-700 text-white rounded-lg text-sm font-medium transition-colors"
            data-testid="scouting-retry"
          >
            Retry
          </button>
        </div>
        <div
          v-else-if="scoutingEmpty"
          class="flex flex-col items-center py-10 text-fg-muted"
          data-testid="scouting-empty"
        >
          <p class="text-sm">No results tracked for either team this season.</p>
        </div>
        <ScoutingHeadToHead
          v-else
          :home="matchup.home"
          :away="matchup.away"
          :homeTeamName="homeTeamName"
          :awayTeamName="awayTeamName"
        />
      </div>
 
      <!-- ── Lineups (SB-1915): the parent's slot ── -->
      <div v-else-if="activeTab === 'lineup'" data-testid="tab-panel-lineup">
        <slot name="lineup" />
      </div>
 
      <!-- The preview's own tabs, while it loads or after it failed -->
      <div
        v-else-if="loading || error || !preview"
        class="flex flex-col items-center justify-center py-10 text-center"
        :data-testid="loading ? 'preview-loading' : 'preview-error'"
      >
        <p class="text-fg-muted text-sm mb-3">
          {{ loading ? 'Loading match preview...' : error }}
        </p>
        <button
          v-if="!loading"
          @click="fetchPreview"
          class="px-4 py-2 bg-brand-600 hover:bg-brand-700 text-white rounded-lg text-sm font-medium transition-colors"
        >
          Retry
        </button>
      </div>
 
      <!-- ── Recent Form ── -->
      <div v-else-if="activeTab === 'form'" data-testid="tab-panel-form">
        <!-- Both teams empty -->
        <div
          v-if="
            preview.home_team_recent.length === 0 &&
            preview.away_team_recent.length === 0
          "
          class="flex flex-col items-center py-10 text-fg-muted"
          data-testid="form-empty"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            class="w-10 h-10 mb-3 text-fg-muted"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
            />
          </svg>
          <p class="text-sm">No recent form data available.</p>
        </div>
        <!-- At least one team has data -->
        <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <!-- Home team column -->
          <div>
            <h3
              class="text-xs font-semibold text-fg-muted uppercase tracking-wide break-words"
              :class="
                preview.has_qop_data && preview.home_qop_rank != null
                  ? 'mb-0.5'
                  : 'mb-2'
              "
            >
              {{ homeTeamName }}
            </h3>
            <p
              v-if="sideAges.home"
              class="m-0 mb-2 text-xs text-fg-muted"
              data-testid="home-form-age"
            >
              {{ sideAges.home.name }} results: where this team plays its season
            </p>
            <div
              v-if="preview.has_qop_data && preview.home_qop_rank != null"
              class="text-xs text-fg-muted mb-2"
            >
              QoP
              <span class="font-medium text-fg-muted"
                >#{{ preview.home_qop_rank }}</span
              >
              <span
                v-if="preview.home_qop_rank_change > 0"
                class="text-green-500 ml-1"
                >▲{{ preview.home_qop_rank_change }}</span
              >
              <span
                v-else-if="preview.home_qop_rank_change < 0"
                class="text-red-500 ml-1"
                >▼{{ Math.abs(preview.home_qop_rank_change) }}</span
              >
            </div>
            <div
              v-if="preview.home_team_recent.length === 0"
              class="rounded border border-dashed border-line bg-surface-alt/60 px-3 py-4 text-center"
              data-testid="home-form-empty"
            >
              <span class="block text-xs font-semibold text-fg"
                >No matches on record</span
              >
              <span class="text-xs text-fg-muted"
                >We haven't tracked this club's results yet.</span
              >
            </div>
            <div
              v-for="m in preview.home_team_recent"
              :key="m.id"
              class="flex items-start gap-2 p-2 rounded bg-surface-alt border border-line text-xs mb-2"
              data-testid="home-recent-match"
            >
              <span
                :class="[
                  'font-bold w-5 text-center shrink-0 rounded-sm py-0.5',
                  matchOutcomeClass(m, homeTeamId),
                ]"
                >{{ matchOutcome(m, homeTeamId) }}</span
              >
              <!-- Two lines (SB-1881): the opponent's full name, then the
                   score and details. One line truncated every name. -->
              <div class="min-w-0 flex-1">
                <div
                  class="text-fg font-medium leading-snug break-words"
                  data-testid="form-opponent"
                >
                  {{ opponentName(m, homeTeamId) }}
                </div>
                <div
                  class="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5"
                >
                  <span class="font-mono font-semibold text-fg">{{
                    teamScoreline(m, homeTeamId) ?? '—'
                  }}</span>
                  <span
                    class="font-mono text-[10px] text-fg-muted"
                    data-testid="form-venue"
                    :title="venueFor(m, homeTeamId) === 'H' ? 'Home' : 'Away'"
                    >{{ venueFor(m, homeTeamId) }}</span
                  >
                  <span
                    v-if="m.match_type_name"
                    :class="[
                      'text-[10px] rounded px-1',
                      competitionClass(m.match_type_name),
                    ]"
                    data-testid="form-competition"
                    >{{ m.match_type_name }}</span
                  >
                  <span class="text-fg-muted ml-auto">{{
                    shortDate(m.match_date)
                  }}</span>
                </div>
              </div>
            </div>
          </div>
 
          <!-- Away team column -->
          <div>
            <h3
              class="text-xs font-semibold text-fg-muted uppercase tracking-wide break-words"
              :class="
                preview.has_qop_data && preview.away_qop_rank != null
                  ? 'mb-0.5'
                  : 'mb-2'
              "
            >
              {{ awayTeamName }}
            </h3>
            <p
              v-if="sideAges.away"
              class="m-0 mb-2 text-xs text-fg-muted"
              data-testid="away-form-age"
            >
              {{ sideAges.away.name }} results: where this team plays its season
            </p>
            <div
              v-if="preview.has_qop_data && preview.away_qop_rank != null"
              class="text-xs text-fg-muted mb-2"
            >
              QoP
              <span class="font-medium text-fg-muted"
                >#{{ preview.away_qop_rank }}</span
              >
              <span
                v-if="preview.away_qop_rank_change > 0"
                class="text-green-500 ml-1"
                >▲{{ preview.away_qop_rank_change }}</span
              >
              <span
                v-else-if="preview.away_qop_rank_change < 0"
                class="text-red-500 ml-1"
                >▼{{ Math.abs(preview.away_qop_rank_change) }}</span
              >
            </div>
            <div
              v-if="preview.away_team_recent.length === 0"
              class="rounded border border-dashed border-line bg-surface-alt/60 px-3 py-4 text-center"
              data-testid="away-form-empty"
            >
              <span class="block text-xs font-semibold text-fg"
                >No matches on record</span
              >
              <span class="text-xs text-fg-muted"
                >We haven't tracked this club's results yet.</span
              >
            </div>
            <div
              v-for="m in preview.away_team_recent"
              :key="m.id"
              class="flex items-start gap-2 p-2 rounded bg-surface-alt border border-line text-xs mb-2"
              data-testid="away-recent-match"
            >
              <span
                :class="[
                  'font-bold w-5 text-center shrink-0 rounded-sm py-0.5',
                  matchOutcomeClass(m, awayTeamId),
                ]"
                >{{ matchOutcome(m, awayTeamId) }}</span
              >
              <!-- Two lines (SB-1881): the opponent's full name, then the
                   score and details. One line truncated every name. -->
              <div class="min-w-0 flex-1">
                <div
                  class="text-fg font-medium leading-snug break-words"
                  data-testid="form-opponent"
                >
                  {{ opponentName(m, awayTeamId) }}
                </div>
                <div
                  class="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5"
                >
                  <span class="font-mono font-semibold text-fg">{{
                    teamScoreline(m, awayTeamId) ?? '—'
                  }}</span>
                  <span
                    class="font-mono text-[10px] text-fg-muted"
                    data-testid="form-venue"
                    :title="venueFor(m, awayTeamId) === 'H' ? 'Home' : 'Away'"
                    >{{ venueFor(m, awayTeamId) }}</span
                  >
                  <span
                    v-if="m.match_type_name"
                    :class="[
                      'text-[10px] rounded px-1',
                      competitionClass(m.match_type_name),
                    ]"
                    data-testid="form-competition"
                    >{{ m.match_type_name }}</span
                  >
                  <span class="text-fg-muted ml-auto">{{
                    shortDate(m.match_date)
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
 
      <!-- ── Common Opponents ── -->
      <div v-else-if="activeTab === 'common'" data-testid="tab-panel-common">
        <div
          v-if="preview.common_opponents.length === 0"
          class="flex flex-col items-center py-10 text-fg-muted"
          data-testid="common-empty"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            class="w-10 h-10 mb-3 text-fg-muted"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"
            />
          </svg>
          <p class="text-sm">No common opponents found this season.</p>
        </div>
        <div
          v-for="opp in preview.common_opponents"
          :key="opp.opponent_id"
          class="mb-4"
          data-testid="common-opponent-section"
        >
          <!-- Opponent header -->
          <div
            class="text-xs font-semibold text-fg mb-1.5 uppercase tracking-wide"
          >
            vs {{ opp.opponent_name }}
          </div>
          <!-- Stacked rows: home team result then away team result -->
          <div class="space-y-1">
            <div
              v-for="m in opp.home_team_matches"
              :key="m.id"
              class="flex items-center gap-2 px-2 py-1.5 rounded bg-surface-alt border border-line text-xs"
              data-testid="common-home-match"
            >
              <span
                :class="[
                  'font-bold w-5 text-center shrink-0 rounded-sm py-0.5',
                  matchOutcomeClass(m, homeTeamId),
                ]"
                >{{ matchOutcome(m, homeTeamId) }}</span
              >
              <span class="font-mono font-semibold text-fg shrink-0">{{
                teamScoreline(m, homeTeamId) ?? '—'
              }}</span>
              <span
                class="font-mono text-[10px] text-fg-muted shrink-0"
                data-testid="form-venue"
                :title="venueFor(m, homeTeamId) === 'H' ? 'Home' : 'Away'"
                >{{ venueFor(m, homeTeamId) }}</span
              >
              <span class="text-fg truncate flex-1">{{ homeTeamName }}</span>
              <span
                v-if="m.match_type_name && m.match_type_name !== 'League'"
                class="text-accent-600 dark:text-accent-300 shrink-0 italic"
                >{{ m.match_type_name }}</span
              >
              <span class="text-fg-muted shrink-0">{{
                shortDate(m.match_date)
              }}</span>
            </div>
            <div
              v-for="m in opp.away_team_matches"
              :key="m.id + '-away'"
              class="flex items-center gap-2 px-2 py-1.5 rounded bg-surface-alt border border-line text-xs"
              data-testid="common-away-match"
            >
              <span
                :class="[
                  'font-bold w-5 text-center shrink-0 rounded-sm py-0.5',
                  matchOutcomeClass(m, awayTeamId),
                ]"
                >{{ matchOutcome(m, awayTeamId) }}</span
              >
              <span class="font-mono font-semibold text-fg shrink-0">{{
                teamScoreline(m, awayTeamId) ?? '—'
              }}</span>
              <span
                class="font-mono text-[10px] text-fg-muted shrink-0"
                data-testid="form-venue"
                :title="venueFor(m, awayTeamId) === 'H' ? 'Home' : 'Away'"
                >{{ venueFor(m, awayTeamId) }}</span
              >
              <span class="text-fg-muted truncate flex-1">{{
                awayTeamName
              }}</span>
              <span
                v-if="m.match_type_name && m.match_type_name !== 'League'"
                class="text-accent-600 dark:text-accent-300 shrink-0 italic"
                >{{ m.match_type_name }}</span
              >
              <span class="text-fg-muted shrink-0">{{
                shortDate(m.match_date)
              }}</span>
            </div>
            <div
              v-if="
                !opp.home_team_matches.length && !opp.away_team_matches.length
              "
              class="text-xs text-fg-muted italic px-2 py-1"
            >
              No match data
            </div>
          </div>
        </div>
      </div>
 
      <!-- ── Head-to-Head ── -->
      <div v-else-if="activeTab === 'h2h'" data-testid="tab-panel-h2h">
        <div
          v-if="preview.head_to_head.length === 0"
          class="flex flex-col items-center py-10 text-fg-muted"
          data-testid="h2h-empty"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            class="w-10 h-10 mb-3 text-fg-muted"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
            />
          </svg>
          <p class="text-sm">No previous meetings found.</p>
        </div>
 
        <!-- Summary row -->
        <div
          v-if="preview.head_to_head.length > 0"
          class="flex justify-around text-center mb-4 p-3 bg-surface-alt rounded-lg"
        >
          <div>
            <span
              class="block text-xl font-bold text-brand-600 dark:text-brand-300"
              >{{ h2hStats.homeWins }}</span
            >
            <span class="text-xs text-fg-muted truncate block max-w-[80px]">{{
              homeTeamName
            }}</span>
          </div>
          <div>
            <span class="block text-xl font-bold text-fg-muted">{{
              h2hStats.draws
            }}</span>
            <span class="text-xs text-fg-muted">Draws</span>
          </div>
          <div>
            <span
              class="block text-xl font-bold text-red-600 dark:text-red-400"
              >{{ h2hStats.awayWins }}</span
            >
            <span class="text-xs text-fg-muted truncate block max-w-[80px]">{{
              awayTeamName
            }}</span>
          </div>
        </div>
 
        <!-- Match list -->
        <div
          v-for="match in preview.head_to_head"
          :key="match.id"
          class="flex items-center gap-2 px-3 py-2 rounded-lg bg-surface-alt border border-line text-xs mb-2"
          data-testid="h2h-match"
        >
          <span
            :class="[
              'flex-1 text-right truncate',
              h2hWinnerClass(match, match.home_team_id),
            ]"
            >{{ match.home_team_name }}</span
          >
          <span
            class="font-mono font-semibold text-fg shrink-0 bg-surface px-2 py-0.5 rounded"
            >{{ match.home_score ?? '-' }} – {{ match.away_score ?? '-' }}</span
          >
          <span
            :class="[
              'flex-1 truncate',
              h2hWinnerClass(match, match.away_team_id),
            ]"
            >{{ match.away_team_name }}</span
          >
          <div class="text-right shrink-0 ml-2">
            <div class="text-fg-muted">{{ longDate(match.match_date) }}</div>
            <div class="flex items-center justify-end gap-1 mt-0.5">
              <span class="text-fg-muted text-[10px]">
                {{ match.season_name }}
              </span>
              <span
                v-if="
                  match.match_type_name && match.match_type_name !== 'League'
                "
                class="text-accent-600 dark:text-accent-300 text-[10px] italic"
                >{{ match.match_type_name }}</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { getApiBaseUrl } from '@/config/api';
import ScoutingHeadToHead from './match/ScoutingHeadToHead.vue';
 
// ─── Template helpers ─────────────────────────────────────────────────────────
 
function matchOutcome(m, teamId) {
  if (m.home_score === null || m.away_score === null) return '?';
  const isHome = m.home_team_id === teamId;
  const teamScore = isHome ? m.home_score : m.away_score;
  const oppScore = isHome ? m.away_score : m.home_score;
  if (teamScore > oppScore) return 'W';
  if (teamScore < oppScore) return 'L';
  return 'D';
}
 
/**
 * The scoreline as *this team* played it (SB-892).
 *
 * `matchOutcome` above already swaps on `isHome` to decide W/L/D, but the
 * template used to print raw `home_score–away_score` beside it — and the
 * opponent-name span hides who was home. So a win could render "1–3", with
 * nothing on the row to say which number was the subject team's.
 *
 * Returns null when either score is absent, so the caller renders an em dash
 * rather than a bare separator. A `Not reported` match (SB-889) reaches here
 * with null scores.
 */
function teamScoreline(m, teamId) {
  if (m.home_score === null || m.away_score === null) return null;
  if (m.home_score === undefined || m.away_score === undefined) return null;
  const isHome = m.home_team_id === teamId;
  const own = isHome ? m.home_score : m.away_score;
  const opp = isHome ? m.away_score : m.home_score;
  return `${own}\u2013${opp}`;
}
 
/** H or A, so "3–1" can only be read one way. */
function venueFor(m, teamId) {
  return m.home_team_id === teamId ? 'H' : 'A';
}
 
/** The other side of a past match, from teamId's point of view. */
function opponentName(m, teamId) {
  return m.home_team_id === teamId ? m.away_team_name : m.home_team_name;
}
 
function matchOutcomeClass(m, teamId) {
  const o = matchOutcome(m, teamId);
  if (o === 'W') return 'bg-green-700 text-white';
  if (o === 'L') return 'bg-red-600 text-white';
  if (o === 'D') return 'bg-surface-alt text-fg border border-line';
  return 'bg-surface-alt text-fg-muted';
}
 
/** League reads neutral; anything else (Flex, a tournament) stands out. */
function competitionClass(name) {
  if (name === 'League') return 'bg-surface-alt text-fg-muted';
  return 'bg-accent-100 text-accent-700 dark:bg-accent-900/50 dark:text-accent-300';
}
 
function shortDate(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr + 'T00:00:00');
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
 
function longDate(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr + 'T00:00:00');
  return d.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}
 
function h2hWinnerClass(m, teamId) {
  if (m.home_score === null || m.away_score === null) return 'text-fg';
  const isHome = m.home_team_id === teamId;
  const score = isHome ? m.home_score : m.away_score;
  const opp = isHome ? m.away_score : m.home_score;
  if (score > opp) return 'font-bold text-fg';
  if (score < opp) return 'text-fg-muted';
  return 'text-fg';
}
 
// ─── Props ────────────────────────────────────────────────────────────────────
 
const props = defineProps({
  homeTeamId: { type: Number, required: true },
  homeTeamName: { type: String, default: 'Home Team' },
  awayTeamId: { type: Number, required: true },
  awayTeamName: { type: String, default: 'Away Team' },
  /** Season ID scopes "recent form" and "common opponents". Null = all seasons. */
  seasonId: { type: Number, default: null },
  /** Optional: narrow to a specific age group */
  ageGroupId: { type: Number, default: null },
  /** How many recent matches to fetch per team */
  recentCount: { type: Number, default: 5 },
  /**
   * The previewed match's competition. A League or Flex match shows League
   * and Flex form only; the server decides which types qualify (SB-1346).
   */
  matchTypeId: { type: Number, default: null },
  /** The previewed match; with tournamentId, the matchup is read too (SB-1782). */
  matchId: { type: Number, default: null },
  /** Set for a tournament match: the Scouting tab leads, and is read. */
  tournamentId: { type: Number, default: null },
  // Show a Lineups tab; its content is the `lineup` slot (SB-1915).
  lineupTab: { type: Boolean, default: false },
});
 
// ─── State ────────────────────────────────────────────────────────────────────
 
const authStore = useAuthStore();
const preview = ref(null);
const loading = ref(false);
const error = ref(null);
const activeTab = ref('form');
const matchup = ref(null);
const matchupLoading = ref(false);
const matchupError = ref(null);
// Once the user picks a tab, a late response never moves them.
const userPicked = ref(false);
 
function pickTab(id) {
  userPicked.value = true;
  activeTab.value = id;
}
 
// The API refused the matchup (4xx: a past-season match, say). Not a blip, so
// no retry: the Scouting tab goes and the usual tab choice applies.
const matchupRefused = ref(false);
 
// Bumped on every read, so a late answer for a previous match is dropped.
let previewSeq = 0;
// Each team's own season age when it is not the match's (SB-1908): a pro
// academy's U15 side plays its league at U16. Learned from the matchup.
const sideAges = ref({ home: null, away: null });
let matchupSeq = 0;
 
/**
 * Scouting leads for a tournament match: Fest teams come from different
 * conferences, so Common Opponents and Head-to-Head are mostly empty. It shows
 * from the start, loading or failed. A league match keeps the old tabs and
 * never reads the matchup.
 */
const scoutingTab = computed(
  () =>
    props.matchId != null && props.tournamentId != null && !matchupRefused.value
);
 
const sideHasNoData = side =>
  !!side?.dossier && !side.dossier.error && side.dossier.totals == null;
 
const scoutingEmpty = computed(
  () => sideHasNoData(matchup.value?.home) && sideHasNoData(matchup.value?.away)
);
 
// ─── Tabs ────────────────────────────────────────────────────────────────────
 
/**
 * Only tabs that actually hold something (SB-892).
 *
 * These used to render with a literal `0` badge, so two of the three tabs
 * advertised their own emptiness and invited a click that led nowhere. A tab
 * with no rows is not a tab.
 *
 * Recent Form always shows: it is the default view, and it has its own
 * per-team empty states rather than a single empty tab.
 */
const tabs = computed(() => {
  const commonCount = preview.value?.common_opponents?.length ?? 0;
  const h2hCount = preview.value?.head_to_head?.length ?? 0;
  const out = [];
  if (scoutingTab.value) {
    out.push({ id: 'scouting', label: 'Scouting', count: null });
  }
  out.push({ id: 'form', label: 'Recent Form', count: null });
  if (commonCount > 0) {
    out.push({ id: 'common', label: 'Common Opponents', count: commonCount });
  }
  if (h2hCount > 0) {
    out.push({ id: 'h2h', label: 'Head-to-Head', count: h2hCount });
  }
  // Starting lineups (SB-1915): the parent decides who sees it — managers
  // always, everyone else only once a lineup is set — and fills the panel.
  if (props.lineupTab) {
    out.push({ id: 'lineup', label: 'Lineups', count: null });
  }
  return out;
});
 
// If the active tab disappears (a reload returns no common opponents, say),
// fall back to Recent Form rather than rendering an empty panel.
watch(tabs, list => {
  if (!list.some(t => t.id === activeTab.value)) activeTab.value = 'form';
});
 
// ─── Head-to-head summary stats ───────────────────────────────────────────────
 
const h2hStats = computed(() => {
  if (!preview.value) return { homeWins: 0, awayWins: 0, draws: 0 };
  return preview.value.head_to_head.reduce(
    (acc, m) => {
      if (m.home_score === null || m.away_score === null) return acc;
      const homeIsOurHome = m.home_team_id === props.homeTeamId;
      const homeScore = homeIsOurHome ? m.home_score : m.away_score;
      const awayScore = homeIsOurHome ? m.away_score : m.home_score;
      if (homeScore > awayScore) acc.homeWins++;
      else if (homeScore < awayScore) acc.awayWins++;
      else acc.draws++;
      return acc;
    },
    { homeWins: 0, awayWins: 0, draws: 0 }
  );
});
 
// ─── Data fetching ───────────────────────────────────────────────────────────
 
/** The tab with the most content: Recent Form, else Common Opponents, else Head-to-Head. */
function autoTab() {
  if (!preview.value) {
    activeTab.value = 'form';
    return;
  }
  const { home_team_recent, away_team_recent, common_opponents } =
    preview.value;
  if (home_team_recent.length > 0 || away_team_recent.length > 0) {
    activeTab.value = 'form';
  } else if (common_opponents.length > 0) {
    activeTab.value = 'common';
  } else {
    activeTab.value = 'h2h';
  }
}
 
async function fetchPreview() {
  const seq = ++previewSeq;
  loading.value = true;
  error.value = null;
  try {
    const params = new URLSearchParams();
    if (props.seasonId) params.set('season_id', props.seasonId);
    if (props.ageGroupId) params.set('age_group_id', props.ageGroupId);
    params.set('recent_count', props.recentCount);
    if (props.matchTypeId) params.set('match_type_id', props.matchTypeId);
    if (sideAges.value.home) {
      params.set('home_age_group_id', sideAges.value.home.id);
    }
    if (sideAges.value.away) {
      params.set('away_age_group_id', sideAges.value.away.id);
    }
 
    const url = `${getApiBaseUrl()}/api/matches/preview/${props.homeTeamId}/${props.awayTeamId}?${params}`;
    const data = await authStore.apiRequest(url);
    if (seq !== previewSeq) return; // a previous match's answer
    // Normalize to guarantee expected arrays are always present
    preview.value = {
      home_team_id: data?.home_team_id ?? props.homeTeamId,
      away_team_id: data?.away_team_id ?? props.awayTeamId,
      home_team_recent: Array.isArray(data?.home_team_recent)
        ? data.home_team_recent
        : [],
      away_team_recent: Array.isArray(data?.away_team_recent)
        ? data.away_team_recent
        : [],
      common_opponents: Array.isArray(data?.common_opponents)
        ? data.common_opponents
        : [],
      head_to_head: Array.isArray(data?.head_to_head) ? data.head_to_head : [],
      has_qop_data: data?.has_qop_data ?? false,
      home_qop_rank: data?.home_qop_rank ?? null,
      home_qop_rank_change: data?.home_qop_rank_change ?? null,
      away_qop_rank: data?.away_qop_rank ?? null,
      away_qop_rank_change: data?.away_qop_rank_change ?? null,
    };
 
    // The user's pick, or a leading Scouting tab, stands.
    if (!userPicked.value && !scoutingTab.value) autoTab();
  } catch (err) {
    if (seq !== previewSeq) return;
    error.value = err.message || 'Failed to load match preview';
  } finally {
    if (seq === previewSeq) loading.value = false;
  }
}
 
async function fetchMatchup() {
  const seq = ++matchupSeq;
  if (!scoutingTab.value) {
    matchup.value = null;
    matchupLoading.value = false;
    return;
  }
  matchupLoading.value = true;
  matchupError.value = null;
  try {
    const url = `${getApiBaseUrl()}/api/matches/${props.matchId}/matchup`;
    const data = await authStore.apiRequest(url);
    if (seq !== matchupSeq) return; // a previous match's answer
    matchup.value = data;
    // A team measured at another age than the bracket: read its form there.
    const ages = { home: ownAge(data?.home), away: ownAge(data?.away) };
    if (ages.home || ages.away) {
      sideAges.value = ages;
      fetchPreview();
    }
  } catch (err) {
    if (seq !== matchupSeq) return;
    matchup.value = null;
    if (err?.status >= 400 && err?.status < 500) {
      matchupRefused.value = true;
      if (!userPicked.value) autoTab();
    } else {
      matchupError.value = 'The scouting report is unavailable right now.';
    }
  } finally {
    if (seq === matchupSeq) matchupLoading.value = false;
  }
}
 
/** A side's season age, only when its dossier says it differs from the match's. */
function ownAge(side) {
  const d = side?.dossier;
  if (!props.ageGroupId) return null; // no match age to differ from
  const age = d && !d.error ? d.age_group : null;
  return age?.id != null && age.id !== props.ageGroupId ? age : null;
}
 
/** Both reads at once; each owns its loading and error, so one never blanks the other. */
function fetchAll() {
  // A new match: nothing of the last one may show, or decide this one's tabs.
  userPicked.value = false;
  preview.value = null;
  error.value = null;
  matchup.value = null;
  matchupError.value = null;
  matchupRefused.value = false;
  sideAges.value = { home: null, away: null };
  activeTab.value = scoutingTab.value ? 'scouting' : 'form';
  return Promise.allSettled([fetchPreview(), fetchMatchup()]);
}
 
// Refetch when key props change
watch(
  () => [
    props.homeTeamId,
    props.awayTeamId,
    props.seasonId,
    props.ageGroupId,
    props.matchTypeId,
    props.matchId,
    props.tournamentId,
  ],
  () => fetchAll(),
  { immediate: false }
);
 
onMounted(fetchAll);
</script>