All files / packages/design-tokens/src/style-dictionary/utils mobile-helpers.js

95.83% Statements 345/360
87.76% Branches 244/278
98.46% Functions 64/65
96% Lines 336/350

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                                                                  6x             6x                   6x                       6x                       6x                                       6x             6x                         6x             6x               6x                             16345x               6x 16322x               6x 6x 12x 11x     6x                   195x 16313x                 6x 4x             6x 498x                 6621x                               7812x                             6043x                                   3000x 2997x 572228x                               662x 3x     659x   655x   655x 655x 17x       638x 638x 82x       556x 556x 543x       13x                   183x 5x     178x   175x   175x 175x 165x       10x 10x 8x       2x                   179x 3x     176x   174x   174x 174x 160x       14x 14x 12x       2x                             205x 42x   163x 157x 157x 150x     13x                               9x   9x   9x     22x     23x 9x   14x       22x 9x   13x       9x 9x 9x                       7x   7x   7x     16x       16x         7x                         8x                             23x 5x       18x 1x 1x   17x   17x 17x   17x 14x     3x                 10116x                         4192x 18x 18x 17x   1x     4174x 34x     4140x                           3918x                   22730x 2x     22728x                                     8x   8x     8x 1x 1x 1x       7x       7x   7x     7x   5x   5x 1x 1x   1x 1x     1x   1x   1x         1x 1x           7x 7x   6x   6x                                                           2x 2x   2x   2x           2x 2x 2x   2x 2x 2x       2x                             40x 9x     31x   164x 164x     31x                                   53x                   53x 541x   464x     464x 75x 75x       389x 15x 15x       374x   14x 14x   83x 83x   7x 7x   253x 253x     17x 16x   1x         53x                                 16x 16x   16x 24x 24x 24x     24x 1x 1x         1x 1x 1x         23x 23x 23x 23x       16x                         21x   21x 84x 84x 84x   84x 80x 80x       21x                                       25x 25x   25x 266x 266x 266x 266x     266x 266x 266x   266x 9x           266x 266x     266x 162x 162x 162x 162x         104x       25x                               18x 18x   18x 76x 76x 76x 76x   76x 76x     76x 11x 11x         11x 11x 11x         65x       18x                         15x   15x 15x 15x 15x   15x 15x 15x       15x                         8641x   8641x 299x   897x       8641x                                                     6x 6x     6x 1x       5x 1x       6x 1x       3x       3x                                                                         6x                                   3x 14x 1x         2x 13x 1x           1x                                   2x 2x   2x                                                                             148x   717x   103x 32x     71x 71x   71x 667x 667x 667x 667x     667x 294x 294x 294x 294x 294x 294x         373x 373x 373x     373x 14x   359x         71x 71x                                                     3x   37x 88x     37x 11x       26x 126x 126x 126x 126x 126x     26x 26x   26x 88x 88x 88x 88x     88x 4x 4x 4x 4x 4x         84x 84x 84x       26x 26x          
/**
 * Shared utilities for iOS and Android mobile token formatters.
 *
 * Tokens are processed based on their $type property.
 *
 * Supported types:
 * - color: Colors (OKLCH, hex)
 * - dimension: Lengths with units (rem, px, %)
 * - duration: Time values (s, ms)
 * - number: Unitless numbers (line heights, ratios)
 * - fontWeight: Font weight values
 * - fontFamily: Font family strings
 *
 * Excluded types (require special handling not suitable for flat output):
 * - shadow: Complex composite type
 */
 
import {
  valueUnitToString,
  getRawValueUnitValue,
  isValueUnitObject,
  extractUnit,
} from './value-unit-helpers.js';
import { MODE_EXTENSION_KEY } from './constants.js';
 
// ============================================================================
// EXCLUSION LISTS
// ============================================================================
 
/**
 * Token types that are excluded from mobile output.
 * These require complex composite handling not suitable for flat output.
 */
export const EXCLUDED_TYPES = new Set(['shadow']);
 
/**
 * Token categories that are intentionally excluded from mobile output.
 * - shadow: Complex composite type requiring platform-specific shadow APIs
 * - ratio: Internal tokens not published publicly
 */
export const EXCLUDED_CATEGORIES = new Set(['shadow', 'ratio']);
 
// ============================================================================
// PATH CONSTANTS
// ============================================================================
 
/**
 * Token path indices for common patterns
 * Example path: ['slds', 'g', 'color', 'neutral', 'base', '100']
 */
export const PATH_INDEX = {
  NAMESPACE: 0, // 'slds' or 'alias'
  SCOPE: 1, // 'g' (global), 'r' (reference), 'c' (component)
  CATEGORY: 2, // 'color', 'spacing', 'font', etc.
  SUBCATEGORY: 3, // 'neutral', 'size', 'palette', etc.
  MODIFIER: 4, // 'base', 'height', etc.
  SCALE: 5, // '100', '50', etc.
};
 
/**
 * Category string constants to avoid typos and enable refactoring
 */
export const CATEGORY = {
  COLOR: 'color',
  SPACING: 'spacing',
  SIZING: 'sizing',
  RADIUS: 'radius',
  FONT: 'font',
  DURATION: 'duration',
};
 
/**
 * Color subcategory constants
 */
export const COLOR_SUBCATEGORY = {
  PALETTE: 'palette',
  NEUTRAL: 'neutral',
  BRAND: 'brand',
  ERROR: 'error',
  WARNING: 'warning',
  SUCCESS: 'success',
  INFO: 'info',
  SURFACE: 'surface',
  BORDER: 'border',
  ON: 'on',
  TEXT: 'text',
  ICON: 'icon',
  BACKGROUND: 'background',
  SHADOW: 'shadow',
};
 
/**
 * Color modifier constants
 */
export const COLOR_MODIFIER = {
  BASE: 'base',
};
 
/**
 * Font subcategory constants
 */
export const FONT_SUBCATEGORY = {
  SIZE: 'size',
  WEIGHT: 'weight',
  FAMILY: 'family',
  SCALE: 'scale',
  LINE: 'line',
  LINECLAMP: 'lineclamp',
  LINE_CLAMP: 'line-clamp',
};
 
