All files / src/components IgShareModal.vue

95.59% Statements 868/908
86.51% Branches 186/215
82.75% Functions 24/29
95.59% Lines 868/908

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 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 14401x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x   1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x   3x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x   15x 15x 1x   1x 3x 3x 3x 3x   3x   1x 2x 1x   1x 1x 16x 16x 16x   16x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 4x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x     1x 1x     1x 1x     1x 1x 1x 1x   1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x       1x 1x 1x 1x 1x 1x 1x                     1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 16x 16x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 116x 116x 116x   116x 116x 116x 116x 116x 116x   116x 116x 116x 116x   116x 116x 116x 116x   116x 116x   116x 116x 116x 116x 71x 71x 71x 116x   116x 116x 116x 116x 116x 17x 17x 17x 17x 17x 17x 17x 17x 16x 17x 1x 1x 116x   116x 116x 116x 116x 116x 116x 116x 116x 116x 11x 11x 116x 116x 120x 120x 116x 116x 116x 20x 20x 20x 20x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x   116x   116x 116x 116x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     116x 116x 2x 2x 2x 2x 2x 116x   116x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 8x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x 1x 1x 1x 1x 2x 2x 3x 3x 3x 3x 3x 8x 12x 2x 2x 2x 6x 6x 6x 12x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 116x   116x 116x 116x 15x 15x 116x   116x 116x 116x 116x 116x 41x 41x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 116x   116x 116x 116x 40x 40x 3x 3x 3x 116x   116x 116x 116x 116x 56x 56x   56x 56x 6x 6x 6x   51x 56x 1x 1x 1x 50x 116x   116x 116x 116x 116x 116x 116x 116x 116x 116x 56x 672x 672x 672x 56x 116x 116x 116x 116x 116x 78x 116x 116x   116x 116x 116x 116x 56x 56x 56x 56x 116x 116x 116x 116x 116x 116x 116x 3x 57x 16x 53x 6x 37x 31x 31x 56x 56x 56x 56x 56x 56x 57x 116x 116x 116x 116x 56x 116x 116x 116x 116x 116x 116x   116x 7x       116x   116x 7x 7x 7x 7x   7x 1x 1x 1x 7x 1x 1x 1x   5x 5x 5x 116x   116x 116x 116x 116x 12x 4x 4x 4x 4x 12x   3x 3x   3x 3x 3x 3x 3x 12x 12x 12x 12x 2x 2x 2x 2x 2x 1x 1x 1x     1x 1x 1x 1x 2x 2x 116x   116x 12x 12x   12x 12x 12x 12x 12x 12x                         12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x 12x 12x 116x   116x   116x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x         116x   116x                                     116x   116x 2x 2x 2x 2x 116x   116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
<template>
  <!-- SB-32: Instagram share modal. Generates a 1080×1080 PNG (1080×1920 for
       the Fest Story, SB-1883) via html2canvas from <IgShareCard>, uploads the
       source photo to R2 for persistence. -->
  <div
    v-if="open"
    class="ig-modal-backdrop"
    data-testid="ig-share-modal"
    @click.self="onClose"
  >
    <div class="ig-modal-panel" role="dialog" aria-modal="true">
      <header class="ig-modal-header">
        <h2 class="ig-modal-title">Share to Instagram</h2>
        <button
          @click="onClose"
          data-testid="ig-close-button"
          class="ig-modal-close"
          aria-label="Close"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="w-5 h-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      </header>
 
      <div class="ig-modal-body">
        <!-- Mode toggle (only meaningful if both modes are available) -->
        <div
          v-if="canPickMode && !isTeamCardTemplate"
          class="ig-mode-toggle"
          role="tablist"
        >
          <button
            role="tab"
            :aria-selected="mode === 'preview'"
            data-testid="ig-mode-preview"
            class="ig-mode-button"
            :class="{ 'ig-mode-active': mode === 'preview' }"
            @click="mode = 'preview'"
          >
            Preview
          </button>
          <button
            role="tab"
            :aria-selected="mode === 'result'"
            data-testid="ig-mode-result"
            class="ig-mode-button"
            :class="{ 'ig-mode-active': mode === 'result' }"
            @click="mode = 'result'"
          >
            Result
          </button>
        </div>
 
        <!-- Template picker -->
        <div
          class="ig-template-picker"
          role="radiogroup"
          aria-label="Card template"
          data-testid="ig-template-picker"
        >
          <button
            v-for="opt in availableTemplates"
            :key="opt.value"
            type="button"
            role="radio"
            :aria-checked="template === opt.value"
            :data-testid="`ig-template-${opt.value}`"
            class="ig-template-option"
            :class="{ 'ig-template-active': template === opt.value }"
            @click="template = opt.value"
          >
            <span class="ig-template-label">{{ opt.label }}</span>
            <span class="ig-template-sub">{{ opt.sub }}</span>
          </button>
        </div>
 
        <!-- SB-1917: which team's Fest schedule the card shows. -->
        <div
          v-if="isTeamCardTemplate"
          class="ig-accent-picker"
          data-testid="ig-schedule-team-picker"
        >
          <span class="ig-accent-heading">Team</span>
          <div role="radiogroup" aria-label="Team" class="ig-accent-row">
            <button
              v-for="opt in scheduleTeamOptions"
              :key="opt.value"
              type="button"
              role="radio"
              :aria-checked="scheduleSide === opt.value"
              :data-testid="`ig-schedule-team-${opt.value}`"
              class="ig-accent-option"
              :class="{ 'ig-accent-active': scheduleSide === opt.value }"
              @click="scheduleSide = opt.value"
            >
              <span class="ig-accent-label">{{ opt.label }}</span>
            </button>
          </div>
        </div>
        <!-- SB-659: accent picker. Defaults to the viewer's own club when
             they are on one of these teams, since that is almost always the
             feed the card is going to. -->
        <!-- The Fest cards keep the Fest palette: no team colors to pick. -->
        <div
          v-if="!isFestTemplate"
          class="ig-accent-picker"
          data-testid="ig-accent-picker"
        >
          <span class="ig-accent-heading">Card colors</span>
          <div role="radiogroup" aria-label="Card colors" class="ig-accent-row">
            <button
              v-for="opt in accentOptions"
              :key="opt.value"
              type="button"
              role="radio"
              :aria-checked="accentPreference === opt.value"
              :disabled="opt.disabled"
              :title="opt.reason || `Use ${opt.label} colors`"
              :data-testid="`ig-accent-${opt.value}`"
              class="ig-accent-option"
              :class="{
                'ig-accent-active': accentPreference === opt.value,
                'ig-accent-disabled': opt.disabled,
              }"
              @click="!opt.disabled && (accentPreference = opt.value)"
            >
              <span
                class="ig-accent-swatch"
                :style="{ background: opt.color || 'transparent' }"
              ></span>
              <span class="ig-accent-label">{{ opt.label }}</span>
            </button>
          </div>
          <p
            v-if="unavailableAccentReason"
            class="ig-accent-note"
            data-testid="ig-accent-note"
          >
            {{ unavailableAccentReason }}
          </p>
        </div>
 
        <!-- Photo picker -->
        <label
          v-if="!isTeamCardTemplate"
          class="ig-file-picker"
          data-testid="ig-file-picker"
        >
          <input
            ref="fileInput"
            type="file"
            accept="image/jpeg,image/png"
            class="sr-only"
            data-testid="ig-file-input"
            @change="onFileChange"
          />
          <span class="ig-file-picker-cta">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="w-5 h-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M3 16v2a2 2 0 002 2h14a2 2 0 002-2v-2M16 8l-4-4m0 0L8 8m4-4v12"
              />
            </svg>
            <span>{{ photoFile ? 'Replace photo' : 'Choose photo' }}</span>
          </span>
          <span
            v-if="photoFile"
            class="ig-file-meta"
            data-testid="ig-file-meta"
          >
            {{ photoFile.name }} ({{ formatBytes(photoFile.size) }})
          </span>
        </label>
 
        <p
          v-if="needsPhotoHint"
          class="ig-photo-hint"
          data-testid="ig-photo-hint"
        >
          Fest Photo is built around your photo — add one from the match.
        </p>
 
        <p v-if="fileError" class="ig-error" data-testid="ig-file-error">
          {{ fileError }}
        </p>
 
        <!-- Scaled preview (visible) -->
        <p
          v-if="isTeamCardTemplate && !teamCard"
          class="ig-photo-hint"
          data-testid="ig-schedule-status"
        >
          {{ scheduleError || 'Loading…' }}
        </p>
        <div
          v-if="!isTeamCardTemplate || teamCard"
          class="ig-preview-frame"
          :class="`ig-preview-frame--${cardShape}`"
        >
          <div
            class="ig-preview-scaler"
            :class="`ig-preview-scaler--${cardShape}`"
          >
            <IgShareCard
              :match="match"
              :photo-src="localPhotoUrl"
              :events="events"
              :mode="mode"
              :template="template"
              :blurb="blurb"
              :week-number="weekNumber"
              :accent-preference="accentPreference"
              :matchup="matchup"
              :schedule="schedule"
              :path="path"
              data-testid="ig-preview-card"
            />
          </div>
        </div>
 
        <p v-if="uploadError" class="ig-error" data-testid="ig-upload-error">
          {{ uploadError }}
        </p>
 
        <!-- Actions -->
        <div class="ig-actions">
          <button
            class="ig-action-button ig-action-secondary"
            data-testid="ig-copy-button"
            :disabled="busy || captureBlocked"
            @click="onCopy"
          >
            <span v-if="status === 'copying'">Copying…</span>
            <span v-else-if="status === 'copied'">Copied!</span>
            <span v-else>Copy to clipboard</span>
          </button>
          <button
            class="ig-action-button ig-action-primary"
            data-testid="ig-download-button"
            :disabled="busy || captureBlocked"
            @click="onDownload"
          >
            <span v-if="status === 'downloading'">Generating…</span>
            <span v-else>Download PNG</span>
          </button>
        </div>
 
        <p class="ig-hint" data-testid="ig-hint">
          <template v-if="cardShape === 'portrait'">
            The card is generated at 1080×1350 — Instagram's portrait post size.
            Paste it into a new post.
          </template>
          <template v-else-if="isStory">
            The card is generated at 1080×1920 — Instagram Story size. Add it to
            your Story.
          </template>
          <template v-else>
            The card is generated at 1080×1080 — Instagram's square size. Paste
            it into a new post.
          </template>
        </p>
      </div>
    </div>
 
    <!-- Offscreen full-size card used for html2canvas capture.
         Kept in the DOM so html2canvas can read computed styles, but
         translated offscreen so it doesn't affect layout. -->
    <div
      class="ig-capture-host"
      :style="{ height: `${cardSize.height}px` }"
      aria-hidden="true"
    >
      <IgShareCard
        v-if="!isTeamCardTemplate || teamCard"
        ref="captureCard"
        :match="match"
        :photo-src="localPhotoUrl"
        :events="events"
        :mode="mode"
        :template="template"
        :blurb="blurb"
        :week-number="weekNumber"
        :accent-preference="accentPreference"
        :matchup="matchup"
        :schedule="schedule"
        :path="path"
        data-testid="ig-capture-card"
      />
    </div>
  </div>
