(() => {
  'use strict';

  const ICONS = {
    dashboard: '<path d="M4 13h6V4H4zM14 20h6V11h-6zM4 20h6v-3H4zM14 7h6V4h-6z"/>',
    ai: '<path d="m12 2 1.7 5.3L19 9l-5.3 1.7L12 16l-1.7-5.3L5 9l5.3-1.7Z"/><path d="m19 15 .8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8Z"/>',
    load: '<rect x="4" y="5" width="16" height="14" rx="2"/><path d="M8 9h8M8 13h5"/>',
    dispatch: '<path d="M4 17h16M6 17l2-9h8l2 9M9 12h6"/>',
    driver: '<circle cx="12" cy="8" r="3"/><path d="M5 21a7 7 0 0 1 14 0"/>',
    people: '<circle cx="9" cy="8" r="3"/><path d="M3 20a6 6 0 0 1 12 0M16 5a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 5"/>',
    truck: '<path d="M3 6h11v11H3zM14 10h4l3 3v4h-7z"/><circle cx="7" cy="18" r="2"/><circle cx="18" cy="18" r="2"/>',
    trailer: '<rect x="3" y="6" width="15" height="10" rx="1"/><path d="M18 12h3M6 16v2M15 16v2"/><circle cx="6" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/>',
    fuel: '<path d="M6 3h8v18H6zM8 7h4"/><path d="M14 8h2l2 2v7a2 2 0 0 0 4 0v-6l-2-2"/>',
    hos: '<path d="M5 3h11a3 3 0 0 1 3 3v15H8a3 3 0 0 1-3-3Z"/><path d="M8 3v18M11 8h5M11 12h5"/>',
    border: '<path d="M5 3v18M19 3v18M5 7h14M5 17h14"/><path d="m9 12 2 2 4-4"/>',
    document: '<path d="M6 2h8l4 4v16H6z"/><path d="M14 2v5h5M9 12h6M9 16h6"/>',
    invoice: '<path d="M7 2h10v20l-2-1.5L13 22l-2-1.5L9 22l-2-1.5Z"/><path d="M10 7h4M10 11h4M10 15h4"/>',
    money: '<circle cx="12" cy="12" r="9"/><path d="M15 8.5c-.7-.6-1.7-1-3-1-1.7 0-3 .8-3 2s1 1.8 3 2.2 3 1 3 2.3-1.3 2.5-3.2 2.5c-1.2 0-2.3-.4-3.1-1.1M12 5.5v13"/>',
    accounting: '<path d="M4 19h16M6 16V9M10 16V5M14 16v-4M18 16V7"/>',
    report: '<path d="M5 20V10M12 20V4M19 20v-7"/>',
    calendar: '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 10h18"/>',
    map: '<path d="m3 6 6-3 6 3 6-3v15l-6 3-6-3-6 3Z"/><path d="M9 3v15M15 6v15"/>',
    maintenance: '<path d="M14.7 6.3a4 4 0 0 0-5-5L12 3.6 9.6 6 7.3 3.7a4 4 0 0 0 5 5L4 17l3 3 8.3-8.3a4 4 0 0 0 5-5L18 9l-2.4-2.4Z"/>',
    settings: '<circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1l2-1.5-2-3.4-2.4 1A7 7 0 0 0 15 6l-.3-2.6h-4L10.5 6A7 7 0 0 0 9 7.1l-2.4-1-2 3.4 2 1.5a7 7 0 0 0 0 2l-2 1.5 2 3.4 2.4-1a7 7 0 0 0 1.5 1.1l.2 2.6h4L15 18a7 7 0 0 0 1.5-1.1l2.4 1 2-3.4-2-1.5a7 7 0 0 0 .1-1Z"/>',
    bell: '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4"/>',
    task: '<path d="M9 11l2 2 4-5"/><rect x="4" y="3" width="16" height="18" rx="2"/>',
    search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
    shield: '<path d="M12 3 20 6v6c0 5-3.4 8-8 9-4.6-1-8-4-8-9V6z"/><path d="m9 12 2 2 4-4"/>',
    temperature: '<path d="M9 5a3 3 0 0 1 6 0v8.2a5 5 0 1 1-6 0Z"/><path d="M12 6v9"/>',
    file: '<path d="M7 3h7l4 4v14H7z"/><path d="M14 3v5h5"/>',
    bank: '<path d="m3 9 9-6 9 6M5 10h14M6 10v8M10 10v8M14 10v8M18 10v8M4 20h16"/>',
    vendor: '<path d="M4 10h16M6 10V7l6-4 6 4v3M5 10v10h14V10M9 14h6"/>',
    alert: '<path d="M12 3 2 21h20Z"/><path d="M12 9v5M12 18h.01"/>',
    user: '<circle cx="12" cy="8" r="3"/><path d="M5 21a7 7 0 0 1 14 0"/>',
    save: '<path d="M5 3h12l2 2v16H5z"/><path d="M8 3v6h8V3M8 21v-7h8v7"/>',
    plus: '<path d="M12 5v14M5 12h14"/>',
    upload: '<path d="M12 16V4M7 9l5-5 5 5"/><path d="M4 20h16"/>',
    edit: '<path d="m4 20 4.5-1 10-10-3.5-3.5-10 10Z"/><path d="m13.5 6.5 3.5 3.5"/>',
    check: '<path d="m5 12 4 4L19 6"/>',
    generic: '<rect x="4" y="4" width="16" height="16" rx="3"/><path d="M8 9h8M8 13h5"/>'
  };

  const svg = (name) => `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${ICONS[name] || ICONS.generic}</svg>`;

  function classify(text = '') {
    const value = text.toLowerCase();
    const rules = [
      [/fleetlume ai|gemini|autopilot|automation|assistant/, ['ai', 'violet']],
      [/fuel|gallon|allowance/, ['fuel', 'green']],
      [/hos|logbook|duty|driver log/, ['hos', 'indigo']],
      [/border|customs|crossing/, ['border', 'orange']],
      [/reefer|temperature|cold chain/, ['temperature', 'cyan']],
      [/invoice|receivable|payment receipt/, ['invoice', 'green']],
      [/account|ledger|journal|financial|profit|balance|cash flow/, ['accounting', 'green']],
      [/bank|reconcil/, ['bank', 'teal']],
      [/vendor|bill|payable/, ['vendor', 'amber']],
      [/settlement|money|expense|factoring|revenue|cost/, ['money', 'green']],
      [/maintenance|repair|service/, ['maintenance', 'orange']],
      [/trailer/, ['trailer', 'cyan']],
      [/truck|power unit|equipment|fleet/, ['truck', 'blue']],
      [/driver/, ['driver', 'indigo']],
      [/carrier|broker|customer|user|team|portal/, ['people', 'violet']],
      [/load|dispatch|shipment|stop/, ['load', 'blue']],
      [/calendar|schedule|appointment/, ['calendar', 'blue']],
      [/map|tracking|location|gps/, ['map', 'cyan']],
      [/document|file|pod|bol|upload/, ['document', 'indigo']],
      [/report|analytics|performance/, ['report', 'violet']],
      [/notification|alert|warning|attention/, ['bell', 'red']],
      [/setting|company|configuration|administration/, ['settings', 'blue']],
      [/task|workflow|activity|audit/, ['task', 'teal']],
      [/dashboard|overview|home/, ['dashboard', 'blue']]
    ];
    for (const [pattern, result] of rules) if (pattern.test(value)) return result;
    return ['generic', 'blue'];
  }

  function textFor(node) {
    return [
      node.querySelector('.eyebrow')?.textContent,
      node.querySelector('h1,h2,h3')?.textContent,
      node.textContent
    ].filter(Boolean).join(' ').trim();
  }

  function makeIcon(className, name, tone) {
    const icon = document.createElement('span');
    icon.className = `${className} tone-${tone}`;
    icon.innerHTML = svg(name);
    icon.setAttribute('aria-hidden', 'true');
    return icon;
  }

  function decoratePageHeadings() {
    document.querySelectorAll('.page-heading:not(.dashboard-welcome)').forEach((heading) => {
      const copy = heading.querySelector(':scope > div:first-child');
      if (!copy || copy.classList.contains('ui-heading-copy')) return;
      const [name, tone] = classify(textFor(copy));
      const text = document.createElement('div');
      text.className = 'ui-heading-text';
      while (copy.firstChild) text.appendChild(copy.firstChild);
      copy.classList.add('ui-heading-copy');
      copy.append(makeIcon('ui-heading-icon', name, tone), text);
      heading.classList.add(`tone-${tone}`);
    });
  }

  function decorateSection(container) {
    const copy = container.querySelector(':scope > div:first-child');
    if (!copy || copy.classList.contains('ui-section-copy')) return;
    if (copy.querySelector('.section-icon,.ui-section-icon,.metric-icon,.health-icon')) return;
    if (!copy.querySelector('h2,h3')) return;
    const [name, tone] = classify(textFor(copy));
    const text = document.createElement('div');
    text.className = 'ui-section-text';
    while (copy.firstChild) text.appendChild(copy.firstChild);
    copy.classList.add('ui-section-copy');
    copy.append(makeIcon('ui-section-icon', name, tone), text);
  }

  function decorateSections() {
    document.querySelectorAll('.panel-header:not(.dashboard-card-header),.form-section-head,.section-title-row').forEach(decorateSection);
  }

  function decorateStats() {
    document.querySelectorAll('.stat-card').forEach((card, index) => {
      if (card.querySelector('.ui-stat-icon,.metric-icon')) return;
      const [name, defaultTone] = classify(card.textContent || '');
      const tones = ['blue', 'violet', 'green', 'cyan', 'orange', 'teal', 'red', 'indigo'];
      const tone = defaultTone === 'blue' ? tones[index % tones.length] : defaultTone;
      card.classList.add(`tone-${tone}`);
      card.prepend(makeIcon('ui-stat-icon', name, tone));
    });
  }

  function buttonIcon(text) {
    const value = text.toLowerCase().trim();
    if (/save|update|apply/.test(value)) return 'save';
    if (/create|add|new|book/.test(value)) return 'plus';
    if (/upload|import/.test(value)) return 'upload';
    if (/edit|configure/.test(value)) return 'edit';
    if (/approve|complete|confirm|submit|generate|analyze|review|run|test/.test(value)) return 'check';
    return null;
  }

  function decorateButtons() {
    document.querySelectorAll('.btn-primary').forEach((button) => {
      if (button.querySelector('svg,.ui-button-icon')) return;
      const name = buttonIcon(button.textContent || '');
      if (!name) return;
      const icon = document.createElement('span');
      icon.className = 'ui-button-icon';
      icon.innerHTML = svg(name);
      button.prepend(icon);
    });
  }

  function improveFieldGroups() {
    document.querySelectorAll('.form-grid,.content-grid,.two-col,.three-col,.ai-grid').forEach((grid) => {
      Array.from(grid.children).forEach((child) => child.classList.add('ui-grid-child'));
    });
    document.querySelectorAll('textarea').forEach((textarea) => {
      if (!textarea.getAttribute('rows')) textarea.setAttribute('rows', '4');
    });
  }

  function markTables() {
    document.querySelectorAll('.table-wrap table').forEach((table) => {
      table.classList.add('ui-table-v5');
      const heads = Array.from(table.querySelectorAll('thead th')).map((th) => th.textContent.trim());
      table.querySelectorAll('tbody tr').forEach((row) => {
        Array.from(row.children).forEach((cell, index) => {
          if (!cell.dataset.label && heads[index]) cell.dataset.label = heads[index];
        });
      });
    });
  }

  function init() {
    decoratePageHeadings();
    decorateSections();
    decorateStats();
    decorateButtons();
    improveFieldGroups();
    markTables();
    document.body.classList.add('ui-v5-ready');
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, { once: true });
  else init();
})();