/**
 * Font modifier constants (for line.height path)
 */
export const FONT_MODIFIER = {
  HEIGHT: 'height',
};
 
/**
 * Namespace constants
 */
export const NAMESPACE = {
  SLDS: 'slds',
  ALIAS: 'alias',
};
 
/**
 * Scope constants
 */
export const SCOPE = {
  GLOBAL: 'g',
  REFERENCE: 'r',
  COMPONENT: 'c',
};
 
// ============================================================================
// TOKEN FILTERS
// ============================================================================
 
/**
 * Check if token is a global scope token (slds.g.*)
 * @param {object} token - Token object
 * @returns {boolean}
 */
export const isGlobalToken = (token) => token.path[0] === 'slds' && token.path[1] === 'g';
 
/**
 * Check if token is a global token of a specific category
 * @param {object} token - Token object
 * @param {string} category - Category to match (e.g., 'spacing', 'sizing', 'duration')
 * @returns {boolean}
 */
export const isGlobalTokenOfCategory = (token, category) =>
  isGlobalToken(token) && token.path[2] === category;
 
/**
 * Detect all unique global token categories from the token set
 * @param {Array} tokens - All tokens
 * @returns {Set<string>} - Set of unique token categories (e.g., 'color', 'spacing', 'sizing')
 */
export function detectGlobalTokenCategories(tokens) {
  const categories = new Set();
  tokens.forEach((token) => {
    if (isGlobalToken(token) && token.path[2]) {
      categories.add(token.path[2]);
    }
  });
  return categories;
}
 
/**
 * Get tokens for a specific category, excluding certain types
 * @param {Array} tokens - All tokens
 * @param {string} category - Category to filter (e.g., 'spacing', 'color')
 * @returns {Array} - Tokens in that category
 */
export function getTokensForCategory(tokens, category) {
  return tokens.filter(
    (token) => isGlobalTokenOfCategory(token, category) && !(token.$type && EXCLUDED_TYPES.has(token.$type)),
  );
}
 
/**
 * Check if token is a reference scope token (slds.r.*)
 * @param {object} token - Token object
 * @returns {boolean}
 */
export const isReferenceToken = (token) =>
  token.path[0] === NAMESPACE.SLDS && token.path[1] === SCOPE.REFERENCE;
 
/**
 * Check if token is a palette token (alias.palette.*)
 * @param {object} token - Token object
 * @returns {boolean}
 */
export const isPaletteToken = (token) =>
  token.path[0] === NAMESPACE.ALIAS && token.path[1] === COLOR_SUBCATEGORY.PALETTE;
 
/**
 * Check if token is a system color token (slds.g.color.{family}.base.{scale})
 * System colors are the foundational color values organized by color family (neutral, brand, error, etc.)
 * @param {object} token - Token object
 * @returns {boolean}
 */
export function isSystemColorToken(token) {
  return (
    token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
    token.path[PATH_INDEX.SCOPE] === SCOPE.GLOBAL &&
    token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
    token.path[PATH_INDEX.MODIFIER] === COLOR_MODIFIER.BASE &&
    token.path.length >= 6
  );
}
 
/**
 * Check if token is a reference color token (slds.r.color.*)
 * Reference colors are brand-specific colors that may reference palette colors
 * @param {object} token - Token object
 * @returns {boolean}
 */
export function isReferenceColorToken(token) {
  return (
    token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
    token.path[PATH_INDEX.SCOPE] === SCOPE.REFERENCE &&
    token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
    token.path.length >= 4
  );
}
 
/**
 * Check if token is a semantic color token (slds.g.color.{semantic-name})
 * Semantic colors are contextual colors (surface, border, accent, etc.) that reference system/reference colors
 * @param {object} token - Token object
 * @returns {boolean}
 */
export function isSemanticColorToken(token) {
  return (
    token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
    token.path[PATH_INDEX.SCOPE] === SCOPE.GLOBAL &&
    token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
    token.path[PATH_INDEX.SUBCATEGORY] !== COLOR_SUBCATEGORY.PALETTE &&
    token.path[PATH_INDEX.MODIFIER] !== COLOR_MODIFIER.BASE &&
    !isPaletteToken(token) &&
    token.path.length >= 4
  );
}
 
/**
 * Helper to find a token by its reference string
 * @param {string} referenceString - Reference string like "{slds.g.spacing.1}"
 * @param {Array} tokens - All tokens
 * @returns {object|null} - Found token or null
 */
export function findTokenByReference(referenceString, tokens) {
  if (!isTokenReference(referenceString)) return null;
  const refPath = referenceString.slice(1, -1).split('.');
  return tokens.find((t) => t.path.join('.') === refPath.join('.')) || null;
}
 
// ============================================================================
// DIMENSION CONVERSIONS
// ============================================================================
 
/**
 * Convert dimension value to numeric points (for iOS CGFloat or Android dp)
 * Supports: px (1:1), rem (1rem = 16), % (100% = 100)
 *
 * @param {string|object} rawValue - Dimension value
 * @param {string} tokenPath - Token path for error messages
 * @returns {number|null} - Converted value or null if unsupported
 */
export function convertDimensionToNumeric(rawValue, tokenPath = '') {
  if (rawValue === null || rawValue === undefined) {
    return null;
  }
 
  const valueStr = valueUnitToString(rawValue, tokenPath);
 
  Eif (typeof valueStr === 'string') {
    // Handle percentage (for circle radius)
    const percentMatch = valueStr.match(/^([\d.]+)%$/);
    if (percentMatch) {
      return parseFloat(percentMatch[1]);
    }
 
    // Handle px (1:1)
    const pxMatch = valueStr.match(/^([\d.]+)px$/);
    if (pxMatch) {
      return parseFloat(pxMatch[1]);
    }
 
    // Handle rem (1rem = 16)
    const remMatch = valueStr.match(/^([\d.]+)rem$/);
    if (remMatch) {
      return parseFloat(remMatch[1]) * 16;
    }
  }
 
  return null;
}
 