</template>
 
<script>
import { computed, ref, watch } from 'vue';
import html2canvas from 'html2canvas';
import {
  inlineSvgsAsImages,
  withHtml2canvasBaselineFix,
} from '../utils/igCapture';
import IgShareCard from './IgShareCard.vue';
import { isUsableAccent, MT_ACCENT } from '@/composables/useIgShareData';
import { useAuthStore } from '@/stores/auth';
import { getApiBaseUrl } from '../config/api';
import { isFestTournament } from '@/utils/festCard';
import { teamPath } from '@/utils/teamPath';
import {
  groupFinish,
  opponentInitials,
  rowDensity,
  scheduleEyebrow,
  schedulePhase,
  scheduleRecord,
  scheduleRows,
  teamGroup,
  topScorers,
} from '@/utils/festSchedule';
 
const MAX_PHOTO_BYTES = 5 * 1024 * 1024;
const ACCEPTED_TYPES = ['image/jpeg', 'image/png'];
 
// Order matters — drives the picker's left-to-right tab order.
const TEMPLATES = [
  {
    value: 'overlay',
    label: 'Photo Overlay',
    sub: 'Photo full-bleed',
  },
  {
    value: 'split',
    label: 'Brand Split',
    sub: 'Panel + photo',
  },
  {
    value: 'tournament-round',
    label: 'Tournament Round',
    sub: 'Quarterfinal / Final',
    tournamentOnly: true,
  },
  // SB-1918: one team's road through a knockout tournament (GA Cup):
  // its group, then each bracket round to the final.
  {
    value: 'team-path',
    label: "Team's Path",
    sub: '4:5 · Knockout road',
    tournamentOnly: true,
    teamCard: 'path',
  },
  {
    value: 'team-path-story',
    label: 'Path Story',
    sub: '9:16 · Knockout road',
    tournamentOnly: true,
    teamCard: 'path',
  },
  {
    value: 'stadium',
    label: 'Stadium',
    sub: 'No photo needed',
  },
  {
    value: 'motw',
    label: 'Match of the Week',
    sub: 'MT weekly pick',
    motwOnly: true,
  },
  {
    value: 'fest',
    label: 'Fest Story',
    sub: '9:16 · Stats',
    festOnly: true,
  },
  {
    value: 'fest-photo',
    label: 'Fest Photo',
    sub: '9:16 · Your photo',
    festOnly: true,
    wantsPhoto: true,
  },
  {
    value: 'fest-post',
    label: 'Fest Post',
    sub: 'Square · Feed',
    festOnly: true,
  },
  // SB-1917: one team's whole Fest, as a preview, a running record or a
  // recap depending on how many of its matches are final.
  {
    value: 'fest-schedule',
    label: 'Schedule Post',
    sub: '4:5 · Team schedule',
    festOnly: true,
    teamCard: 'schedule',
  },
  {
    value: 'fest-schedule-story',
    label: 'Schedule Story',
    sub: '9:16 · Team schedule',
    festOnly: true,
    teamCard: 'schedule',
  },
];
 
