LabelCanvas.tsx 57.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
import React, { useCallback, useRef, useEffect } from 'react';
import JsBarcode from 'jsbarcode';
import { QRCodeSVG } from 'qrcode.react';
import type {
  LabelTemplate,
  LabelElement,
  NutritionExtraItem,
} from '../../../types/labelTemplate';
import { canonicalElementType, isPrintInputElement } from '../../../types/labelTemplate';
import { PRESET_LABEL_SIZES } from '../../../types/labelTemplate';
import { NUTRITION_FIXED_ITEMS } from '../../../types/labelTemplate';
import { cn } from '../../ui/utils';
import { resolvePictureUrlForDisplay } from '../../../services/imageUploadService';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../ui/select';

/** 真实条形码渲染(JsBarcode),支持水平/竖排 */
function BarcodeBlock({
  data,
  width,
  height,
  showText,
  orientation = 'horizontal',
}: {
  data: string;
  width: number;
  height: number;
  showText?: boolean;
  orientation?: 'horizontal' | 'vertical';
}) {
  const svgRef = useRef<SVGSVGElement>(null);
  const isVertical = orientation === 'vertical';
  const barHeight = Math.max(20, (isVertical ? width : height) - (showText ? 14 : 4));
  useEffect(() => {
    if (svgRef.current && data) {
      try {
        JsBarcode(svgRef.current, data, {
          format: 'CODE128',
          width: 1,
          height: barHeight,
          displayValue: showText !== false,
          margin: 2,
          fontOptions: '',
          fontSize: 10,
        });
      } catch {
        // invalid data, ignore
      }
    }
  }, [data, barHeight, showText]);
  const svg = <svg ref={svgRef} className="w-full h-full min-h-0" style={{ maxHeight: isVertical ? width : height }} />;
  if (isVertical) {
    return (
      <div className="w-full h-full flex items-center justify-center">
        <div
          style={{
            transform: 'rotate(-90deg)',
            transformOrigin: 'center center',
            width: height,
            height: width,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          {svg}
        </div>
      </div>
    );
  }
  return svg;
}

/** 画布网格步长(px),控件吸附到该步长 */
const GRID_SIZE = 8;

/** 将数值对齐到网格 */
function snapToGrid(value: number): number {
  return Math.round(value / GRID_SIZE) * GRID_SIZE;
}

/** 1cm ≈ 37.8px (96 DPI); 1 inch = 96px */
function unitToPx(value: number, unit: 'cm' | 'inch'): number {
  return unit === 'cm' ? value * 37.8 : value * 96;
}

/** px 转单位(用于拖拽调整纸张尺寸) */
function pxToUnit(px: number, unit: 'cm' | 'inch'): number {
  return unit === 'cm' ? px / 37.8 : px / 96;
}

/**
 * 多选项在画布上的文案:有 prefix 时与 App 打印一致(prefix + 答案/占位);否则在已选字典时显示「字典名称: 内容」。
 */
function formatMultipleOptionsCanvasLine(
  cfg: Record<string, unknown>,
  text: string,
  selected: string[],
): string {
  const prefix = String(cfg.prefix ?? '').trim();
  const dictLabel = String(cfg.multipleOptionName ?? cfg.MultipleOptionName ?? '').trim();
  const answers = selected.filter(Boolean).join(', ');
  const fallback = text || '…';
  if (prefix) {
    return answers ? `${prefix}${answers}` : `${prefix}${fallback}`;
  }
  if (dictLabel) {
    const body = answers || fallback;
    return `${dictLabel}: ${body}`;
  }
  return answers || fallback;
}

function nutritionExtraRows(cfg: Record<string, unknown>): NutritionExtraItem[] {
  const raw = cfg.extraNutrients;
  if (!Array.isArray(raw)) return [];
  return raw.map((item, idx) => {
    const row = item as Record<string, unknown>;
    return {
      id: String(row.id ?? `extra-${idx}`),
      name: String(row.name ?? ''),
      value: String(row.value ?? ''),
      unit: String(row.unit ?? ''),
    };
  });
}

function nutritionFixedField(
  cfg: Record<string, unknown>,
  key: string,
  field: 'value' | 'unit',
): string {
  const directKey = field === 'value' ? key : `${key}Unit`;
  const direct = cfg[directKey];
  if (direct != null && String(direct).trim() !== '') return String(direct).trim();
  const fixedRows = Array.isArray(cfg.fixedNutrients)
    ? (cfg.fixedNutrients as Record<string, unknown>[])
    : [];
  const row = fixedRows.find((item) => String(item.key ?? '').trim() === key);
  return String(row?.[field] ?? '').trim();
}

function formatDateByPreset(format: string, date: Date): string {
  const yyyy = String(date.getFullYear());
  const yy = yyyy.slice(-2);
  const mm = String(date.getMonth() + 1).padStart(2, '0');
  const dd = String(date.getDate()).padStart(2, '0');
  const hh = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  const monthLong = date.toLocaleString('en-US', { month: 'long' }).toUpperCase();
  const dayLong = date.toLocaleString('en-US', { weekday: 'long' }).toUpperCase();
  const dayShort = date.toLocaleString('en-US', { weekday: 'short' }).toUpperCase();
  const monthShort = date.toLocaleString('en-US', { month: 'short' }).toUpperCase();
  switch (format) {
    case 'DD/MM/YYYY':
      return `${dd}/${mm}/${yyyy}`;
    case 'MM/DD/YYYY':
      return `${mm}/${dd}/${yyyy}`;
    case 'DD/MM/YY':
      return `${dd}/${mm}/${yy}`;
    case 'MM/DD/YY':
      return `${mm}/${dd}/${yy}`;
    case 'MM/YY':
      return `${mm}/${yy}`;
    case 'MM/DD':
      return `${mm}/${dd}`;
    case 'MM':
      return mm;
    case 'DD':
      return dd;
    case 'YY':
      return yy;
    case 'FULLY DAY(WEDNESDAY)':
      return dayLong;
    case 'DAY (WED)':
      return dayShort;
    case 'MONTH (DECEMBER)':
      return monthLong;
    case 'YEAR (2025)':
      return yyyy;
    case 'DD MONTH YEAR (25 DECEMBER 2025)':
      return `${dd} ${monthLong} ${yyyy}`;
    default:
      return format
        .replace('YYYY', yyyy)
        .replace('YY', yy)
        .replace('MM', mm)
        .replace('DD', dd)
        .replace('HH', hh)
        .replace('mm', min);
  }
}

const DURATION_UNITS = new Set([
  'Minutes',
  'Hours',
  'Days',
  'Weeks',
  'Months (30 Day)',
  'Years',
]);

function normalizeWeightUnit(raw: unknown): 'lb' | 'kg' | 'mg' | 'g' | 'oz' {
  const unit = String(raw ?? '').trim().toLowerCase();
  if (unit === 'milligrams') return 'mg';
  if (unit === 'grams') return 'g';
  if (unit === 'ounces') return 'oz';
  if (unit === 'pounds') return 'lb';
  if (unit === 'kilograms') return 'kg';
  if (unit === 'lb' || unit === 'kg' || unit === 'mg' || unit === 'g' || unit === 'oz') return unit;
  return 'g';
}

/** 根据元素类型与 config 渲染画布上的默认内容 */
function ElementContent({ el, isAppPrintField }: { el: LabelElement; isAppPrintField?: boolean }) {
  const cfg = el.config as Record<string, unknown>;
  const type = canonicalElementType(el.type);
  const isVerticalRotation = el.rotation === 'vertical';

  // Common styles
  const commonStyle: React.CSSProperties = {
    fontSize: (cfg?.fontSize as number) ?? 14,
    fontFamily: (cfg?.fontFamily as string) ?? 'Arial',
    fontWeight: (cfg?.fontWeight as string) ?? 'normal',
    textAlign: (cfg?.textAlign as any) ?? 'left',
    color: (cfg?.color as string) ?? '#000',
  };

  // Rotation support:
  // The editor's Rotation is currently a simple horizontal/vertical toggle.
  // For text-like elements we render vertical via writing-mode to avoid layout clipping.
  const textLike =
    type === 'TEXT_STATIC' || type === 'TEXT_PRODUCT' || type === 'TEXT_PRICE';
  const textRotationStyle: React.CSSProperties =
    isVerticalRotation && textLike
      ? { writingMode: 'vertical-rl', textOrientation: 'mixed' as any }
      : {};
  const rotateBoxStyle: React.CSSProperties = isVerticalRotation
    ? { transform: 'rotate(-90deg)', transformOrigin: 'center center' }
    : {};

  // 文本类
  const inputType = cfg?.inputType as string | undefined;
  if (type === 'TEXT_STATIC') {
    const text = (cfg?.text as string) ?? 'Text';
    if (isAppPrintField) {
      if (inputType === 'options') {
        const selected = Array.isArray(cfg?.selectedOptionValues)
          ? (cfg.selectedOptionValues as string[])
          : [];
        const line = formatMultipleOptionsCanvasLine(cfg, text, selected);
        return (
          <div
            className="w-full h-full px-1 flex flex-col justify-center overflow-hidden pointer-events-none text-gray-600 italic text-[11px] leading-tight break-all"
            style={{ ...commonStyle, ...textRotationStyle }}
            title="Filled in mobile app when printing"
          >
            {line}
          </div>
        );
      }
      const display =
        inputType === 'number' ? ((cfg?.text as string) ?? '0') : text;
      return (
        <div
          className="w-full h-full px-1 flex items-center overflow-hidden pointer-events-none text-gray-600 italic text-[11px]"
          style={{ ...commonStyle, ...textRotationStyle }}
          title="Filled in mobile app when printing"
        >
          {display}
        </div>
      );
    }
    if (inputType === 'number') {
      return (
        <input
          type="number"
          readOnly
          value={(cfg?.text as string) ?? '0'}
          className="w-full h-full min-w-0 border border-gray-300 bg-white rounded px-1 pointer-events-none"
          style={{ ...commonStyle, ...textRotationStyle, textAlign: 'right' }}
        />
      );
    }
    if (inputType === 'options') {
      // 画布只展示「答案」纯文本,不出现勾选、下拉箭头等控件样式;实际选择在 APP 打印流程中完成
      const selected = Array.isArray(cfg?.selectedOptionValues)
        ? (cfg.selectedOptionValues as string[])
        : [];
      const line = formatMultipleOptionsCanvasLine(cfg, text, selected);
      const muted = selected.length === 0;
      return (
        <div
          className={cn(
            'w-full h-full px-1 overflow-hidden whitespace-pre-wrap break-all leading-tight',
            muted && 'text-gray-400',
          )}
          style={{ ...commonStyle, ...textRotationStyle }}
          title={line}
        >
          {line}
        </div>
      );
    }
    if (inputType === 'text') {
      return (
        <input
          type="text"
          readOnly
          value={text}
          className="w-full h-full min-w-0 border border-gray-300 bg-white rounded px-1 pointer-events-none"
          style={{ ...commonStyle, ...textRotationStyle }}
        />
      );
    }
    return (
      <div
        className="w-full h-full px-1 overflow-hidden whitespace-pre-wrap break-all leading-tight"
        style={{ ...commonStyle, ...textRotationStyle }}
      >
        {text}
      </div>
    );
  }
  if (type === 'TEXT_PRODUCT') {
    const text = (cfg?.text as string) ?? 'Product name';
    return (
      <div
        className="w-full h-full px-1 overflow-hidden whitespace-pre-wrap break-all leading-tight"
        style={{ ...commonStyle, ...textRotationStyle }}
      >
        {text}
      </div>
    );
  }
  if (type === 'TEXT_PRICE') {
    const text = (cfg?.text as string) ?? '0.00';
    return (
      <div
        className="w-full h-full px-1 overflow-hidden flex items-center"
        style={{
          ...commonStyle,
          ...textRotationStyle,
          justifyContent:
            commonStyle.textAlign === 'center'
              ? 'center'
              : commonStyle.textAlign === 'right'
                ? 'flex-end'
                : 'flex-start',
        }}
      >
        <span>{text}</span>
      </div>
    );
  }

  // 条码(支持水平/竖排)
  if (type === 'BARCODE') {
    const data = (cfg?.data as string) ?? '123456789';
    const showText = (cfg?.showText as boolean) !== false;
    const orientation = ((cfg?.orientation as string) === 'vertical' ? 'vertical' : 'horizontal') as 'horizontal' | 'vertical';
    return (
      <div className="flex flex-col items-center justify-center w-full h-full overflow-hidden p-0.5">
        <div className="flex-1 w-full min-h-0 flex items-center justify-center">
          <BarcodeBlock
            data={data}
            width={el.width}
            height={el.height}
            showText={showText}
            orientation={orientation}
          />
        </div>
      </div>
    );
  }

  // 二维码
  if (type === 'QRCODE') {
    const data = (cfg?.data as string) ?? 'https://example.com';
    const size = Math.min(el.width, el.height) - 4;
    return (
      <div className="w-full h-full flex items-center justify-center p-0.5">
        <QRCodeSVG value={data} size={Math.max(20, size)} level="M" includeMargin={false} />
      </div>
    );
  }

  // 图片/Logo
  if (type === 'IMAGE') {
    const src = cfg?.src as string | undefined;
    const imageRotateStyle: React.CSSProperties = isVerticalRotation
      ? { transform: 'rotate(-90deg)' }
      : {};
    if (src) {
      return (
        <div className="w-full h-full flex items-center justify-center overflow-hidden">
          <img
            src={resolvePictureUrlForDisplay(src)}
            alt=""
            className="max-w-full max-h-full object-contain"
            style={imageRotateStyle}
          />
        </div>
      );
    }
    return (
      <div
        className="w-full h-full flex flex-col items-center justify-center bg-gray-100 text-gray-500 text-[10px] border border-dashed border-gray-300"
        style={imageRotateStyle}
      >
        <span className="font-medium">Logo</span>
      </div>
    );
  }

  // 日期/时间
  if (type === 'DATE') {
    const it = String(cfg?.inputType ?? cfg?.InputType ?? '').toLowerCase();
    const format =
      (typeof cfg?.format === 'string' && cfg.format.trim()
        ? cfg.format
        : typeof cfg?.Format === 'string' && cfg.Format.trim()
          ? cfg.Format
          : it === 'datetime'
            ? 'YYYY-MM-DD HH:mm'
            : 'DD/MM/YYYY') ?? (it === 'datetime' ? 'YYYY-MM-DD HH:mm' : 'DD/MM/YYYY');
    const offset = Number(cfg?.offsetDays ?? cfg?.OffsetDays ?? 0) || 0;
    const d = new Date();
    d.setDate(d.getDate() + offset);
    const example = formatDateByPreset(format, d);
    const isInput = it === 'datetime' || it === 'date';
    if (isInput) {
      if (isAppPrintField) {
        return (
          <div className="w-full h-full flex items-center justify-center overflow-hidden">
            <div
              className="px-1 flex items-center justify-center overflow-hidden pointer-events-none text-[10px] text-center whitespace-nowrap"
              style={{ ...commonStyle, ...rotateBoxStyle }}
              title={`Format: ${format}`}
            >
              {format}
            </div>
          </div>
        );
      }
      return (
        <div className="w-full h-full flex items-center justify-center overflow-hidden">
          <input
            type="date"
            readOnly
            value="2025-02-01"
            className="w-full h-full min-w-0 border border-gray-300 bg-white rounded px-1 pointer-events-none text-[10px]"
            style={{ ...commonStyle, ...rotateBoxStyle }}
          />
        </div>
      );
    }
    return (
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div className="px-1 overflow-hidden whitespace-nowrap" style={{ ...commonStyle, ...rotateBoxStyle }}>
          {example}
        </div>
      </div>
    );
  }

  // (Simplified other types similarly for brevity, ensuring style prop is passed)
  if (type === 'TIME') {
    const format = 'HH:mm';
    const example = format.replace('HH', '12').replace('mm', '30');
    return (
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div className="px-1 overflow-hidden whitespace-nowrap" style={{ ...commonStyle, ...rotateBoxStyle }}>
          {example}
        </div>
      </div>
    );
  }

  if (type === 'DURATION') {
    const rawFormat =
      (typeof cfg?.format === 'string' && cfg.format.trim()
        ? cfg.format
        : typeof cfg?.Format === 'string' && cfg.Format.trim()
          ? cfg.Format
          : 'Days') ?? 'Days';
    const unit = DURATION_UNITS.has(rawFormat) ? rawFormat : 'Days';
    const rawV = cfg?.durationValue ?? cfg?.value ?? cfg?.offsetDays ?? cfg?.DurationValue ?? cfg?.Value ?? cfg?.OffsetDays;
    const durationValue = Number.isFinite(Number(rawV)) ? Number(rawV) : 3;
    const example = `${durationValue} ${unit}`;
    return (
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div className="px-1 overflow-hidden whitespace-nowrap" style={{ ...commonStyle, ...rotateBoxStyle }}>
          {example}
        </div>
      </div>
    );
  }

  if (type === 'WEIGHT') {
    const rawV = cfg?.value ?? cfg?.Value;
    const numVal =
      rawV == null || rawV === ''
        ? 500
        : typeof rawV === 'number'
          ? rawV
          : Number(rawV);
    const weightNum = Number.isFinite(numVal) ? numVal : 500;
    const weightUnit = normalizeWeightUnit(
      (typeof cfg?.unit === 'string' && cfg.unit.trim()
        ? cfg.unit
        : typeof cfg?.Unit === 'string' && cfg.Unit.trim()
          ? cfg.Unit
          : 'g') ?? 'g',
    );
    const weightFontSizeRaw = cfg?.fontSize ?? cfg?.FontSize;
    const weightFontSize = Number.isFinite(Number(weightFontSizeRaw)) ? Number(weightFontSizeRaw) : 14;
    const weightTextAlignRaw = String(cfg?.textAlign ?? cfg?.TextAlign ?? 'left').toLowerCase();
    const weightTextAlign: 'left' | 'center' | 'right' =
      weightTextAlignRaw === 'center' || weightTextAlignRaw === 'right' ? weightTextAlignRaw : 'left';
    return (
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div
          className="px-1 overflow-hidden whitespace-nowrap"
          style={{ ...commonStyle, ...rotateBoxStyle, fontSize: weightFontSize, textAlign: weightTextAlign }}
        >
          {weightNum}
          {weightUnit}
        </div>
      </div>
    );
  }

  if (type === 'WEIGHT_PRICE') {
    const unitPrice = (cfg?.unitPrice as number) ?? 10;
    const weight = (cfg?.weight as number) ?? 0.5;
    const currency = (cfg?.currency as string) ?? '$';
    return <div className="w-full h-full px-1 overflow-hidden whitespace-nowrap" style={commonStyle}>{currency}{(unitPrice * weight).toFixed(2)}</div>;
  }

  // 营养成分表
  if (type === 'NUTRITION') {
    const servingsPerContainer = String(cfg.servingsPerContainer ?? cfg.ServingsPerContainer ?? '').trim();
    const servingSize = String(cfg.servingSize ?? cfg.ServingSize ?? '').trim();
    const calories = String(cfg.calories ?? cfg.Calories ?? nutritionFixedField(cfg, 'calories', 'value') ?? '').trim();
    const nutritionTitleSize = Number(cfg.nutritionTitleFontSize ?? cfg.NutritionTitleFontSize ?? 16) || 16;
    const baseRows = NUTRITION_FIXED_ITEMS.map((item) => {
      const value = nutritionFixedField(cfg, item.key, 'value');
      const unit = nutritionFixedField(cfg, item.key, 'unit');
      if (!value) return null;
      return {
        id: item.key,
        label: item.label,
        value,
        unit,
      };
    }).filter(Boolean) as Array<{ id: string; label: string; value: string; unit: string }>;
    const extraRows = nutritionExtraRows(cfg)
      .filter((item) => item.value.trim())
      .map((item) => ({
        id: item.id,
        label: item.name.trim() || 'Other',
        value: item.value.trim(),
        unit: item.unit.trim(),
      }));
    const rows = [...baseRows, ...extraRows];
    const formatNutritionValue = (value: string, unit: string): string => {
      const v = String(value ?? '').trim();
      const u = String(unit ?? '').trim();
      if (!v && !u) return '';
      return `<${v}${u ? ` ${u}` : ''}`;
    };
    const nutritionContent = (
      <div className="text-[10px] p-1 w-full h-full overflow-hidden flex flex-col leading-tight bg-white">
        <div className="font-bold border-b border-black pb-0.5" style={{ fontSize: `${nutritionTitleSize}px` }}>
          Nutrition Facts
        </div>
        {calories ? (
          <div className="flex items-center justify-between py-0.5 mt-0.5">
            <span className="font-semibold text-[10px]">Calories</span>
            <span className="font-semibold text-[10px]">{formatNutritionValue(calories, '')}</span>
          </div>
        ) : null}
        {servingsPerContainer ? (
          <div className="flex items-center justify-between py-0.5 text-[10px]">
            <span>Servings Per Container</span>
            <span>{servingsPerContainer}</span>
          </div>
        ) : null}
        {servingSize ? (
          <div className="flex items-center justify-between pb-0.5 text-[10px]">
            <span>Serving Size</span>
            <span>{servingSize}</span>
          </div>
        ) : null}
        <div className="flex-1 min-h-0 overflow-hidden pt-0.5">
          {rows.length === 0 ? (
            <div className="text-[7px] text-gray-500">No nutrients</div>
          ) : (
            rows.slice(0, 18).map((row) => (
              <div key={row.id} className="flex items-center justify-between py-[1px] text-[10px]">
                <span className="truncate font-medium">{row.label}</span>
                <span className="shrink-0 font-medium">
                  {formatNutritionValue(row.value, row.unit)}
                </span>
              </div>
            ))
          )}
        </div>
      </div>
    );
    return (
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div
          className="shrink-0"
          style={
            isVerticalRotation
              ? {
                  width: el.height,
                  height: el.width,
                  transform: 'rotate(-90deg)',
                  transformOrigin: 'center center',
                }
              : { width: '100%', height: '100%' }
          }
        >
          {nutritionContent}
        </div>
      </div>
    );
  }

  // 空白占位
  if (type === 'BLANK') {
    return <div className="w-full h-full border border-dashed border-gray-200" />;
  }

  return (
    <div className="text-gray-500 text-[10px] px-1 truncate w-full flex items-center justify-center">
      {el.type.replace(/_/g, ' ')}
    </div>
  );
}

interface LabelCanvasProps {
  template: LabelTemplate;
  selectedId: string | null;
  onSelect: (id: string | null) => void;
  onUpdateElement: (id: string, patch: Partial<LabelElement>) => void;
  onDeleteElement: (id: string) => void;
  onTemplateChange?: (patch: Partial<LabelTemplate>) => void;
  scale?: number;
  onZoomIn?: () => void;
  onZoomOut?: () => void;
  onPreview?: () => void;
}

type PaperResizeEdge =
  | 'bottom'
  | 'right'
  | 'top'
  | 'left'
  | 'top-left'
  | 'top-right'
  | 'bottom-left'
  | 'bottom-right';

function cursorForPaperResizeEdge(edge: PaperResizeEdge): string {
  if (edge === 'top' || edge === 'bottom') return 'ns-resize';
  if (edge === 'left' || edge === 'right') return 'ew-resize';
  if (edge === 'top-left' || edge === 'bottom-right') return 'nwse-resize';
  return 'nesw-resize';
}

export function LabelCanvas({
  template,
  selectedId,
  onSelect,
  onUpdateElement,
  onDeleteElement,
  onTemplateChange,
  scale = 1,
  onZoomIn,
  onZoomOut,
  onPreview,
}: LabelCanvasProps) {
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLDivElement>(null);
  const dragRef = useRef<{ id: string; startX: number; startY: number; elX: number; elY: number } | null>(null);
  const resizeRef = useRef<{ id: string; corner: string; startX: number; startY: number; w: number; h: number; elX: number; elY: number } | null>(null);
  const paperResizeRef = useRef<{
    edge: PaperResizeEdge;
    startX: number;
    startY: number;
    startW: number;
    startH: number;
    startElements: { id: string; x: number; y: number }[];
  } | null>(null);
  const lastUpdateRef = useRef<{ id: string; x?: number; y?: number; width?: number; height?: number } | null>(null);

  const nextFrameRef = useRef<number | null>(null);
  const [isSpacePressed, setIsSpacePressed] = React.useState(false);
  const [isPanning, setIsPanning] = React.useState(false);
  const [paperResizeCursor, setPaperResizeCursor] = React.useState<string | null>(null);
  const panStartRef = useRef<{ x: number; y: number; scrollLeft: number; scrollTop: number } | null>(null);
  const [panOffset, setPanOffset] = React.useState({ x: 0, y: 0 });
  const panOffsetStartRef = useRef<{ x: number; y: number; startX: number; startY: number } | null>(null);

  const baseW = unitToPx(template.width, template.unit);
  const baseH = unitToPx(template.height, template.unit);
  const widthPx = baseW * scale;
  const heightPx = baseH * scale;
  const showGrid = template.showGrid !== false;

  const handlePointerDown = useCallback(
    (e: React.PointerEvent, id: string) => {
      // 如果按住了空格,直接返回,交给外层 panning 处理
      // 允许中键 (button 1) 拖动
      if (isSpacePressed || e.button === 1) return;

      e.stopPropagation();
      onSelect(id);

      // Focus canvas for keyboard events
      canvasRef.current?.focus();

      const el = template.elements.find((x) => x.id === id);
      if (!el) return;

      const domEl = document.getElementById(`element-${id}`);
      if (domEl) {
        domEl.classList.add('z-50', 'opacity-90', 'shadow-xl', 'ring-2', 'ring-blue-400', 'ring-offset-2');
        domEl.style.cursor = 'grabbing';
      }

      dragRef.current = { id, startX: e.clientX, startY: e.clientY, elX: el.x, elY: el.y };
      lastUpdateRef.current = { id, x: el.x, y: el.y }; // 初始化
      (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
    },
    [template.elements, onSelect, isSpacePressed]
  );

  const requestUpdate = useCallback((updateFn: () => void) => {
    if (nextFrameRef.current !== null) {
      cancelAnimationFrame(nextFrameRef.current);
    }
    nextFrameRef.current = requestAnimationFrame(() => {
      updateFn();
      nextFrameRef.current = null;
    });
  }, []);

  const beginPaperResize = useCallback((e: React.PointerEvent, edge: PaperResizeEdge) => {
    e.stopPropagation();
    paperResizeRef.current = {
      edge,
      startX: e.clientX,
      startY: e.clientY,
      startW: template.width,
      startH: template.height,
      startElements: template.elements.map((el) => ({ id: el.id, x: el.x, y: el.y })),
    };
    const cursor = cursorForPaperResizeEdge(edge);
    setPaperResizeCursor(cursor);
    document.body.style.cursor = cursor;
    (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
  }, [template.width, template.height, template.elements]);

  const handlePointerMove = useCallback(
    (e: React.PointerEvent) => {
      // 画布平移:优先处理(translate 方式,不依赖滚动)
      if (isPanning && panOffsetStartRef.current) {
        const dx = e.clientX - panOffsetStartRef.current.startX;
        const dy = e.clientY - panOffsetStartRef.current.startY;
        setPanOffset({
          x: panOffsetStartRef.current.x + dx,
          y: panOffsetStartRef.current.y + dy,
        });
        return;
      }
      if (isPanning && panStartRef.current && scrollContainerRef.current) {
        const dx = e.clientX - panStartRef.current.x;
        const dy = e.clientY - panStartRef.current.y;
        scrollContainerRef.current.scrollLeft = panStartRef.current.scrollLeft - dx;
        scrollContainerRef.current.scrollTop = panStartRef.current.scrollTop - dy;
        return;
      }
      // Drag Element
      if (dragRef.current) {
        // e.persist(); // React 17+ doesn't strictly need this for properties access in rAF closure if we read them now
        const { id, startX, startY, elX, elY } = dragRef.current;
        const clientX = e.clientX;
        const clientY = e.clientY;

        requestUpdate(() => {
          const dx = (clientX - startX) / scale;
          const dy = (clientY - startY) / scale;
          const rawX = Math.max(0, elX + dx);
          const rawY = Math.max(0, elY + dy);
          const snappedX = snapToGrid(rawX);
          const snappedY = snapToGrid(rawY);

          // 直接操作 DOM 避免频繁重渲染
          const domEl = document.getElementById(`element-${id}`);
          if (domEl) {
            domEl.style.left = `${snappedX}px`;
            domEl.style.top = `${snappedY}px`;
          }
          lastUpdateRef.current = { id, x: snappedX, y: snappedY };
          // 注意:这里不再更新 dragRef.current,因为我们在闭包里计算 dx, dy 也是 Ok 的。
          // 只要我们始终基于 startX/elX 计算,就不会有精度积累误差。
        });
      }

      // Resize Element
      if (resizeRef.current) {
        const { id, corner, startX, startY, w, h, elX, elY } = resizeRef.current;
        const clientX = e.clientX;
        const clientY = e.clientY;

        requestUpdate(() => {
          const dx = (clientX - startX) / scale;
          const dy = (clientY - startY) / scale;
          let nw = w;
          let nh = h;
          let nx = elX;
          let ny = elY;
          if (corner.includes('e')) nw = Math.max(20, w + dx);
          if (corner.includes('w')) {
            nw = Math.max(20, w - dx);
            // Keep the right edge anchored when width hits min limit.
            nx = elX + (w - nw);
          }
          if (corner.includes('s')) nh = Math.max(12, h + dy);
          if (corner.includes('n')) {
            nh = Math.max(12, h - dy);
            // Keep the bottom edge anchored when height hits min limit.
            ny = elY + (h - nh);
          }
          const snappedW = snapToGrid(nw);
          const snappedH = snapToGrid(nh);
          const snappedX = snapToGrid(nx);
          const snappedY = snapToGrid(ny);

          // 直接操作 DOM
          const domEl = document.getElementById(`element-${id}`);
          if (domEl) {
            domEl.style.width = `${snappedW}px`;
            domEl.style.height = `${snappedH}px`;
            domEl.style.left = `${snappedX}px`;
            domEl.style.top = `${snappedY}px`;
          }

          lastUpdateRef.current = { id, width: snappedW, height: snappedH, x: snappedX, y: snappedY };
        });
      }

      // Resize Paper
      if (paperResizeRef.current && onTemplateChange) {
        const { edge, startX, startY, startW, startH, startElements } = paperResizeRef.current;
        const clientX = e.clientX;
        const clientY = e.clientY;

        requestUpdate(() => {
          const deltaPxX = (clientX - startX) / scale;
          const deltaPxY = (clientY - startY) / scale;

          const minPaperUnit = 1;
          const startWPx = unitToPx(startW, template.unit);
          const startHPx = unitToPx(startH, template.unit);
          const minWPx = unitToPx(minPaperUnit, template.unit);
          const minHPx = unitToPx(minPaperUnit, template.unit);

          const affectsTop = edge === 'top' || edge === 'top-left' || edge === 'top-right';
          const affectsBottom = edge === 'bottom' || edge === 'bottom-left' || edge === 'bottom-right';
          const affectsLeft = edge === 'left' || edge === 'top-left' || edge === 'bottom-left';
          const affectsRight = edge === 'right' || edge === 'top-right' || edge === 'bottom-right';

          let nextWUnit = startW;
          let nextHUnit = startH;
          let offsetContentPxX = 0;
          let offsetContentPxY = 0;

          if (affectsRight) {
            const proposedPx = Math.max(minWPx, startWPx + deltaPxX);
            nextWUnit = Math.max(minPaperUnit, Math.round(pxToUnit(proposedPx, template.unit)));
          }
          if (affectsBottom) {
            const proposedPx = Math.max(minHPx, startHPx + deltaPxY);
            nextHUnit = Math.max(minPaperUnit, Math.round(pxToUnit(proposedPx, template.unit)));
          }
          if (affectsLeft) {
            const proposedPx = Math.max(minWPx, startWPx - deltaPxX);
            nextWUnit = Math.max(minPaperUnit, Math.round(pxToUnit(proposedPx, template.unit)));
            const snappedPx = unitToPx(nextWUnit, template.unit);
            const appliedDelta = startWPx - snappedPx;
            offsetContentPxX = appliedDelta;
          }
          if (affectsTop) {
            const proposedPx = Math.max(minHPx, startHPx - deltaPxY);
            nextHUnit = Math.max(minPaperUnit, Math.round(pxToUnit(proposedPx, template.unit)));
            const snappedPx = unitToPx(nextHUnit, template.unit);
            const appliedDelta = startHPx - snappedPx;
            offsetContentPxY = appliedDelta;
          }

          const patch: Partial<LabelTemplate> = {};
          if (affectsLeft || affectsRight) patch.width = nextWUnit;
          if (affectsTop || affectsBottom) patch.height = nextHUnit;

          if ((offsetContentPxX !== 0 || offsetContentPxY !== 0) && startElements.length > 0) {
            const byId = new Map(startElements.map(s => [s.id, s]));
            patch.elements = template.elements.map((el) => {
              const s = byId.get(el.id);
              if (!s) return el;
              const nx = Math.max(0, s.x - offsetContentPxX);
              const ny = Math.max(0, s.y - offsetContentPxY);
              return (nx === el.x && ny === el.y) ? el : { ...el, x: nx, y: ny };
            });
          }

          onTemplateChange(patch);
        });
      }
    },
    [isPanning, onTemplateChange, scale, template.unit, requestUpdate]
  );

  const handlePointerUp = useCallback(() => {
    // 结束画布平移
    if (isPanning) {
      setIsPanning(false);
      panStartRef.current = null;
      panOffsetStartRef.current = null;
    }
    // Cancel pending animation frame
    if (nextFrameRef.current !== null) {
      cancelAnimationFrame(nextFrameRef.current);
      nextFrameRef.current = null;
    }

    const activeId = dragRef.current?.id || resizeRef.current?.id;
    if (activeId) {
      const domEl = document.getElementById(`element-${activeId}`);
      if (domEl) {
        domEl.classList.remove('z-50', 'opacity-90', 'shadow-xl', 'ring-2', 'ring-blue-400', 'ring-offset-2');
        domEl.style.cursor = '';
      }
    }

    if (lastUpdateRef.current) {
      const { id, ...patch } = lastUpdateRef.current;
      onUpdateElement(id, patch);
      lastUpdateRef.current = null;
    }
    dragRef.current = null;
    resizeRef.current = null;
    paperResizeRef.current = null;
    setPaperResizeCursor(null);
    document.body.style.cursor = '';
  }, [onUpdateElement]);

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.code === 'Space' && !e.repeat) {
        setIsSpacePressed(true);
      }
    };
    const onKeyUp = (e: KeyboardEvent) => {
      if (e.code === 'Space') {
        setIsSpacePressed(false);
        setIsPanning(false);
        panStartRef.current = null;
        panOffsetStartRef.current = null;
      }
    };
    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keydown', onKeyDown);
      window.removeEventListener('keyup', onKeyUp);
    };
  }, []);

  useEffect(() => {
    if (!paperResizeCursor) return;
    document.body.style.cursor = paperResizeCursor;
    return () => {
      document.body.style.cursor = '';
    };
  }, [paperResizeCursor]);

  // 画布初始居中:挂载或尺寸/缩放变化后让内容居中
  useEffect(() => {
    const el = scrollContainerRef.current;
    if (!el) return;
    const center = () => {
      el.scrollLeft = Math.max(0, (el.scrollWidth - el.clientWidth) / 2);
      el.scrollTop = Math.max(0, (el.scrollHeight - el.clientHeight) / 2);
    };
    const raf = requestAnimationFrame(center);
    const t = setTimeout(center, 100);
    return () => {
      cancelAnimationFrame(raf);
      clearTimeout(t);
    };
  }, [scale, baseW, baseH]);

  // Keyboard navigation for elements
  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (!selectedId) return;
    if (e.key === 'Delete' || e.key === 'Backspace') {
      // ... existing delete logic
      e.preventDefault();
      const idx = template.elements.findIndex((x) => x.id === selectedId);
      if (idx >= 0) {
        const next = template.elements.filter((x) => x.id !== selectedId);
        onDeleteElement(selectedId);
        onSelect(next[idx]?.id ?? next[idx - 1]?.id ?? null);
      }
      return;
    }

    const el = template.elements.find(x => x.id === selectedId);
    if (!el) return;

    // allow typing in inputs without triggering move? 
    // Actually our elements are not inputs (unless we implement inline edit).
    // But preventDefault is good.

    const step = e.shiftKey ? 1 : GRID_SIZE;
    let dx = 0;
    let dy = 0;

    switch (e.key) {
      case 'ArrowLeft': dx = -step; break;
      case 'ArrowRight': dx = step; break;
      case 'ArrowUp': dy = -step; break;
      case 'ArrowDown': dy = -step; break; // Wait, ArrowDown should be +step (y increases downwards)
      default: return;
    }

    // Fix: ArrowDown +step
    if (e.key === 'ArrowDown') dy = step;

    e.preventDefault();
    onUpdateElement(el.id, {
      x: Math.max(0, el.x + dx),
      y: Math.max(0, el.y + dy)
    });

  }, [selectedId, template.elements, onUpdateElement, onDeleteElement, onSelect]);

  const canvasClick = () => onSelect(null);

  // 容器的 Pan 处理
  // 容器的 Pan 处理
  const handleContainerPointerDown = (e: React.PointerEvent) => {
    if (isSpacePressed || e.button === 1) {
      e.preventDefault();
      setIsPanning(true);
      panStartRef.current = {
        x: e.clientX,
        y: e.clientY,
        scrollLeft: scrollContainerRef.current?.scrollLeft || 0,
        scrollTop: scrollContainerRef.current?.scrollTop || 0
      };
      (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
    }
  };

  const handleContainerPointerMove = (e: React.PointerEvent) => {
    if (isPanning && panStartRef.current && scrollContainerRef.current) {
      const dx = e.clientX - panStartRef.current.x;
      const dy = e.clientY - panStartRef.current.y;
      scrollContainerRef.current.scrollLeft = panStartRef.current.scrollLeft - dx;
      scrollContainerRef.current.scrollTop = panStartRef.current.scrollTop - dy;
    }
  };

  const handleContainerPointerUp = (e: React.PointerEvent) => {
    if (isPanning) {
      setIsPanning(false);
      panStartRef.current = null;
    }
  };

  return (
    <div className="flex-1 flex flex-col min-h-0 overflow-hidden bg-gray-100">
      {/* Label Preview 标题 + 网格/预览/缩放 */}
      <div className="shrink-0 px-4 py-2 border-b border-gray-200 bg-white flex items-center justify-between gap-2 flex-wrap z-10">
        <span className="text-sm font-medium text-gray-700">Label Preview</span>
        <div className="flex items-center gap-2 flex-wrap">
          {onPreview && (
            <button
              type="button"
              onClick={onPreview}
              className="h-8 px-3 rounded border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 text-xs font-medium shadow-sm transition-all active:scale-95"
            >
              Preview
            </button>
          )}
          {onTemplateChange && (
            <>
              <Select
                value={(() => {
                  const i = PRESET_LABEL_SIZES.findIndex(
                    (p) => p.width === template.width && p.height === template.height && p.unit === template.unit
                  );
                  return i >= 0 ? String(i) : 'custom';
                })()}
                onValueChange={(v: string) => {
                  if (v === 'custom') return;
                  const p = PRESET_LABEL_SIZES[Number(v)];
                  if (p) onTemplateChange({ width: p.width, height: p.height, unit: p.unit });
                }}
              >
                <SelectTrigger className="h-8 w-[130px] text-xs">
                  <SelectValue placeholder="Canvas size" />
                </SelectTrigger>
                <SelectContent>
                  {PRESET_LABEL_SIZES.map((p, i) => (
                    <SelectItem key={i} value={String(i)} className="text-xs">
                      {p.name}
                    </SelectItem>
                  ))}
                  <SelectItem value="custom" className="text-xs text-gray-500">
                    Custom
                  </SelectItem>
                </SelectContent>
              </Select>
              <button
                type="button"
                onClick={() => onTemplateChange({ showGrid: !showGrid })}
                className={cn(
                  'h-8 px-3 rounded border text-xs font-medium shadow-sm transition-colors',
                  showGrid ? 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50' : 'border-gray-300 bg-gray-100 text-gray-500'
                )}
              >
                {showGrid ? 'Hide grid' : 'Show grid'}
              </button>
            </>
          )}
          <div className="flex items-center gap-1 bg-white rounded border border-gray-300 p-0.5 shadow-sm h-8">
            <button
              type="button"
              onClick={onZoomOut}
              disabled={!onZoomOut}
              className="h-6 w-6 rounded hover:bg-gray-100 text-gray-600 disabled:opacity-50 disabled:pointer-events-none flex items-center justify-center text-sm font-medium active:scale-90 transition-transform"
              title="Zoom out"
            >

            </button>
            <span className="min-w-[3rem] text-center text-xs text-gray-600 font-medium">
              {Math.round(scale * 100)}%
            </span>
            <button
              type="button"
              onClick={onZoomIn}
              disabled={!onZoomIn}
              className="h-6 w-6 rounded hover:bg-gray-100 text-gray-600 disabled:opacity-50 disabled:pointer-events-none flex items-center justify-center text-sm font-medium active:scale-90 transition-transform"
              title="Zoom in"
            >
              +
            </button>
          </div>
        </div>
      </div>

      {/* Canvas Container */}
      <div
        ref={scrollContainerRef}
        className={cn(
          "flex-1 overflow-auto bg-gray-100 relative",
          isSpacePressed ? "cursor-grab active:cursor-grabbing" : ""
        )}
        onPointerDown={handleContainerPointerDown}
        onPointerMove={handleContainerPointerMove}
        onPointerUp={handleContainerPointerUp}
        onPointerLeave={handleContainerPointerUp}
      >
        <div
          style={{
            minWidth: '100%',
            minHeight: '100%',
            width: 'fit-content',
            height: 'fit-content',
            display: 'flex',
            padding: 50,
            boxSizing: 'border-box',
            transform: `translate(${panOffset.x}px, ${panOffset.y}px)`,
          }}
        >
          <div
            ref={canvasRef}
            tabIndex={0}
            className={cn(
              'relative bg-white shadow-lg border border-dashed border-gray-300 origin-top-left outline-none m-auto',
              isPanning ? 'cursor-grabbing' : 'cursor-grab'
            )}
            style={{
              width: baseW,
              height: baseH,
              transform: `scale(${scale})`,
              backgroundImage: showGrid
                ? `linear-gradient(to right, rgba(0,0,0,0.06) 1px, transparent 1px),
                   linear-gradient(to bottom, rgba(0,0,0,0.06) 1px, transparent 1px)`
                : undefined,
              backgroundSize: showGrid ? `${GRID_SIZE}px ${GRID_SIZE}px` : undefined,
              // 如果按住空格,禁用 canvas 内部的 pointer-events 以便拖动容器
              pointerEvents: isSpacePressed ? 'none' : 'auto',
              cursor: paperResizeCursor ?? undefined,
            }}
            onClick={(e) => {
              // 点击画布空白处取消选中
              const target = e.target as HTMLElement;
              const isOnElement = target.closest('[id^="element-"]');
              const isOnPaperResize =
                target.closest('[data-paper-resize-handle="true"]') ||
                target.closest('[title*="Drag to resize paper"]') ||
                target.closest('[title*="Drag to increase paper height"]') ||
                target.closest('[title*="Drag to increase paper width"]');
              if (!isOnElement && !isOnPaperResize) {
                onSelect(null);
              }
            }}
            onPointerDown={(e) => {
              // 空白处或标尺等非控件区域按下即开始平移(放宽判定:在画布内且未点到元素/纸张拖拽条)
              const target = e.target as HTMLElement;
              const isOnElement = target.closest('[id^="element-"]');
              const isOnPaperResize =
                target.closest('[data-paper-resize-handle="true"]') ||
                target.closest('[title*="Drag to resize paper"]') ||
                target.closest('[title*="Drag to increase paper height"]') ||
                target.closest('[title*="Drag to increase paper width"]');
              const isOnCanvasArea = canvasRef.current?.contains(target);
              if (isOnCanvasArea && !isOnElement && !isOnPaperResize && !dragRef.current && !resizeRef.current) {
                // 如果按住空格或中键,开始平移
                if (isSpacePressed || e.button === 1) {
                  e.preventDefault();
                  e.stopPropagation();
                  setIsPanning(true);
                  panOffsetStartRef.current = {
                    x: panOffset.x,
                    y: panOffset.y,
                    startX: e.clientX,
                    startY: e.clientY,
                  };
                  panStartRef.current = {
                    x: e.clientX,
                    y: e.clientY,
                    scrollLeft: scrollContainerRef.current?.scrollLeft ?? 0,
                    scrollTop: scrollContainerRef.current?.scrollTop ?? 0,
                  };
                  (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
                }
              }
            }}
            onPointerMove={handlePointerMove}
            onPointerUp={handlePointerUp}
            onKeyDown={handleKeyDown}
          >
            {template.showRuler && (
              <div className="absolute top-0 left-0 right-0 h-5 border-b border-gray-300 bg-gray-50 text-[10px] text-gray-500 flex items-center px-1 pointer-events-none select-none">
                {template.unit} {template.width} × {template.height}
              </div>
            )}
            {/* Paper resize: top */}
            {onTemplateChange && (
              <div
                className="absolute left-0 right-0 h-3 cursor-ns-resize flex items-center justify-center bg-gray-200/80 hover:bg-blue-400/30 border-b border-gray-300 text-[10px] text-gray-500 transition-colors"
                style={{ top: template.showRuler ? 20 : 0 }}
                title="Drag to resize paper (top edge)"
                data-paper-resize-handle="true"
                onPointerDown={(e) => beginPaperResize(e, 'top')}
              >

              </div>
            )}
            {/* Paper resize: left */}
            {onTemplateChange && (
              <div
                className="absolute top-0 bottom-0 w-3 cursor-ew-resize flex items-center justify-center bg-gray-200/80 hover:bg-blue-400/30 border-r border-gray-300 text-[10px] text-gray-500 transition-colors"
                style={{ top: template.showRuler ? 20 : 0 }}
                title="Drag to resize paper (left edge)"
                data-paper-resize-handle="true"
                onPointerDown={(e) => beginPaperResize(e, 'left')}
              >

              </div>
            )}
            {/* Paper resize: corners (optional but helpful) */}
            {onTemplateChange && (
              <>
                <div
                  className="absolute w-3 h-3 bg-gray-200/90 hover:bg-blue-400/30 border border-gray-300 cursor-nwse-resize transition-colors"
                  style={{ left: 0, top: template.showRuler ? 20 : 0 }}
                  title="Drag to resize paper (top-left corner)"
                  data-paper-resize-handle="true"
                  onPointerDown={(e) => beginPaperResize(e, 'top-left')}
                />
                <div
                  className="absolute w-3 h-3 bg-gray-200/90 hover:bg-blue-400/30 border border-gray-300 cursor-nesw-resize transition-colors"
                  style={{ right: 0, top: template.showRuler ? 20 : 0 }}
                  title="Drag to resize paper (top-right corner)"
                  data-paper-resize-handle="true"
                  onPointerDown={(e) => beginPaperResize(e, 'top-right')}
                />
                <div
                  className="absolute w-3 h-3 bg-gray-200/90 hover:bg-blue-400/30 border border-gray-300 cursor-nesw-resize transition-colors"
                  style={{ left: 0, bottom: 0 }}
                  title="Drag to resize paper (bottom-left corner)"
                  data-paper-resize-handle="true"
                  onPointerDown={(e) => beginPaperResize(e, 'bottom-left')}
                />
                <div
                  className="absolute w-3 h-3 bg-gray-200/90 hover:bg-blue-400/30 border border-gray-300 cursor-nwse-resize transition-colors"
                  style={{ right: 0, bottom: 0 }}
                  title="Drag to resize paper (bottom-right corner)"
                  data-paper-resize-handle="true"
                  onPointerDown={(e) => beginPaperResize(e, 'bottom-right')}
                />
              </>
            )}
            {/* 纸张尺寸拖拽:底部拉高 */}
            {onTemplateChange && (
              <div
                className="absolute bottom-0 left-0 right-0 h-3 cursor-ns-resize flex items-center justify-center bg-gray-200/80 hover:bg-blue-400/30 border-t border-gray-300 text-[10px] text-gray-500 transition-colors"
                title="Drag to resize paper (bottom edge)"
                data-paper-resize-handle="true"
                onPointerDown={(e) => beginPaperResize(e, 'bottom')}
              >

              </div>
            )}
            {/* 纸张尺寸拖拽:右侧拉宽 */}
            {onTemplateChange && (
              <div
                className="absolute top-0 right-0 bottom-0 w-3 cursor-ew-resize flex items-center justify-center bg-gray-200/80 hover:bg-blue-400/30 border-l border-gray-300 text-[10px] text-gray-500 transition-colors"
                title="Drag to resize paper (right edge)"
                data-paper-resize-handle="true"
                onPointerDown={(e) => beginPaperResize(e, 'right')}
              >

              </div>
            )}
            {template.elements.map((el) => {
              const isPrintField = isPrintInputElement(el);
              return (
              <div
                key={el.id}
                id={`element-${el.id}`}
                className={cn(
                  'absolute box-border cursor-move overflow-hidden transition-shadow',
                  el.border === 'line' && 'border border-gray-400',
                  el.border === 'dotted' && 'border border-dotted border-gray-400',
                  selectedId === el.id && 'ring-2 ring-blue-500 ring-offset-1 z-10'
                )}
                style={{
                  left: el.x,
                  top: el.y,
                  width: el.width,
                  height: el.height,
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  onSelect(el.id);
                }}
                onPointerDown={(e) => handlePointerDown(e, el.id)}
              >
                <div
                  className={cn(
                    'w-full h-full min-h-0 relative',
                    isPrintField &&
                      'rounded-sm border-2 border-dashed border-amber-500/85 bg-amber-50/35',
                  )}
                >
                  <ElementContent el={el} isAppPrintField={isPrintField} />
                </div>
                {selectedId === el.id && (
                  <>
                    {/* 4 Corners */}
                    {(['nw', 'ne', 'sw', 'se'] as const).map((corner) => (
                      <div
                        key={corner}
                        className="absolute w-4 h-4 bg-white border-2 border-blue-500 rounded-full z-20 shadow-md hover:scale-110 transition-transform"
                        style={{
                          cursor: 'nwse-resize',
                          top: corner.startsWith('n') ? -6 : undefined,
                          bottom: corner.startsWith('s') ? -6 : undefined,
                          left: corner.endsWith('w') ? -6 : undefined,
                          right: corner.endsWith('e') ? -6 : undefined,
                        }}
                        onPointerDown={(e) => {
                          e.stopPropagation();
                          const el0 = template.elements.find((x) => x.id === el.id)!;
                          resizeRef.current = {
                            id: el.id,
                            corner,
                            startX: e.clientX,
                            startY: e.clientY,
                            w: el0.width,
                            h: el0.height,
                            elX: el0.x,
                            elY: el0.y,
                          };
                          (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
                        }}
                      />
                    ))}
                    {/* 4 Edges */}
                    {(['n', 's', 'w', 'e'] as const).map((edge) => (
                      <div
                        key={edge}
                        className="absolute bg-blue-500/50 border border-white/50 rounded-sm z-10 shadow-sm hover:bg-blue-600"
                        style={{
                          cursor: edge === 'n' || edge === 's' ? 'ns-resize' : 'ew-resize',
                          width: edge === 'n' || edge === 's' ? '20px' : '6px',
                          height: edge === 'n' || edge === 's' ? '6px' : '20px',
                          top: edge === 'n' ? -3 : edge === 's' ? undefined : '50%',
                          bottom: edge === 's' ? -3 : undefined,
                          left: edge === 'w' ? -3 : edge === 'e' ? undefined : '50%',
                          right: edge === 'e' ? -3 : undefined,
                          transform: edge === 'n' || edge === 's' ? 'translateX(-50%)' : 'translateY(-50%)',
                        }}
                        onPointerDown={(e) => {
                          e.stopPropagation();
                          const el0 = template.elements.find((x) => x.id === el.id)!;

                          const domEl = document.getElementById(`element-${el.id}`);
                          if (domEl) {
                            domEl.classList.add('z-50', 'opacity-90');
                          }

                          resizeRef.current = {
                            id: el.id,
                            corner: edge,
                            startX: e.clientX,
                            startY: e.clientY,
                            w: el0.width,
                            h: el0.height,
                            elX: el0.x,
                            elY: el0.y,
                          };
                          (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
                        }}
                      />
                    ))}
                  </>
                )}
              </div>
            );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

/** Preview only: no grid, no rulers, no drag; scale to fit. */
export function LabelPreviewOnly({
  template,
  maxWidth = 480,
}: {
  template: LabelTemplate;
  maxWidth?: number;
}) {
  const baseW = unitToPx(template.width, template.unit);
  const baseH = unitToPx(template.height, template.unit);
  const minX = Math.min(0, ...template.elements.map((el) => el.x));
  const minY = Math.min(0, ...template.elements.map((el) => el.y));
  const maxX = Math.max(baseW, ...template.elements.map((el) => el.x + el.width));
  const maxY = Math.max(baseH, ...template.elements.map((el) => el.y + el.height));
  const contentW = Math.max(1, maxX - minX);
  const contentH = Math.max(1, maxY - minY);
  const scaleToFit = maxWidth ? Math.min(maxWidth / contentW, maxWidth / contentH, 2) : 1;
  const displayW = contentW * scaleToFit;
  const displayH = contentH * scaleToFit;
  // 与编辑区一致:内层 baseW×baseH,transformOrigin 0 0 缩放,保证位置/样式一致
  return (
    <div
      className="inline-flex items-center justify-center p-4 bg-gray-100 rounded"
      style={{ minWidth: displayW + 32 }}
    >
      <div style={{ width: displayW, height: displayH }} className="relative bg-white shadow-lg overflow-hidden">
        <div
          className="origin-top-left"
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            width: contentW,
            height: contentH,
            transform: `scale(${scaleToFit})`,
            transformOrigin: '0 0',
          }}
        >
          {template.elements.map((el) => {
            const isPrintField = isPrintInputElement(el);
            return (
            <div
              key={el.id}
              className="absolute box-border overflow-hidden pointer-events-none flex items-center justify-center text-xs"
              style={{
                left: el.x - minX,
                top: el.y - minY,
                width: el.width,
                height: el.height,
                border: el.border === 'line' ? '1px solid #999' : el.border === 'dotted' ? '1px dotted #999' : undefined,
              }}
            >
              <div
                className={cn(
                  'w-full h-full min-h-0 relative',
                  isPrintField &&
                    'rounded-sm border-2 border-dashed border-amber-500/85 bg-amber-50/35',
                )}
              >
                <ElementContent el={el} isAppPrintField={isPrintField} />
              </div>
            </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}