/**
 * Convert duration to seconds (for iOS TimeInterval)
 * @param {string|object} rawValue - Duration value
 * @param {string} tokenPath - Token path for error messages
 * @returns {number|null} - Seconds or null
 */
export function convertDurationToSeconds(rawValue, tokenPath = '') {
  if (rawValue === null || rawValue === undefined) {
    return null;
  }
 
  const valueStr = valueUnitToString(rawValue, tokenPath);
 
  Eif (typeof valueStr === 'string') {
    // Handle seconds (1:1)
    const secondsMatch = valueStr.match(/^([\d.]+)s$/);
    if (secondsMatch) {
      return parseFloat(secondsMatch[1]);
    }
 
    // Handle milliseconds (divide by 1000)
    const msMatch = valueStr.match(/^([\d.]+)ms$/);
    if (msMatch) {
      return parseFloat(msMatch[1]) / 1000;
    }
  }
 
  return null;
}
 
/**
 * Convert duration to milliseconds (for Android Long)
 * @param {string|object} rawValue - Duration value
 * @param {string} tokenPath - Token path for error messages
 * @returns {number|null} - Milliseconds (integer) or null
 */
export function convertDurationToMs(rawValue, tokenPath = '') {
  if (rawValue === null || rawValue === undefined) {
    return null;
  }
 
  const valueStr = valueUnitToString(rawValue, tokenPath);
 
  Eif (typeof valueStr === 'string') {
    // Handle seconds (multiply by 1000)
    const secondsMatch = valueStr.match(/^([\d.]+)s$/);
    if (secondsMatch) {
      return Math.round(parseFloat(secondsMatch[1]) * 1000);
    }
 
    // Handle milliseconds (1:1)
    const msMatch = valueStr.match(/^([\d.]+)ms$/);
    if (msMatch) {
      return Math.round(parseFloat(msMatch[1]));
    }
  }
 
  return null;
}
 
// ============================================================================
// NUMBER EXTRACTION
// ============================================================================
 
/**
 * Extract a plain number value from a token
 * Works for $type: number tokens (line heights, ratios, etc.)
 *
 * @param {*} rawValue - Token value
 * @returns {number|null} - Numeric value or null
 */
export function extractNumber(rawValue) {
  if (typeof rawValue === 'number') {
    return rawValue;
  }
  if (typeof rawValue === 'string') {
    const num = parseFloat(rawValue);
    if (!isNaN(num)) {
      return num;
    }
  }
  return null;
}
 
// ============================================================================
// NAMING UTILITIES
// ============================================================================
 
/**
 * Convert token path to iOS constant name (camelCase with prefix)
 * Example: ['slds', 'g', 'spacing', '1'] -> "salesforceCosmosSpacing1"
 *
 * @param {Array<string>} path - Token path array
 * @param {string} suffix - Optional suffix (e.g., 'Light', 'Dark')
 * @returns {string} - iOS constant name
 */
export function pathToiOSConstantName(path, suffix = '') {
  const TOKEN_PREFIX = 'salesforceCosmos';
  // Remove first two segments (slds.g or slds.s)
  const relevantPath = path.slice(2);
 
  const camelCase = relevantPath
    .map((segment, index) => {
      // Convert hyphens to camelCase (e.g., "line-clamp" -> "lineClamp")
      const camelSegment = segment
        .split('-')
        .map((word, wordIndex) => {
          if (wordIndex === 0 && index === 0) {
            return word; // First word of first segment stays lowercase
          }
          return word.charAt(0).toUpperCase() + word.slice(1);
        })
        .join('');
 
      if (index === 0) {
        return camelSegment;
      }
      return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
    })
    .join('');
 
  const capitalizedCamelCase = camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
  const suffixPart = suffix ? suffix.charAt(0).toUpperCase() + suffix.slice(1) : '';
  return `${TOKEN_PREFIX}${capitalizedCamelCase}${suffixPart}`;
}
 
/**
 * Convert token path to Android constant name (underscore-separated with prefix)
 * Example: ['slds', 'g', 'spacing', '1'] -> "SalesforceCosmos_Spacing_1"
 *
 * @param {Array<string>} path - Token path array
 * @param {string} suffix - Optional suffix (e.g., 'Light', 'Dark', 'Percent')
 * @returns {string} - Android constant name
 */
export function pathToAndroidConstantName(path, suffix = '') {
  const TOKEN_PREFIX = 'SalesforceCosmos';
  // Remove first two segments (slds.g or slds.s)
  const relevantPath = path.slice(2);
 
  const name = relevantPath
    .map((segment) => {
      // Convert hyphens to underscores, then split camelCase/PascalCase words
      return segment
        .replace(/-/g, '_') // Convert hyphens to underscores first
        .replace(/([a-z])([A-Z])/g, '$1_$2') // Split camelCase
        .split('_')
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join('_');
    })
    .join('_');
 
  return `${TOKEN_PREFIX}_${name}${suffix ? '_' + suffix : ''}`;
}
 
// ============================================================================
// CATEGORY LABEL FORMATTING
// ============================================================================
 
/**
 * Format a category name for use in section headers
 * @param {string} category - Category name (e.g., 'spacing', 'font')
 * @returns {string} - Formatted label (e.g., 'Spacing', 'Font')
 */
export function formatCategoryLabel(category) {
  return category.charAt(0).toUpperCase() + category.slice(1);
}
 
// ============================================================================
// TOKEN REFERENCE RESOLUTION
// ============================================================================
 
/**
 * Resolve a token reference to its raw value, handling circular references
 * @param {string} reference - Token reference in format "{slds.g.color.brand}"
 * @param {Array} allTokens - All tokens for reference resolution
 * @param {Set} visited - Set of visited references to prevent circular loops
 * @returns {*} - Resolved token value or null if not found
 */