// Cards about one team rather than this match: which kind each template is.
const TEAM_CARD_KIND = Object.fromEntries(
  TEMPLATES.filter(t => t.teamCard).map(t => [t.value, t.teamCard])
);
 
const FEST_TEMPLATES = new Set(
  TEMPLATES.filter(t => t.festOnly).map(t => t.value)
);
 
// Templates drawing inline SVG, which html2canvas leaves out (SB-1916).
const SVG_TEMPLATES = new Set([
  ...FEST_TEMPLATES,
  ...TEMPLATES.filter(t => t.teamCard === 'path').map(t => t.value),
]);
 
// Every template is Instagram's square post size except the Fest Story,
// which is a 9:16 Story (SB-1883).
const CARD_SIZES = {
  fest: { width: 1080, height: 1920 },
  'fest-photo': { width: 1080, height: 1920 },
  'fest-schedule': { width: 1080, height: 1350 },
  'fest-schedule-story': { width: 1080, height: 1920 },
  'team-path': { width: 1080, height: 1350 },
  'team-path-story': { width: 1080, height: 1920 },
};
const SQUARE = { width: 1080, height: 1080 };
 
const formatBytes = bytes => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};
 
export default {
  name: 'IgShareModal',
  components: { IgShareCard },
  props: {
    open: { type: Boolean, default: false },
    match: { type: Object, required: true },
    // Goal/card events for the match. Used to render scorers on the
    // result card when the match was live-scored (SB-33).
    events: { type: Array, default: () => [] },
    // SB-659: generating a card is open to anyone signed in, but writing
    // the photo onto the match is not. False hides the upload affordance
    // rather than letting it fail against the backend.
    canPersistPhoto: { type: Boolean, default: false },
    // The team the viewer belongs to, when it is one of the two playing.
    // Seeds the accent choice so a player gets their own club's colors
    // without touching the picker. Null for admins and neutrals.
    viewerTeamId: { type: Number, default: null },
    // The viewer's club, when it is one of the two playing. Covers club
    // fans and club managers, who have no team_id of their own.
    viewerClubId: { type: Number, default: null },
    // SB-1010: this match is the current Match of the Week. Unlocks the MOTW
    // template and makes it the opening choice, since someone who pressed
    // share on the MOTW strip wants the MOTW card.
    isMotw: { type: Boolean, default: false },
    blurb: { type: String, default: null },
    weekNumber: { type: Number, default: null },
  },
  emits: ['close', 'photo-uploaded'],
  setup(props, { emit }) {
    const authStore = useAuthStore();
    const fileInput = ref(null);
    const captureCard = ref(null);
 
    const photoFile = ref(null);
    const localPhotoUrl = ref(null);
    const fileError = ref(null);
    const uploadError = ref(null);
    const status = ref(null); // 'downloading' | 'copying' | 'copied'
    const uploadedKey = ref(null);
 
    const isCompleted = computed(
      () => props.match?.match_status === 'completed'
    );
    const canPickMode = computed(() => isCompleted.value);
 
    const mode = ref('preview');
    const template = ref('overlay');
    // 'auto' | 'home' | 'away' | 'mt'
    const accentPreference = ref('auto');
 
    const hasTournamentRound = computed(() => !!props.match?.tournament_round);
    const isFest = computed(() => isFestTournament(props.match));
 
    const cardSize = computed(() => CARD_SIZES[template.value] || SQUARE);
    const isStory = computed(() => cardSize.value.height === 1920);
    // 'square' 1080×1080, 'portrait' 1080×1350, 'story' 1080×1920.
    const cardShape = computed(() => {
      const h = cardSize.value.height;
      if (h === SQUARE.height) return 'square';
      return h === 1920 ? 'story' : 'portrait';
    });
 
    // SB-1883: the Fest Story's stat panels. Fetched once per open; a
    // failure leaves it null and the card renders without them.
    const matchup = ref(null);
    let matchupRequest = 0;
    const loadMatchup = async () => {
      const id = props.match?.id;
      const request = ++matchupRequest;
      matchup.value = null;
      if (!id) return;
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/matches/${id}/matchup`
        );
        if (request === matchupRequest) matchup.value = data || null;
      } catch {
        if (request === matchupRequest) matchup.value = null;
      }
    };
 
    // SB-1917 / SB-1918: cards about one team — the Fest Team Schedule and
    // the Team's Path. Loaded for the chosen team when such a template is
    // picked; cached per kind and team for this open.
    const teamCardKind = computed(() => TEAM_CARD_KIND[template.value] || null);
    const isTeamCardTemplate = computed(() => !!teamCardKind.value);
    const scheduleSide = ref('home');
    const scheduleCache = ref({});
    const scheduleError = ref(null);
    const scheduleTeamOptions = computed(() => [
      { value: 'home', label: props.match?.home_team_name || 'Home' },
      { value: 'away', label: props.match?.away_team_name || 'Away' },
    ]);
    const scheduleTeamId = computed(() =>
      scheduleSide.value === 'away'
        ? props.match?.away_team_id
        : props.match?.home_team_id
    );
    const teamCard = computed(() =>
      teamCardKind.value
        ? scheduleCache.value[
            `${teamCardKind.value}:${scheduleTeamId.value}`
          ] || null
        : null
    );
    const schedule = computed(() =>
      teamCardKind.value === 'schedule' ? teamCard.value : null
    );
    const path = computed(() =>
      teamCardKind.value === 'path' ? teamCard.value : null
    );
    const captureBlocked = computed(
      () => isTeamCardTemplate.value && !teamCard.value
    );
 
    const api = path => authStore.apiRequest(`${getApiBaseUrl()}${path}`);
 
    // The recap's extras. Either may come back empty; the card then leaves
    // that line out rather than showing a zero.
    const loadGroupFinish = async (matches, teamId) => {
      const group = teamGroup(matches, teamId);
      if (!group) return { group: null, finish: null };
      const q = new URLSearchParams({
        group,
        age_group_id: String(props.match.age_group_id),
        limit: '200',
      });
      try {
        const data = await api(
          `/api/tournaments/${props.match.tournament_id}/matches?${q}`
        );
        return { group, finish: groupFinish(data?.matches, teamId) };
      } catch {
        return { group, finish: null };
      }
    };
    const loadScorers = async (rows, teamId) => {
      const finals = rows.filter(r => r.status === 'final');
      const lists = await Promise.all(
        finals.map(r => api(`/api/matches/${r.id}/live/events`).catch(() => []))
      );
      return topScorers(lists.flat(), teamId);
    };
 
    const loadTeamCard = async () => {
      const m = props.match;
      const teamId = scheduleTeamId.value;
      const kind = teamCardKind.value;
      const key = `${kind}:${teamId}`;
      if (!kind || !m?.tournament_id || !teamId || scheduleCache.value[key])
        return;
      scheduleError.value = null;
      const side = scheduleSide.value;
      const teamName = side === 'away' ? m.away_team_name : m.home_team_name;
      const club = side === 'away' ? m.away_team_club : m.home_team_club;
      const age = m.age_group_name;
      const teamMeta = {
        teamName,
        teamLogoUrl: club?.logo_url || null,
        teamInitials: opponentInitials(teamName),
        ageGroup: age && age !== 'Unknown' ? age : null,
      };
      const store = card => {
        scheduleCache.value = { ...scheduleCache.value, [key]: card };
      };
      try {
        const q = new URLSearchParams({ team_id: String(teamId), limit: '50' });
        if (m.age_group_id) q.set('age_group_id', String(m.age_group_id));
        const data = await api(
          `/api/tournaments/${m.tournament_id}/matches?${q}`
        );
        const matches = data?.matches || [];
        if (kind === 'path') {
          if (!matches.length) {
            scheduleError.value =
              'No matches found for this team in this tournament.';
            return;
          }
          store({
            ...teamMeta,
            tournamentName: m.tournament_name || null,
            ...teamPath(matches, teamId, m.tournament_location),
          });
          return;
        }
        const rows = scheduleRows(matches, teamId, m.tournament_location);
        if (!rows.length) {
          scheduleError.value = 'No Fest matches found for this team.';
          return;
        }
        const phase = schedulePhase(rows);
        const extras =
          phase === 'recap'
            ? {
                ...(await loadGroupFinish(matches, teamId)),
                scorers: await loadScorers(rows, teamId),
              }
            : { group: null, finish: null, scorers: null };
        store({
          ...teamMeta,
          phase,
          eyebrow: scheduleEyebrow(phase, rows),
          rows,
          record: scheduleRecord(rows),
          density: rowDensity(rows.length),
          ...extras,
        });
      } catch {
        scheduleError.value = "Couldn't load this team's matches. Try again.";
      }
    };
 
    watch(
      [() => props.open, isTeamCardTemplate, scheduleTeamId, teamCardKind],
      ([isOpen, isSchedule]) => {
        if (isOpen && isSchedule) loadTeamCard();
      }
    );
 
    // SB-659: accent options, with the unusable ones disabled and a reason
    // attached. A club whose color is the seeded gray or too dark to see on
    // the card cannot be offered — but saying so beats silently handing back
    // a different color than the one that was clicked.
    const accentOptions = computed(() => {
      const m = props.match || {};
      const side = (value, club, teamName) => {
        const color = club?.primary_color || null;
        const usable = isUsableAccent(color);
        return {
          value,
          label: teamName || (value === 'home' ? 'Home' : 'Away'),
          color: usable ? color : null,
          disabled: !usable,
          reason: !color
            ? 'No club color on file'
            : !usable
              ? 'Too dark or unset — would not be visible'
              : null,
        };
      };
      return [
        side('home', m.home_team_club, m.home_team_name),
        side('away', m.away_team_club, m.away_team_name),
        {
          value: 'mt',
          label: 'Missing Table',
          color: MT_ACCENT,
          disabled: false,
          reason: null,
        },
      ];
    });
 
    // One line explaining any greyed-out club, so a user whose own team is
    // unavailable learns it is missing club data rather than a bug.
    const unavailableAccentReason = computed(() => {
      const blocked = accentOptions.value.filter(o => o.disabled);
      if (!blocked.length) return null;
      return blocked
        .map(o => `${o.label}: ${o.reason.toLowerCase()}`)
        .join(' · ');
    });
 
    // Which side, if any, the viewer belongs to. Team first — it is the
    // more specific claim — then club, which is all a club fan or club
    // manager has.
    const viewerSide = computed(() => {
      const m = props.match;
      if (!m) return null;
 
      const teamId = props.viewerTeamId;
      if (teamId) {
        if (teamId === m.home_team_id) return 'home';
        if (teamId === m.away_team_id) return 'away';
      }
 
      const clubId = props.viewerClubId;
      if (clubId) {
        if (clubId === m.home_team_club?.id) return 'home';
        if (clubId === m.away_team_club?.id) return 'away';
      }
      return null;
    });
 
    // The MOTW card is only offered for the match that actually is the pick.
    // A "Match of the Week" frame around an ordinary fixture would be a
    // graphic claiming something untrue, which is worse than one fewer
    // template.
    //
    // A Fest match gets only the Fest family (SB-1893): the generic cards
    // were built for league weekends, not the Fest. MOTW stays when the
    // match is the pick, for the reason above.
    const availableTemplates = computed(() =>
      TEMPLATES.filter(t => {
        if (t.motwOnly) return props.isMotw;
        if (isFest.value) return !!t.festOnly;
        return !t.festOnly && (!t.tournamentOnly || hasTournamentRound.value);
      })
    );
    const isFestTemplate = computed(() => FEST_TEMPLATES.has(template.value));
    // The chosen template is built around a photo the visitor has not added.
    const needsPhotoHint = computed(
      () =>
        !photoFile.value &&
        !!TEMPLATES.find(t => t.value === template.value)?.wantsPhoto
    );
 
    watch(
      () => props.open,
      isOpen => {
        if (!isOpen) return;
        // Reset transient state on open, but keep defaults sensible.
        fileError.value = null;
        uploadError.value = null;
        status.value = null;
        mode.value = isCompleted.value ? 'result' : 'preview';
        // The Match of the Week card wins when this match is the pick:
        // whoever pressed share on the MOTW strip wants the MOTW frame, and
        // it is the one template no other match can use. Tournament Round is
        // the next highest-impact default.
        // A Fest match opens on the Fest Story, which only Fest matches get.
        if (props.isMotw) {
          template.value = 'motw';
        } else if (isFest.value) {
          template.value = 'fest';
        } else if (hasTournamentRound.value) {
          template.value = 'tournament-round';
        } else {
          template.value = 'overlay';
        }
        // Default the accent to the viewer's own club when they are on one
        // of these two teams and that club's color is actually usable —
        // otherwise leave it automatic rather than preselecting an option
        // that resolves to something else.
        const side = viewerSide.value;
        const sideOption = side
          ? accentOptions.value.find(o => o.value === side)
          : null;
        accentPreference.value =
          sideOption && !sideOption.disabled ? side : 'auto';
        if (isFest.value) loadMatchup();
        // The viewer's own team first; otherwise the home side.
        scheduleSide.value = viewerSide.value === 'away' ? 'away' : 'home';
        scheduleCache.value = {};
        scheduleError.value = null;
      },
      { immediate: true }
    );
 
    const revokeLocalUrl = () => {
      if (localPhotoUrl.value) {
        URL.revokeObjectURL(localPhotoUrl.value);
        localPhotoUrl.value = null;
      }
    };
 
    const onFileChange = e => {
      const file = e.target.files?.[0];
      if (!file) return;
      fileError.value = null;
      uploadError.value = null;
 
      if (!ACCEPTED_TYPES.includes(file.type)) {
        fileError.value = 'Photo must be a JPEG or PNG.';
        return;
      }
      if (file.size > MAX_PHOTO_BYTES) {
        fileError.value = `Photo is too large (max 5 MB). Got ${formatBytes(file.size)}.`;
        return;
      }
 
      revokeLocalUrl();
      photoFile.value = file;
      localPhotoUrl.value = URL.createObjectURL(file);
    };
 
    // Upload the source photo to R2 so it's persisted on the match. Returns
    // true on success, false on graceful failure (we still let the user
    // download the card).
    const ensurePhotoUploaded = async () => {
      if (!photoFile.value || uploadedKey.value) return true;
      // SB-659: viewers without edit rights can still build and download a
      // card — the photo just stays local to their browser. Skip the request
      // rather than firing one the backend will refuse, which would put a
      // permission error in front of someone doing nothing wrong.
      if (!props.canPersistPhoto) return true;
 
      const formData = new FormData();
      formData.append('file', photoFile.value);
 
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/matches/${props.match.id}/photo`,
          { method: 'POST', body: formData }
        );
        uploadedKey.value = data?.photo_key || null;
        emit('photo-uploaded', data);
        return true;
      } catch (err) {
        // apiRequest surfaces the FastAPI `detail` as err.message — we lose
        // the HTTP code, so match known phrases to give a useful UI.
        // Either way we don't block card generation; user still gets a PNG.
        const msg = err?.message || '';
        if (msg.includes('Cloudflare R2 is not configured')) {
          uploadError.value =
            'Photo storage is not configured. Card will download but the photo will not be saved to the match.';
        } else if (msg.includes('permission')) {
          uploadError.value =
            'You do not have permission to save a photo for this match. Card will download but not be saved.';
        } else {
          uploadError.value =
            'Failed to upload photo to storage. Card will still download.';
        }
        return false;
      }
    };
 
    const captureBlob = async () => {
      const el = captureCard.value?.root;
      if (!el) throw new Error('Capture card not mounted');
 
      // html2canvas rasterises from computed styles at call time. If a
      // webfont hasn't finished loading it silently falls back, so the
      // on-screen preview looks right while the downloaded PNG — the
      // thing that actually gets posted — is set in a fallback face.
      // Wait for the headline font specifically, then for the rest.
      if (document.fonts) {
        try {
          await document.fonts.load('400 116px Anton');
          if (FEST_TEMPLATES.has(template.value)) {
            await document.fonts.load('italic 900 74px "Barlow Condensed"');
          }
          await document.fonts.ready;
        } catch {
          // A font that fails to load shouldn't block the download; the
          // card still renders, just in the fallback face.
        }
      }
 
      const { width, height } = cardSize.value;
      const canvas = await withHtml2canvasBaselineFix(() =>
        html2canvas(el, {
          backgroundColor: '#0b0b0d',
          scale: 1, // Already rendered at full size.
          useCORS: true,
          allowTaint: false,
          logging: false,
          width,
          height,
          windowWidth: width,
          windowHeight: height,
          // The Fest mesas are inline SVG, which html2canvas leaves out of
          // the PNG; draw them as images instead (SB-1916).
          onclone: SVG_TEMPLATES.has(template.value)
            ? (_doc, clonedEl) => inlineSvgsAsImages(clonedEl)
            : undefined,
        })
      );
 
      return await new Promise(resolve => {
        canvas.toBlob(blob => resolve(blob), 'image/png');
      });
    };
 
    const busy = computed(() => status.value !== null);
 
    const onDownload = async () => {
      if (busy.value) return;
      status.value = 'downloading';
      try {
        await ensurePhotoUploaded();
        const blob = await captureBlob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = isTeamCardTemplate.value
          ? `${template.value}-${scheduleTeamId.value}.png`
          : `match-${props.match.id}-${mode.value}.png`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        status.value = null;
      } catch (err) {
        console.error('Failed to generate share card:', err);
        uploadError.value = 'Failed to generate the share card. Try again.';
        status.value = null;
      }
    };
 
    const onCopy = async () => {
      if (busy.value) return;
      status.value = 'copying';
      try {
        await ensurePhotoUploaded();
        const blob = await captureBlob();
        await navigator.clipboard.write([
          new ClipboardItem({ 'image/png': blob }),
        ]);
        status.value = 'copied';
        setTimeout(() => {
          if (status.value === 'copied') status.value = null;
        }, 2000);
      } catch (err) {
        console.error('Failed to copy share card:', err);
        uploadError.value =
          'Failed to copy to clipboard. Try Download PNG instead.';
        status.value = null;
      }
    };
 
    const onClose = () => {
      revokeLocalUrl();
      photoFile.value = null;
      uploadedKey.value = null;
      emit('close');
    };
 
    return {
      fileInput,
      captureCard,
      photoFile,
      localPhotoUrl,
      fileError,
      uploadError,
      status,
      mode,
      template,
      availableTemplates,
      cardSize,
      cardShape,
      isStory,
      isTeamCardTemplate,
      scheduleSide,
      scheduleTeamOptions,
      schedule,
      path,
      teamCard,
      scheduleError,
      captureBlocked,
      needsPhotoHint,
      isFestTemplate,
      matchup,
      accentPreference,
      accentOptions,
      unavailableAccentReason,
      isCompleted,
      canPickMode,
      busy,
      onFileChange,
      onDownload,
      onCopy,
      onClose,
      formatBytes,
    };
  },
};
</script>
 
<style scoped>
.ig-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(15, 23, 42, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
  padding: 16px;
  overflow-y: auto;
}
 
.ig-modal-panel {
  background: rgb(var(--color-card));
  border-radius: 12px;
  width: 100%;
  max-width: 560px;
  max-height: calc(100vh - 32px);
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
 
.ig-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid rgb(var(--color-line));
}
 
.ig-modal-title {
  font-size: 18px;
  font-weight: 600;
  color: rgb(var(--color-fg));
  margin: 0;
}
 
.ig-modal-close {
  background: transparent;
  border: none;
  cursor: pointer;
  color: rgb(var(--color-fg-muted));
  padding: 6px;
  border-radius: 6px;
}
 
.ig-modal-close:hover {
  background: rgb(var(--color-surface-alt));
  color: rgb(var(--color-fg));
}
 
.ig-modal-body {
  padding: 16px 20px 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
}
 
.ig-mode-toggle {
  display: inline-flex;
  border-radius: 8px;
  background: rgb(var(--color-surface-alt));
  padding: 4px;
  align-self: flex-start;
  gap: 2px;
}
 
.ig-mode-button {
  border: none;
  background: transparent;
  padding: 6px 16px;
  font-size: 13px;
  font-weight: 500;
  color: rgb(var(--color-fg-muted));
  border-radius: 6px;
  cursor: pointer;
}
 