export function resolveTokenReference(reference, allTokens, visited = new Set()) {
  if (!reference || typeof reference !== 'string' || !reference.startsWith('{') || !reference.endsWith('}')) {
    return null;
  }
 
  // Prevent circular references
  if (visited.has(reference)) {
    console.warn(`[Mobile] Circular token reference detected: ${reference}`);
    return null;
  }
  visited.add(reference);
 
  const refPath = reference.slice(1, -1).split('.');
  const refToken = allTokens.find((t) => t.path.join('.') === refPath.join('.'));
 
  if (refToken) {
    return getRawValueUnitValue(refToken);
  }
 
  return null;
}
 
/**
 * Check if a value is a token reference
 * @param {*} value - Value to check
 * @returns {boolean} - True if value is a token reference
 */
export function isTokenReference(value) {
  return typeof value === 'string' && value.startsWith('{') && value.endsWith('}');
}
 
// ============================================================================
// OKLCH PARSING
// ============================================================================
 
/**
 * Parse OKLCH color from string or object format
 * @param {string|object} oklch - OKLCH color in string "oklch(L C H)" or object {colorSpace: "oklch", components: [L, C, H]}
 * @returns {Array|null} - [L, C, H] components or null if invalid
 */
export function parseOklch(oklch) {
  if (typeof oklch === 'string' && oklch.startsWith('oklch(')) {
    const match = oklch.match(/oklch\(\s*([\d.]+)\s+([\d.]+)\s+([\d.]+)\s*\)/);
    if (match) {
      return match.slice(1, 4).map(Number);
    }
    return null;
  }
 
  if (typeof oklch === 'object' && oklch?.colorSpace === 'oklch' && Array.isArray(oklch.components)) {
    return oklch.components;
  }
 
  return null;
}
 
// ============================================================================
// TOKEN FILTERING
// ============================================================================
 
/**
 * Get the description from a token
 * Checks token.original.$description (preserved from source) and token.$description (fallback)
 * @param {object} token - Token object
 * @returns {string|null} - Description string or null if not found
 */
export function getTokenDescription(token) {
  return token.original?.$description || token.$description || null;
}
 
/**
 * Check if a token should be skipped (deprecated or excluded type)
 * @param {object} token - Token to check
 * @returns {boolean} - True if token should be skipped
 * @throws {Error} - If token is missing $type
 */
export function shouldSkipToken(token) {
  if (!token.$type) {
    throw new Error(`[Mobile] Token missing $type: ${token.path?.join('.') || token.name || 'unknown'}`);
  }
 
  return (
    token.$deprecated || token.deprecated || token.original?.$deprecated || EXCLUDED_TYPES.has(token.$type)
  );
}
 
// ============================================================================
// COLOR TOKEN PROCESSING
// ============================================================================
 
/**
 * Process light/dark mode color variants for a token
 * Returns an object with light and dark color values (platform-specific format)
 *
 * @param {object} token - Token object
 * @param {Function} resolveColorFn - Function to resolve color (resolveColorToHex or resolveColorToRGB)
 * @param {Array} allTokens - All tokens for reference resolution
 * @returns {object} - { light: resolvedColor, dark: resolvedColor } or null
 */
export function processLightDarkColorToken(token, resolveColorFn, allTokens) {
  const tokenValue = getRawValueUnitValue(token);
  // Also check original value in case Style Dictionary has transformed it
  const originalValue = token.original?.$value;
 
  // Check for light/dark structure in tokenValue
  if (tokenValue && typeof tokenValue === 'object' && tokenValue.light && tokenValue.dark) {
    const light = resolveColorFn(tokenValue.light, allTokens);
    const dark = resolveColorFn(tokenValue.dark, allTokens);
    return { light, dark };
  }
 
  // Check for dark mode extension
  Eif (tokenValue && typeof tokenValue === 'string') {
    // First check if current token has dark mode extension
    // Check both token.$extensions and token.original.$extensions (Style Dictionary may transform)
    let darkValue =
      token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value ||
      token.original?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
    let lightValue = tokenValue;
 
    // If no dark mode on current token, check if it references another token with dark mode
    if (!darkValue) {
      // Check original value first (before Style Dictionary transforms)
      const valueToCheck = isTokenReference(originalValue) ? originalValue : tokenValue;
 
      if (isTokenReference(valueToCheck)) {
        const refPath = valueToCheck.slice(1, -1).split('.');
        const refToken = allTokens.find((t) => {
          // Match token path (Style Dictionary uses array format)
          const tokenPath = t.path.join('.');
          return tokenPath === refPath.join('.');
        });
 
        Eif (refToken) {
          // Use the referenced token's value for light
          const refLightValue = getRawValueUnitValue(refToken) || refToken.original?.$value;
          // Check both refToken.$extensions and refToken.original.$extensions for dark mode
          darkValue =
            refToken.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value ||
            refToken.original?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
 
          // If we found a reference, use the referenced token's light value
          Eif (refLightValue) {
            lightValue = refLightValue;
          }
        }
      }
    }
 
    const light = resolveColorFn(lightValue, allTokens);
    if (!light) return null;
 
    const dark = darkValue ? resolveColorFn(darkValue, allTokens) : light; // Use light if no dark variant
 
    return { light, dark };
  }
 
  // Simple color value (palette colors) - no light/dark variants
  if (tokenValue) {
    const color = resolveColorFn(tokenValue, allTokens);
    return color ? { simple: color } : null;
  }
 
  return null;
}
 
/**
 * Generate color token output (shared between platforms)
 * @param {object} token - Token object
 * @param {Array} allTokens - All tokens for reference resolution
 * @param {Function} resolveColorFn - Platform-specific color resolver (resolveColorToHex or resolveColorToRGB)
 * @param {Function} formatColorFn - Platform-specific color formatter (toComposeColor or toSwiftUIColor)
 * @param {Function} nameFormatter - Platform-specific naming function (pathToAndroidConstantName or pathToiOSConstantName)
 * @param {string} declarationKeyword - Platform-specific declaration keyword ("val" or "let")
 * @returns {string} - Formatted output
 */