.ig-mode-active {
  background: rgb(var(--color-card));
  color: rgb(var(--color-fg));
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
 
.ig-template-picker {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}
 
@media (min-width: 600px) {
  .ig-template-picker {
    grid-template-columns: repeat(4, 1fr);
  }
}
 
.ig-template-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 10px 12px;
  border-radius: 8px;
  background: rgb(var(--color-surface-alt));
  border: 2px solid rgb(var(--color-line));
  cursor: pointer;
  text-align: left;
  transition: all 0.15s ease;
}
 
.ig-template-option:hover {
  background: rgb(var(--color-surface-alt));
}
 
/* The selected tile is dark with light text in both themes. Qualified with
   the base class (and :hover) so the hover rule above cannot repaint it
   light underneath its light text — which a tap leaves stuck on touch
   screens, making the chosen template unreadable (SB-1883). */
.ig-template-option.ig-template-active,
.ig-template-option.ig-template-active:hover {
  background: rgb(var(--color-fg));
  border-color: rgb(var(--color-fg));
  color: rgb(var(--color-card));
}
 
/* In dark mode --color-fg is light, so use the darkest surface instead and
   let the border carry the selection. */
:global(.dark .ig-template-option.ig-template-active),
:global(.dark .ig-template-option.ig-template-active:hover) {
  background: rgb(var(--color-surface));
  border-color: rgb(var(--color-fg));
  color: rgb(var(--color-fg));
}
 