export function outputColorToken(
  token,
  allTokens,
  resolveColorFn,
  formatColorFn,
  nameFormatter,
  declarationKeyword,
) {
  const colorVariants = processLightDarkColorToken(token, resolveColorFn, allTokens);
  Iif (!colorVariants) return '';
 
  let output = '';
 
  Iif (colorVariants.simple) {
    // Simple color value (palette colors) - no light/dark variants
    const name = nameFormatter(token.path);
    output += `${declarationKeyword} ${name} = ${formatColorFn(colorVariants.simple)}\n`;
  } else {
    // Light/dark variants
    Eif (colorVariants.light) {
      const lightName = nameFormatter(token.path, 'Light');
      output += `${declarationKeyword} ${lightName} = ${formatColorFn(colorVariants.light)}\n`;
    }
    Eif (colorVariants.dark) {
      const darkName = nameFormatter(token.path, 'Dark');
      output += `${declarationKeyword} ${darkName} = ${formatColorFn(colorVariants.dark)}\n`;
    }
  }
 
  return output;
}
 
// ============================================================================
// FONT STACK PROCESSING
// ============================================================================
 
/**
 * Process a font family string into a clean font stack
 * Removes quotes, trims whitespace, and filters empty fonts
 *
 * @param {string} rawValue - Raw font family string (e.g., "Consolas, Menlo, Monaco")
 * @returns {string|null} - Cleaned font stack or null if empty
 */