.ig-template-label {
  font-size: 13px;
  font-weight: 700;
}
 
.ig-template-sub {
  font-size: 11px;
  color: rgb(var(--color-fg-muted));
}
 
.ig-template-active .ig-template-sub {
  color: rgb(var(--color-card));
  opacity: 0.8;
}
 
:global(.dark .ig-template-active .ig-template-sub) {
  color: rgb(var(--color-fg));
}
 
/* SB-659: accent picker */
.ig-accent-picker {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
 
.ig-accent-heading {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: rgb(var(--color-fg-muted));
}
 
.ig-accent-row {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
 
.ig-accent-option {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  background: rgb(var(--color-surface-alt));
  border: 2px solid rgb(var(--color-line));
  cursor: pointer;
  transition: all 0.15s ease;
  min-width: 0;
}
 
.ig-accent-option:hover:not(.ig-accent-disabled) {
  background: rgb(var(--color-surface-alt));
}
 
.ig-accent-active {
  background: rgb(var(--color-fg));
  border-color: rgb(var(--color-fg));
  color: rgb(var(--color-card));
}
 
/* Disabled must stay readable. Fading toward the panel colour is what put
   several of these at 1.11:1 contrast in dark mode (SB-897); state the
   unavailability with a muted token instead. */
.ig-accent-disabled {
  cursor: not-allowed;
  color: rgb(var(--color-fg-muted));
  background: rgb(var(--color-surface-alt));
  border-style: dashed;
}
 
.ig-accent-swatch {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  border-radius: 4px;
  /* Outline so a dark or absent swatch is still a visible chip rather
     than a hole in the button. */
  box-shadow: inset 0 0 0 1px rgba(100, 116, 139, 0.55);
}
 
.ig-accent-label {
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 160px;
}
 
.ig-accent-note {
  font-size: 11px;
  color: rgb(var(--color-fg-muted));
  margin: 0;
}
 
.ig-file-picker {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  cursor: pointer;
}
 
.ig-file-picker-cta {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 14px;
  border-radius: 8px;
  background: rgb(var(--color-fg));
  color: rgb(var(--color-card));
  font-size: 13px;
  font-weight: 600;
}
 
.ig-file-meta {
  font-size: 12px;
  color: rgb(var(--color-fg-muted));
}
 
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}
 
.ig-error {
  color: rgb(239 68 68);
  font-size: 13px;
  margin: 0;
}
 
.ig-photo-hint {
  color: rgb(var(--color-fg-muted));
  font-size: 13px;
  margin: 0;
}
 
/* Preview frame: shows the IgShareCard scaled to fit modal width.
   The card itself is rendered at 1080×1080 and scaled visually via
   CSS transform — the offscreen capture card stays at full size. */
.ig-preview-frame {
  width: 100%;
  aspect-ratio: 1 / 1;
  overflow: hidden;
  border-radius: 8px;
  /* Deliberately NOT a theme token. This is the letterbox behind the
     1080x1080 card, and the card is dark-designed whatever theme the author
     is using -- it is an exported image, not UI. Tokenising this would make
     the preview surface disagree with the PNG people actually post. */
  background: #0f172a;
  position: relative;
}
 
.ig-preview-scaler {
  position: absolute;
  top: 0;
  left: 0;
  width: 1080px;
  height: 1080px;
  transform-origin: top left;
  /* The actual scale is set per-element in CSS via container query.
     For typical modal widths (~480px) this is roughly 0.44. */
  transform: scale(0.44);
}
 
@media (min-width: 600px) {
  .ig-preview-scaler {
    transform: scale(0.48);
  }
}
 
/* SB-1883: the Fest Story is 1080×1920. The frame is sized to the scaled
   card (1080·s × 1920·s) and centred, so the 9:16 preview fits the modal
   rather than being cropped to a square. */
.ig-preview-frame--story {
  aspect-ratio: auto;
  width: 281px; /* 1080 × 0.26 */
  height: 500px; /* 1920 × 0.26 */
  align-self: center;
}
 
.ig-preview-scaler--story {
  height: 1920px;
  transform: scale(0.26);
}
 
/* SB-1917: the Schedule Post is Instagram's 4:5 portrait post. */
.ig-preview-frame--portrait {
  aspect-ratio: auto;
  width: 324px; /* 1080 × 0.3 */
  height: 405px; /* 1350 × 0.3 */
  align-self: center;
}
 
.ig-preview-scaler--portrait {
  height: 1350px;
  transform: scale(0.3);
}
 
@media (min-width: 600px) {
  .ig-preview-frame--portrait {
    width: 432px; /* 1080 × 0.4 */
    height: 540px; /* 1350 × 0.4 */
  }
 
  .ig-preview-scaler--portrait {
    transform: scale(0.4);
  }
 
  .ig-preview-frame--story {
    width: 324px; /* 1080 × 0.3 */
    height: 576px; /* 1920 × 0.3 */
  }
 
  .ig-preview-scaler--story {
    transform: scale(0.3);
  }
}
 
.ig-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
 
.ig-action-button {
  padding: 10px 18px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  border: 1px solid transparent;
}
 
.ig-action-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
 
.ig-template-option:disabled {
  cursor: not-allowed;
  color: rgb(var(--color-fg-muted));
  border-style: dashed;
}
 
.ig-action-primary {
  background: rgb(var(--color-fg));
  color: rgb(var(--color-card));
}
 
.ig-action-primary:hover:not(:disabled) {
  background: rgb(var(--color-fg-muted));
}
 
.ig-action-secondary {
  background: rgb(var(--color-card));
  color: rgb(var(--color-fg));
  border-color: rgb(var(--color-line));
}
 
.ig-action-secondary:hover:not(:disabled) {
  background: rgb(var(--color-surface-alt));
}
 
.ig-hint {
  font-size: 12px;
  color: rgb(var(--color-fg-muted));
  margin: 0;
}
 
/* Offscreen host for the full-size capture card. Positioned far offscreen
   but kept in normal flow so html2canvas can read computed styles. */
.ig-capture-host {
  position: fixed;
  top: 0;
  left: -10000px;
  width: 1080px;
  height: 1080px;
  pointer-events: none;
}
</style>