export function processFontStack(rawValue) {
  if (typeof rawValue !== 'string' || !rawValue.trim()) {
    return null;
  }
 
  const fontStack = rawValue
    .split(',')
    .map((font) => font.trim().replace(/['"]/g, ''))
    .filter((font) => font.length > 0)
    .join(', ');
 
  return fontStack || null;
}
 
/**
 * Group font tokens by subcategory (sizes, weights, families, etc.)
 * Reduces cognitive complexity by extracting the grouping logic from format functions.
 *
 * @param {Array} fontTokens - Array of font tokens to group
 * @returns {Object} - Object with grouped font tokens
 * @returns {Array} .sizes - Font size tokens
 * @returns {Array} .weights - Font weight tokens
 * @returns {Array} .families - Font family tokens
 * @returns {Array} .lineHeights - Line height tokens
 * @returns {Array} .scales - Font scale tokens
 * @returns {Array} .truncation - Line clamp/truncation tokens
 * @returns {Array} .other - Other font tokens that don't fit the above categories
 */
export function groupFontTokens(fontTokens) {
  const groups = {
    sizes: [],
    weights: [],
    families: [],
    lineHeights: [],
    scales: [],
    truncation: [],
    other: [],
  };
 
  fontTokens.forEach((token) => {
    if (shouldSkipToken(token)) return;
 
    const subCategory = token.path[PATH_INDEX.SUBCATEGORY];
 
    // Check for line.height (two segments)
    if (subCategory === FONT_SUBCATEGORY.LINE && token.path[PATH_INDEX.MODIFIER] === FONT_MODIFIER.HEIGHT) {
      groups.lineHeights.push(token);
      return;
    }
 
    // Check for line-clamp/lineclamp
    if (subCategory === FONT_SUBCATEGORY.LINECLAMP || subCategory === FONT_SUBCATEGORY.LINE_CLAMP) {
      groups.truncation.push(token);
      return;
    }
 
    // Switch on subcategory for standard font tokens
    switch (subCategory) {
      case FONT_SUBCATEGORY.SIZE:
        groups.sizes.push(token);
        break;
      case FONT_SUBCATEGORY.WEIGHT:
        groups.weights.push(token);
        break;
      case FONT_SUBCATEGORY.FAMILY:
        groups.families.push(token);
        break;
      case FONT_SUBCATEGORY.SCALE:
        groups.scales.push(token);
        break;
      default:
        // Check if subcategory starts with family- prefix (e.g., family-base, family-monospace)
        if (subCategory && subCategory.startsWith(FONT_SUBCATEGORY.FAMILY + '-')) {
          groups.families.push(token);
        } else {
          groups.other.push(token);
        }
    }
  });
 
  return groups;
}
 
/**
 * Generate font family output for Android/iOS
 * Reduces cognitive complexity by extracting font family processing logic.
 *
 * @param {Array} fontFamilies - Array of font family tokens
 * @param {Array} allTokens - All tokens (for reference resolution)
 * @param {Object} config - Configuration object
 * @param {Function} config.pathToPropertyName - Function to convert path to property name
 * @param {Function} config.formatValue - Function to format a value (propName, value) => string
 * @param {Function} config.formatReference - Function to format a reference (propName, refPropName) => string
 * @param {string} config.objectName - Name of the object/enum for reference (e.g., 'SalesforceCosmosFontFamily')
 * @returns {Array} - Array of output strings for each font family
 */
export function generateFontFamilyOutput(fontFamilies, allTokens, config) {
  const { pathToPropertyName, formatValue, formatReference, objectName } = config;
  const output = [];
 
  fontFamilies.forEach((token) => {
    const originalValue = token.original?.$value;
    const familyName = pathToPropertyName(token.path);
    const description = getTokenDescription(token);
 
    // Check if it's a reference to another font family token
    if (isTokenReference(originalValue)) {
      const refToken = findTokenByReference(originalValue, allTokens);
      Eif (
        refToken &&
        refToken.path[PATH_INDEX.SUBCATEGORY] &&
        refToken.path[PATH_INDEX.SUBCATEGORY].startsWith(FONT_SUBCATEGORY.FAMILY)
      ) {
        const refFamilyName = pathToPropertyName(refToken.path);
        output.push(formatReference(familyName, refFamilyName, objectName, description));
        return;
      }
    }
 
    // Otherwise process as a font stack string
    const rawValue = getRawValueUnitValue(token);
    const fontStack = processFontStack(rawValue);
    Eif (fontStack) {
      output.push(formatValue(familyName, fontStack, description));
    }
  });
 
  return output;
}
 
/**
 * Generate font weight output for Android/iOS
 * Reduces cognitive complexity by extracting font weight processing logic.
 *
 * @param {Array} fontWeights - Array of font weight tokens
 * @param {Function} pathToPropertyName - Function to convert path to property name
 * @param {Function} formatValue - Function to format a value (propName, value) => string
 * @returns {Array} - Array of output strings for each font weight
 */
export function generateFontWeightOutput(fontWeights, pathToPropertyName, formatValue) {
  const output = [];
 
  fontWeights.forEach((token) => {
    const rawValue = getRawValueUnitValue(token);
    const numValue = extractNumber(rawValue);
    const description = getTokenDescription(token);
 
    if (numValue !== null) {
      const weightName = pathToPropertyName(token.path);
      output.push(formatValue(weightName, Math.round(numValue), description));
    }
  });
 
  return output;
}
 
/**
 * Generate font dimension tokens (sizes and scales) output for Android/iOS
 * Reduces cognitive complexity by extracting shared dimension processing logic.
 * Handles both dimension and number types (e.g., font scales with ratio).
 *
 * @param {Array} tokenList - Array of font dimension tokens (sizes or scales)
 * @param {Array} allTokens - All tokens (for reference resolution)
 * @param {Object} config - Configuration object
 * @param {Function} config.pathToPropertyName - Function to convert token path to property name (path) => string
 * @param {Function} config.formatValue - Function to format a value (propName, value, token) => string
 * @param {Function} config.formatReference - Function to format a reference (propToken, refToken, allTokens) => string
 * @param {boolean} config.useDimensionConversion - Whether to use convertDimensionToNumeric (true) or extractNumber (false)
 * @param {string} config.expectedSubcategory - Expected subcategory for reference preservation (e.g., 'scale')
 * @returns {Array} - Array of output strings for each dimension token
 */
export function generateFontDimensionOutput(tokenList, allTokens, config) {
  const { pathToPropertyName, formatValue, formatReference, useDimensionConversion, expectedSubcategory } =
    config;
  const output = [];
 
  tokenList.forEach((token) => {
    const rawValue = getRawValueUnitValue(token);
    const originalValue = token.original?.$value;
    const tokenPath = token.path.join('.');
    const description = getTokenDescription(token);
 
    // Try dimension conversion first, then fall back to extractNumber for number types
    let numValue = null;
    if (useDimensionConversion) {
      numValue = convertDimensionToNumeric(rawValue, tokenPath);
      // If dimension conversion failed, try extractNumber (for number types like ratio)
      if (numValue === null) {
        numValue = extractNumber(rawValue);
      }
    } else E{
      numValue = extractNumber(rawValue);
    }
 
    Eif (numValue !== null) {
      const propName = pathToPropertyName(token.path);
 
      // Check if it's a reference to another token of the same type
      if (isTokenReference(originalValue)) {
        const refToken = findTokenByReference(originalValue, allTokens);
        Eif (refToken && refToken.path[PATH_INDEX.SUBCATEGORY] === expectedSubcategory) {
          output.push(formatReference(propName, refToken, allTokens, description));
          return;
        }
      }
 
      // Otherwise, resolve to numeric value
      output.push(formatValue(propName, numValue, token, description));
    }
  });
 
  return output;
}
 
/**
 * Generate line height output for Android/iOS
 * Reduces cognitive complexity by extracting line height processing logic.
 *
 * @param {Array} fontLineHeights - Array of line height tokens
 * @param {Array} allTokens - All tokens (for reference resolution)
 * @param {Object} config - Configuration object
 * @param {Function} config.pathToPropertyName - Function to convert token path to property name (path) => string
 * @param {Function} config.formatValue - Function to format a value (propName, value) => string
 * @param {Function} config.formatReference - Function to format a reference (propName, refPropName) => string
 * @returns {Array} - Array of output strings for each line height
 */
export function generateLineHeightOutput(fontLineHeights, allTokens, config) {
  const { pathToPropertyName, formatValue, formatReference } = config;
  const output = [];
 
  fontLineHeights.forEach((token) => {
    const rawValue = getRawValueUnitValue(token);
    const originalValue = token.original?.$value;
    const numValue = extractNumber(rawValue);
    const description = getTokenDescription(token);
 
    Eif (numValue !== null) {
      const propName = pathToPropertyName(token.path);
 
      // Check if it's a reference to another line height token
      if (isTokenReference(originalValue)) {
        const refToken = findTokenByReference(originalValue, allTokens);
        Eif (
          refToken &&
          refToken.path[PATH_INDEX.SUBCATEGORY] === FONT_SUBCATEGORY.LINE &&
          refToken.path[PATH_INDEX.MODIFIER] === FONT_MODIFIER.HEIGHT
        ) {
          const refPropName = pathToPropertyName(refToken.path);
          output.push(formatReference(propName, refPropName, description));
          return;
        }
      }
 
      // Otherwise, resolve to numeric value
      output.push(formatValue(propName, numValue, description));
    }
  });
 
  return output;
}
 
/**
 * Generate truncation (line clamp) output for Android/iOS
 * Reduces cognitive complexity by extracting truncation processing logic.
 *
 * @param {Array} fontTruncation - Array of truncation tokens
 * @param {Function} pathToPropertyName - Function to convert token path to property name (path) => string
 * @param {Function} formatValue - Function to format a value (propName, value) => string
 * @returns {Array} - Array of output strings for each truncation token
 */
export function generateTruncationOutput(fontTruncation, pathToPropertyName, formatValue) {
  const output = [];
 
  fontTruncation.forEach((token) => {
    const rawValue = getRawValueUnitValue(token);
    const numValue = extractNumber(rawValue);
    const description = getTokenDescription(token);
 
    Eif (numValue !== null) {
      const propName = pathToPropertyName(token.path);
      output.push(formatValue(propName, numValue, description));
    }
  });
 
  return output;
}
 
// ============================================================================
// HEX UTILITIES
// ============================================================================
 
/**
 * Expand a 3-digit hex color to 6-digit format
 * @param {string} hex - 3-digit hex (e.g., "F00" or "#F00")
 * @returns {string} - 6-digit hex without # (e.g., "FF0000")
 */
export function expandHexColor(hex) {
  let cleanHex = hex.replace('#', '').toUpperCase();
 
  if (cleanHex.length === 3) {
    cleanHex = cleanHex
      .split('')
      .map((char) => char + char)
      .join('');
  }
 
  return cleanHex;
}
 
// ============================================================================
// GENERIC TOKEN OUTPUT
// ============================================================================
 
/**
 * Generate generic output for unknown token types
 * Attempts to output a reasonable value based on the raw value structure
 *
 * @param {object} token - Token object
 * @param {Function} pathToNameFn - Function to convert path to constant name (pathToAndroidConstantName or pathToiOSConstantName)
 * @param {Function} formatNumber - Function to format number output (e.g., (name, value) => `const val ${name} = ${value}f\n`)
 * @param {Function} formatString - Function to format string output (e.g., (name, value) => `const val ${name} = "${value}"\n`)
 * @param {Function} formatArray - Function to format array output (e.g., (name, values) => `val ${name} = listOf(${values})\n`)
 * @param {string} platformPrefix - Platform prefix for warnings (e.g., "[Android]" or "[iOS]")
 * @returns {string} - Formatted output or empty string
 */
export function outputGenericToken(
  token,
  pathToNameFn,
  formatNumber,
  formatString,
  formatArray,
  platformPrefix,
) {
  const rawValue = getRawValueUnitValue(token);
  const name = pathToNameFn(token.path);
 
  // Handle simple numeric values
  if (typeof rawValue === 'number') {
    return formatNumber(name, rawValue);
  }
 
  // Handle simple string values (that aren't CSS-specific)
  if (typeof rawValue === 'string' && !rawValue.includes('(') && !rawValue.includes(' ')) {
    return formatString(name, rawValue);
  }
 
  // Handle arrays (e.g., cubicBezier [0.4, 0, 0.2, 1])
  if (Array.isArray(rawValue) && rawValue.every((v) => typeof v === 'number')) {
    return formatArray(name, rawValue);
  }
 
  // Complex values we can't handle generically - skip with warning
  console.warn(
    `${platformPrefix} Cannot output token "${token.path.join('.')}" with type "${token.$type}" - ` +
      `value too complex for generic output. Consider adding a handler to TYPE_OUTPUT_MAP.`,
  );
  return '';
}
 
/**
 * Output a single token based on its $type
 *
 * @param {object} token - Token to output
 * @param {Array} allTokens - All tokens (for color reference resolution)
 * @param {Object} TYPE_OUTPUT_MAP - Map of $type to output function
 * @param {Function} outputGenericTokenFn - Function to output generic tokens
 * @param {string} platformPrefix - Platform prefix for warnings (e.g., "[Android]" or "[iOS]")
 * @returns {string} - Platform-specific output
 */
export function outputTokenByType(token, allTokens, TYPE_OUTPUT_MAP, outputGenericTokenFn, platformPrefix) {
  if (shouldSkipToken(token)) {
    return '';
  }
 
  const outputFn = TYPE_OUTPUT_MAP[token.$type];
  if (outputFn) {
    return outputFn(token, allTokens);
  }
 
  // Unknown type - try generic fallback
  console.warn(
    `${platformPrefix} Unknown token type "${token.$type}" for ${token.path.join('.')} - using generic output`,
  );
  return outputGenericTokenFn(token);
}
 
// ============================================================================
// TYPE OUTPUT MAP FACTORY
// ============================================================================
 
/**
 * Supported token types for mobile output.
 */
export const SUPPORTED_TOKEN_TYPES = ['color', 'dimension', 'duration', 'number', 'fontWeight', 'fontFamily'];
 
/**
 * Create a TYPE_OUTPUT_MAP from platform-specific output functions.
 * Validates that all required types have handlers and no extra types are provided.
 *
 * @param {Object} outputFns - Object containing output functions for each type
 * @param {Function} outputFns.color - Color token output function
 * @param {Function} outputFns.dimension - Dimension token output function
 * @param {Function} outputFns.duration - Duration token output function
 * @param {Function} outputFns.number - Number token output function
 * @param {Function} outputFns.fontWeight - Font weight token output function
 * @param {Function} outputFns.fontFamily - Font family token output function
 * @returns {Object} - TYPE_OUTPUT_MAP object
 * @throws {Error} - If a required type is missing or an unknown type is provided
 */
export function createTypeOutputMap(outputFns) {
  // Validate all required types are provided
  for (const type of SUPPORTED_TOKEN_TYPES) {
    if (!outputFns[type]) {
      throw new Error(`[Mobile] createTypeOutputMap missing required handler for type: "${type}"`);
    }
  }
 
  // Validate no unknown types are provided
  for (const type of Object.keys(outputFns)) {
    if (!SUPPORTED_TOKEN_TYPES.includes(type)) {
      throw new Error(
        `[Mobile] createTypeOutputMap received unknown type: "${type}". Add it to SUPPORTED_TOKEN_TYPES if intentional.`,
      );
    }
  }
 
  return { ...outputFns };
}
 
// ============================================================================
// MAIN FORMATTER HELPERS
// ============================================================================
 
/**
 * Generate the category output section for a formatter
 * Processes all tokens in a category and formats them
 *
 * @param {Array} tokens - All tokens
 * @param {string} category - Category name
 * @param {Function} outputTokenByTypeFn - Function to output tokens (outputTokenByType)
 * @param {Function} formatCategoryHeader - Function to format category header (e.g., (category) => `// MARK: - ${category}\n\n`)
 * @returns {string} - Formatted category section
 */
export function generateCategorySection(tokens, category, outputTokenByTypeFn, formatCategoryHeader) {
  const categoryTokens = getTokensForCategory(tokens, category);
  const tokenOutput = categoryTokens.map((token) => outputTokenByTypeFn(token, tokens)).join('');
 
  return tokenOutput ? formatCategoryHeader(category) + tokenOutput + '\n' : '';
}
 
// ============================================================================
// SHARED DIMENSION OUTPUT GENERATOR
// ============================================================================
 
/**
 * Platform-specific configuration for dimension output generation
 * @typedef {Object} DimensionOutputConfig
 * @property {string} objectDeclaration - How to declare the object/class (e.g., 'object X {' or 'public class X {')
 * @property {string} objectClose - How to close the object/class (e.g., '}')
 * @property {Function} valueProperty - Function to generate value property: (propName, value, unit) => string
 * @property {Function} referenceProperty - Function to generate reference property: (propName, refPropName) => string
 * @property {Function} percentProperty - Function to generate percentage property: (propName, value) => string
 * @property {string} dpUnit - Unit suffix for dimension values (e.g., '.dp' or '')
 * @property {string} spUnit - Unit suffix for font scale values (e.g., '.sp' or '')
 */
 
/**
 * Generate dimension-based output (spacing, sizing, shapes) for any platform
 *
 * @param {Object} params
 * @param {Array} params.tokens - All tokens from dictionary
 * @param {string} params.category - Token category (CATEGORY.SPACING, CATEGORY.SIZING, etc.)
 * @param {string} params.fileHeader - File header string
 * @param {string} params.objectName - Name of the object/class
 * @param {DimensionOutputConfig} params.config - Platform-specific configuration
 * @param {Function} params.pathToPropertyName - Function to convert path to property name
 * @param {Function} [params.shouldPreserveRef] - Optional function to check if reference should be preserved: (token, refToken, category) => boolean
 * @returns {string} - Generated output
 */
export function generateDimensionOutput({
  tokens,
  category,
  fileHeader,
  objectName,
  config,
  pathToPropertyName,
  shouldPreserveRef = () => true, // Default: always preserve if refToken exists
}) {
  const categoryTokens = getTokensForCategory(tokens, category).filter((token) => !shouldSkipToken(token));
 
  if (categoryTokens.length === 0) {
    return '';
  }
 
  let output = fileHeader;
  output += `${config.objectDeclaration.replace('{{name}}', objectName)}\n`;
 
  categoryTokens.forEach((token) => {
    const propName = pathToPropertyName(token.path, category);
    const originalValue = token.original?.$value;
    const rawValue = getRawValueUnitValue(token);
    const description = getTokenDescription(token);
 
    // Check if it's a reference to another token
    if (isTokenReference(originalValue)) {
      const refToken = findTokenByReference(originalValue, tokens);
      Eif (refToken && shouldPreserveRef(token, refToken, category)) {
        const refPropName = pathToPropertyName(refToken.path, category);
        const unit = extractUnit(rawValue);
        output += config.referenceProperty(propName, refPropName, unit, description);
        return;
      }
    }
 
    // Resolve to numeric value
    const numericValue = convertDimensionToNumeric(rawValue, token.path.join('.'));
    Eif (numericValue !== null) {
      const unit = extractUnit(rawValue);
 
      // Handle percentage for circle radius
      if (unit === '%') {
        output += config.percentProperty(propName, numericValue, description);
      } else {
        output += config.valueProperty(propName, numericValue, description);
      }
    }
  });
 
  output += `${config.objectClose}\n`;
  return output;
}
 
/**
 * Generate duration output for any platform
 *
 * @param {Object} params
 * @param {Array} params.tokens - All tokens from dictionary
 * @param {string} params.fileHeader - File header string
 * @param {string} params.objectName - Name of the object/class
 * @param {Object} params.config - Platform-specific configuration
 * @param {Function} params.config.valueProperty - (propName, msValue) => string
 * @param {Function} params.config.referenceProperty - (propName, refPropName) => string
 * @param {string} params.config.objectDeclaration - Object/class declaration template
 * @param {string} params.config.objectClose - Object/class close
 * @param {Function} params.pathToPropertyName - Function to convert path to property name
 * @param {Function} params.convertDuration - Duration conversion function (ms or seconds)
 * @param {Function} [params.shouldPreserveRef] - Optional function to check if reference should be preserved
 * @returns {string} - Generated output
 */
export function generateDurationOutput({
  tokens,
  fileHeader,
  objectName,
  config,
  pathToPropertyName,
  convertDuration,
  shouldPreserveRef = () => true,
}) {
  const durationTokens = getTokensForCategory(tokens, CATEGORY.DURATION).filter(
    (token) => !shouldSkipToken(token),
  );
 
  if (durationTokens.length === 0) {
    return '';
  }
 
  // Sort duration tokens by their numeric value for better readability
  durationTokens.sort((a, b) => {
    const rawValueA = getRawValueUnitValue(a);
    const rawValueB = getRawValueUnitValue(b);
    const durationA = convertDuration(rawValueA, a.path.join('.')) || 0;
    const durationB = convertDuration(rawValueB, b.path.join('.')) || 0;
    return durationA - durationB;
  });
 
  let output = fileHeader;
  output += `${config.objectDeclaration.replace('{{name}}', objectName)}\n`;
 
  durationTokens.forEach((token) => {
    const propName = pathToPropertyName(token.path, CATEGORY.DURATION);
    const originalValue = token.original?.$value;
    const rawValue = getRawValueUnitValue(token);
    const description = getTokenDescription(token);
 
    // Check if it's a reference to another token
    if (isTokenReference(originalValue)) {
      const refToken = findTokenByReference(originalValue, tokens);
      Eif (refToken && shouldPreserveRef(token, refToken, CATEGORY.DURATION)) {
        const refPropName = pathToPropertyName(refToken.path, CATEGORY.DURATION);
        output += config.referenceProperty(propName, refPropName, description);
        return;
      }
    }
 
    // Resolve to duration value
    const durationValue = convertDuration(rawValue, token.path.join('.'));
    Eif (durationValue !== null) {
      output += config.valueProperty(propName, durationValue, description);
    }
  });
 
  output += `${config.objectClose}\n`;
  return output;
}
 
// Re-export getRawValueUnitValue for convenience
export { getRawValueUnitValue, valueUnitToString, isValueUnitObject };