@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,300;0,14..32,400;0,14..32,500;0,14..32,600;0,14..32,700&family=JetBrains+Mono:wght@400;500;600&display=swap');
    
    html, body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif !important; }
    * { font-family: inherit; }
    
    :root {
      --bg:       #08090b;
      --surface:  #0e1016;
      --surface2: #131520;
      --border:   #1c1f2e;
      --border2:  #252838;
      --text:     #f1f2f6;
      --text2:    #8b8fa8;
      --text3:    #565a75;
      --text4:    #363a52;
      --radius-sm: 6px;
      --radius:    10px;
      --radius-lg: 14px;
      --radius-xl: 18px;

      --mat-ultra-thin: rgba(255,255,255,0.04);
      --mat-thin:       rgba(255,255,255,0.06);
      --mat-regular:    rgba(255,255,255,0.10);
      --mat-thick:      rgba(255,255,255,0.16);
      --mat-elevated:   rgba(28,28,30,0.94);

      --blur-thin:    blur(20px) saturate(180%);
      --blur-regular: blur(30px) saturate(180%);
      --blur-thick:   blur(40px) saturate(180%);

      --label-1: rgba(255,255,255,0.96);
      --label-2: rgba(255,255,255,0.6);
      --label-3: rgba(255,255,255,0.38);
      --label-4: rgba(255,255,255,0.22);

      --separator:        rgba(255,255,255,0.08);
      --separator-strong: rgba(255,255,255,0.16);

      --tint-blue:   #0a84ff;
      --tint-green:  #30d158;
      --tint-orange: #ff9f0a;
      --tint-red:    #ff453a;
      --tint-purple: #bf5af2;

      --bg-blue:   rgba(10,132,255,0.16);
      --bg-green:  rgba(48,209,88,0.16);
      --bg-orange: rgba(255,159,10,0.16);
      --bg-red:    rgba(255,69,58,0.16);
      --bg-purple: rgba(191,90,242,0.16);

      --s-0: 0px;   --s-1: 4px;   --s-2: 8px;   --s-3: 12px;
      --s-4: 16px;  --s-5: 20px;  --s-6: 24px;  --s-8: 32px;
      --s-10: 40px; --s-12: 48px; --s-16: 64px;

      --r-1: 6px; --r-2: 10px; --r-3: 14px; --r-4: 20px; --r-full: 9999px;

      --shadow-1: 0 1px 3px rgba(0,0,0,0.2), inset 0 0.5px 0 rgba(255,255,255,0.04);
      --shadow-2: 0 4px 12px rgba(0,0,0,0.3);
      --shadow-3: 0 8px 24px rgba(0,0,0,0.35);
      --shadow-4: 0 16px 48px rgba(0,0,0,0.45);

      --z-base: 1; --z-sticky: 10; --z-dropdown: 100;
      --z-overlay: 1000; --z-modal: 1010; --z-toast: 2000;

      --ease:     cubic-bezier(0.32, 0.72, 0, 1);
      --dur-fast: 150ms;
      --dur-base: 250ms;
      --dur-slow: 400ms;

      --safe-top:    env(safe-area-inset-top, 0px);
      --safe-bottom: env(safe-area-inset-bottom, 0px);
      --safe-left:   env(safe-area-inset-left, 0px);
      --safe-right:  env(safe-area-inset-right, 0px);

      --font-display: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Inter", sans-serif;
      --font-text:    -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", sans-serif;
      --font-mono:    "SF Mono", "JetBrains Mono", Menlo, Monaco, Consolas, monospace;

      --t-caption-2-size: 11px; --t-caption-2-line: 1.3; --t-caption-2-weight: 500; --t-caption-2-track: 0.06px;
      --t-caption-size:   12px; --t-caption-line:   1.35; --t-caption-weight:   500; --t-caption-track:   0px;
      --t-footnote-size:  13px; --t-footnote-line:  1.4; --t-footnote-weight:  500; --t-footnote-track:  -0.08px;
      --t-body-size:      15px; --t-body-line:      1.45; --t-body-weight:      500; --t-body-track:      -0.24px;
      --t-callout-size:   16px; --t-callout-line:   1.4; --t-callout-weight:   500; --t-callout-track:   -0.32px;
      --t-headline-size:  17px; --t-headline-line:  1.3; --t-headline-weight:  600; --t-headline-track:  -0.4px;
      --t-title-3-size:   20px; --t-title-3-line:   1.25; --t-title-3-weight:   700; --t-title-3-track:   -0.45px;
      --t-title-2-size:   24px; --t-title-2-line:   1.2; --t-title-2-weight:   700; --t-title-2-track:   -0.55px;
      --t-title-1-size:   30px; --t-title-1-line:   1.15; --t-title-1-weight:   700; --t-title-1-track:   -0.6px;

      --sidebar-w: 240px;
      --topbar-h:  56px;

      --bg-primary:      var(--bg);        
      --bg-secondary:    var(--surface);   
      --bg-tertiary:     var(--surface2);  
      --surface-primary: var(--surface);
      --surface-secondary: var(--surface2);
      --surface-hover:   var(--surface2);
      --fill-quaternary: var(--mat-ultra-thin);
      --fill-tertiary:   var(--mat-thin);
      --fill-secondary:  var(--mat-regular);
      --fill-primary:    var(--mat-thick);

      --system-blue:   var(--tint-blue);
      --system-green:  var(--tint-green);
      --system-orange: var(--tint-orange);
      --system-red:    var(--tint-red);
      --system-purple: var(--tint-purple);
      --system-yellow: #ffd60a;
      --system-teal:   #5ac8fa;
      --system-indigo: #5e5ce6;
      --system-pink:   #ff375f;

      --success:        var(--tint-green);
      --success-bg:     var(--bg-green);
      --success-border: rgba(48,209,88,0.32);
      --danger:         var(--tint-red);
      --danger-bg:      var(--bg-red);
      --warning:        var(--tint-orange);
      --warning-bg:     var(--bg-orange);
      --info:           var(--tint-blue);
      --info-bg:        var(--bg-blue);
      
      --separator-green:  rgba(48,209,88,0.32);
      --separator-orange: rgba(255,159,10,0.32);
      --separator-red:    rgba(255,69,58,0.32);
      --separator-blue:   rgba(10,132,255,0.32);
      --separator-purple: rgba(191,90,242,0.32);
      --warn-border:    var(--separator-orange);
      --danger-border:  var(--separator-red);
      --info-border:    var(--separator-blue);
      
      --spec-hi:        rgba(255,255,255,0.10);
      --spec-hi-soft:   rgba(255,255,255,0.06);
      --spec-lo:        rgba(0,0,0,0.20);

      --r-card:    16px;
      --r-control: 12px;
      --r-field:   12px;
      --r-pill:    9999px;

      --control-h: 44px;

      --white: #ffffff;
      --black: #000000;
    }

    .t-caption-2 { font: var(--t-caption-2-weight) var(--t-caption-2-size)/var(--t-caption-2-line) var(--font-text); letter-spacing: var(--t-caption-2-track); }
    .t-caption   { font: var(--t-caption-weight)   var(--t-caption-size)/var(--t-caption-line)     var(--font-text); letter-spacing: var(--t-caption-track); }
    .t-footnote  { font: var(--t-footnote-weight)  var(--t-footnote-size)/var(--t-footnote-line)   var(--font-text); letter-spacing: var(--t-footnote-track); }
    .t-body      { font: var(--t-body-weight)      var(--t-body-size)/var(--t-body-line)           var(--font-text); letter-spacing: var(--t-body-track); }
    .t-headline  { font: var(--t-headline-weight)  var(--t-headline-size)/var(--t-headline-line)   var(--font-display); letter-spacing: var(--t-headline-track); }
    .t-title-3   { font: var(--t-title-3-weight)   var(--t-title-3-size)/var(--t-title-3-line)     var(--font-display); letter-spacing: var(--t-title-3-track); }
    .t-title-1   { font: var(--t-title-1-weight)   var(--t-title-1-size)/var(--t-title-1-line)     var(--font-display); letter-spacing: var(--t-title-1-track); }

    button, a, [role="button"], [tabindex] { -webkit-tap-highlight-color: transparent; }
    body.modal-open { overflow: hidden; touch-action: none; }
    html, body { overscroll-behavior-y: contain; }
    @keyframes spin { to { transform: rotate(360deg); } }

    details > summary { list-style: none; }
    details > summary::-webkit-details-marker { display: none; }
    details[open] > summary .chevron-marker { transform: rotate(90deg); }
    details > summary:hover { color: var(--label-1); }

    .hide-on-mobile  { }
    .hide-on-desktop { display: none; }
    .mobile-only-block  { display: none; }
    .desktop-only-block { display: block; }
    .mobile-only-flex   { display: none; }
    .desktop-only-flex  { display: flex; }

    .btn {
      display: inline-flex; align-items: center; justify-content: center;
      gap: var(--s-2);
      border: none; border-radius: var(--r-control);
      cursor: pointer; user-select: none;
      white-space: nowrap; text-decoration: none;
      font-family: var(--font-text);
      transition: background var(--dur-fast) var(--ease),
                  color var(--dur-fast) var(--ease),
                  border-color var(--dur-fast) var(--ease),
                  filter var(--dur-fast) var(--ease);
      -webkit-tap-highlight-color: transparent;
    }
    .btn:active:not(:disabled):not([data-loading="true"]) {
      transform: scale(0.97);
      transition: transform 50ms var(--ease);
    }
    .btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .btn[data-loading="true"] { pointer-events: none; }
    .btn[data-loading="true"] .spinner { animation: spin 1s linear infinite; }
    .btn:focus-visible { outline: 2px solid var(--tint-blue); outline-offset: 2px; }

    .btn-sm { height: 28px; padding: 0 12px; font-size: var(--t-footnote-size); line-height: 1; font-weight: 500; letter-spacing: var(--t-footnote-track); min-width: 28px; }
    .btn-md { height: 44px; padding: 0 20px; font-size: var(--t-body-size);     line-height: 1; font-weight: 600; letter-spacing: var(--t-body-track);     min-width: 44px; }
    .btn-lg { height: 50px; padding: 0 20px; font-size: var(--t-body-size);     line-height: 1; font-weight: 600; letter-spacing: var(--t-body-track);     min-width: 50px; }

    .btn-icon          { padding: 0; }
    .btn-icon.btn-sm   { width: 28px; }
    .btn-icon.btn-md   { width: 36px; }
    .btn-icon.btn-lg   { width: 50px; }

    .btn-filled                 { background: linear-gradient(180deg, rgba(255,255,255,0.14), rgba(255,255,255,0)), var(--tint-orange); color: #000; box-shadow: inset 0 0.5px 0 rgba(255,255,255,0.20); }
    .btn-filled:hover:not(:disabled)  { filter: brightness(1.08); }
    .btn-filled:active:not(:disabled) { filter: brightness(0.92); }
    .btn-filled:disabled        { background: var(--mat-thick); color: var(--label-3); box-shadow: none; }
    .btn-filled.btn-success     { background: linear-gradient(180deg, rgba(255,255,255,0.14), rgba(255,255,255,0)), var(--tint-green); color: var(--white); }
    .btn-filled.btn-info        { background: linear-gradient(180deg, rgba(255,255,255,0.14), rgba(255,255,255,0)), var(--tint-blue);  color: var(--white); }
    .btn-filled.btn-destructive { background: linear-gradient(180deg, rgba(255,255,255,0.14), rgba(255,255,255,0)), var(--tint-red);   color: var(--white); }
    .btn-filled.btn-destructive:focus-visible { outline-color: var(--tint-red); }
    .btn-filled.btn-success:focus-visible     { outline-color: var(--tint-green); }
    .btn-filled.btn-info:focus-visible        { outline-color: var(--tint-blue); }

    .btn-tinted                 { background: var(--bg-orange); color: var(--tint-orange); box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .btn-tinted:hover:not(:disabled)  { background: rgba(255,159,10,0.24); }
    .btn-tinted:active:not(:disabled) { background: rgba(255,159,10,0.32); }
    .btn-tinted:disabled        { background: rgba(255,159,10,0.08); color: var(--label-3); box-shadow: none; }
    .btn-tinted.btn-info        { background: var(--bg-blue); color: var(--tint-blue); }
    .btn-tinted.btn-info:hover:not(:disabled)        { background: rgba(10,132,255,0.24); }
    .btn-tinted.btn-info:active:not(:disabled)       { background: rgba(10,132,255,0.32); }
    .btn-tinted.btn-success     { background: var(--bg-green); color: var(--tint-green); }
    .btn-tinted.btn-success:hover:not(:disabled)     { background: rgba(48,209,88,0.24); }
    .btn-tinted.btn-success:active:not(:disabled)    { background: rgba(48,209,88,0.32); }
    .btn-tinted.btn-destructive { background: var(--bg-red); color: var(--tint-red); }
    .btn-tinted.btn-destructive:hover:not(:disabled) { background: rgba(255,69,58,0.24); }
    .btn-tinted.btn-destructive:active:not(:disabled){ background: rgba(255,69,58,0.32); }
    .btn-tinted.btn-purple      { background: var(--bg-purple); color: var(--tint-purple); }

    .btn-plain                  { background: transparent; color: var(--label-1); }
    .btn-plain:hover:not(:disabled)   { background: var(--mat-ultra-thin); }
    .btn-plain:active:not(:disabled)  { background: var(--mat-thin); }
    .btn-plain:disabled         { background: transparent; color: var(--label-4); }
    .btn-plain.btn-neutral      { color: var(--label-2); }
    .btn-plain.btn-neutral:hover:not(:disabled) { color: var(--label-1); background: var(--mat-ultra-thin); }
    .btn-plain.btn-info         { color: var(--tint-blue); }
    .btn-plain.btn-destructive  { color: var(--tint-red); }
    .btn-plain.btn-success      { color: var(--tint-green); }
    .btn-plain.btn-accent       { color: var(--tint-orange); } 

    .btn-outlined               { background: transparent; color: var(--label-1); border: 0.5px solid var(--separator-strong); box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .btn-outlined:hover:not(:disabled)  { background: var(--mat-ultra-thin); }
    .btn-outlined:active:not(:disabled) { background: var(--mat-thin); }
    .btn-outlined:disabled      { background: transparent; color: var(--label-4); border-color: var(--separator); box-shadow: none; }
    .btn-outlined.btn-destructive       { color: var(--tint-red); border-color: var(--danger-border); }
    .btn-outlined.btn-destructive:hover { background: var(--bg-red); border-color: rgba(255,69,58,0.5); }

    .btn-group {
      display: inline-flex;
      padding: 2px;
      background: var(--mat-regular);
      border-radius: var(--r-control);
    }
    .btn-group > .btn {
      height: 32px; min-width: 0; padding: 0 16px;
      background: transparent; color: var(--label-2);
      border-radius: 10px; border: none; font-weight: 500;
    }
    .btn-group > .btn[aria-pressed="true"],
    .btn-group > .btn.active {
      background: var(--mat-thick); color: var(--label-1);
    }
    .btn-group > .btn:hover:not([aria-pressed="true"]):not(.active) { color: var(--label-1); }

    .btn-block { width: 100%; }
    .btn-stretch { flex: 1; min-width: 0; }
    .btn[aria-expanded="true"] .chevron { transform: rotate(180deg); }
    .btn .chevron { transition: transform var(--dur-fast) var(--ease); }

    .input {
      display: block; width: 100%;
      background: var(--mat-thin);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-field);
      color: var(--label-1);
      font-family: var(--font-text); font-weight: 500;
      letter-spacing: var(--t-body-track);
      transition: border-color var(--dur-fast) var(--ease),
                  background var(--dur-fast) var(--ease),
                  box-shadow var(--dur-fast) var(--ease);
      -webkit-appearance: none; appearance: none; outline: none;
    }
    .input::placeholder { color: var(--label-3); font-weight: 400; }
    .input:hover:not(:disabled):not(:focus) { border-color: var(--separator-strong); }
    .input:focus {
      border: 1px solid var(--tint-blue);
      background: var(--mat-regular);
      box-shadow: 0 0 0 3px var(--bg-blue);
    }
    .input:disabled { opacity: 0.4; cursor: not-allowed; }
    .input[readonly] { background: transparent; border-color: var(--separator); }
    .input[aria-invalid="true"] {
      border: 1px solid var(--tint-red);
      box-shadow: 0 0 0 3px var(--bg-red);
    }

    .input-sm { height: 28px; padding: 0 12px; font-size: var(--t-footnote-size); line-height: 1; }
    .input-md { height: 44px; padding: 0 14px; font-size: var(--t-body-size);     line-height: 1; }
    .input-lg { height: 50px; padding: 0 16px; font-size: var(--t-body-size);     line-height: 1; }

    .input[type="number"]::-webkit-inner-spin-button,
    .input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
    .input[type="number"] { -moz-appearance: textfield; }
    .input[type="date"], .input[type="time"], .input[type="datetime-local"] { color-scheme: dark; }

    .input-wrap { position: relative; display: block; }
    .input-wrap > .input { padding-left: var(--s-10); padding-right: var(--s-3); }
    .input-wrap.input-trailing > .input { padding-right: var(--s-10); }
    .input-wrap.input-no-leading > .input { padding-left: var(--s-3); }
    .input-icon {
      position: absolute; top: 50%; transform: translateY(-50%);
      pointer-events: none; color: var(--label-3);
    }
    .input-icon.leading  { left:  12px; }
    .input-icon.trailing { right: 12px; pointer-events: auto; }
    .input:focus ~ .input-icon.leading { color: var(--tint-blue); }

    .textarea {
      width: 100%;
      background: var(--mat-thin);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-field);
      color: var(--label-1);
      font: var(--t-body-weight) var(--t-body-size)/1.5 var(--font-text);
      letter-spacing: var(--t-body-track);
      padding: 12px; min-height: 80px;
      resize: vertical;
      transition: inherit;
      -webkit-appearance: none; outline: none;
    }
    .textarea::placeholder { color: var(--label-3); font-weight: 400; }
    .textarea:focus { border: 1px solid var(--tint-blue); background: var(--mat-regular); box-shadow: 0 0 0 3px var(--bg-blue); }
    .textarea[aria-invalid="true"] { border: 1px solid var(--tint-red); box-shadow: 0 0 0 3px var(--bg-red); }
    .textarea:disabled { opacity: 0.4; cursor: not-allowed; }

    .select-trigger {
      display: flex; align-items: center; justify-content: space-between;
      width: 100%;
      background: var(--mat-thin);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-field);
      color: var(--label-1);
      font-family: var(--font-text); font-weight: 500;
      letter-spacing: var(--t-body-track);
      cursor: pointer; transition: inherit; outline: none;
    }
    .select-trigger.placeholder { color: var(--label-3); }
    .select-trigger:hover:not(:disabled):not([aria-expanded="true"]) { border-color: var(--separator-strong); }
    .select-trigger[aria-expanded="true"],
    .select-trigger:focus-visible {
      border: 1px solid var(--tint-blue);
      background: var(--mat-regular);
      box-shadow: 0 0 0 3px var(--bg-blue);
    }
    .select-trigger .chevron { transition: transform var(--dur-fast) var(--ease); color: var(--label-2); flex-shrink: 0; }
    .select-trigger[aria-expanded="true"] .chevron { transform: rotate(180deg); }
    .select-trigger-sm { height: 28px; padding: 0 12px; font-size: var(--t-footnote-size); }
    .select-trigger-md { height: 44px; padding: 0 14px; font-size: var(--t-body-size); }
    .select-trigger-lg { height: 50px; padding: 0 16px; font-size: var(--t-body-size); }

    .select-menu {
      position: absolute;
      z-index: var(--z-dropdown);
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick); -webkit-backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-3);
      box-shadow: var(--shadow-2);
      padding: var(--s-1);
      max-height: 280px; overflow-y: auto;
      min-width: 100%;
      animation: dropdown-in var(--dur-fast) var(--ease);
    }
    @keyframes dropdown-in {
      from { opacity: 0; transform: translateY(-4px); }
      to   { opacity: 1; transform: translateY(0); }
    }
    .select-option {
      display: flex; align-items: center; justify-content: space-between;
      gap: var(--s-2);
      height: 36px; padding: 0 12px;
      border-radius: var(--r-1);
      color: var(--label-1);
      font: var(--t-body-weight) var(--t-body-size)/1 var(--font-text);
      cursor: pointer;
      transition: background var(--dur-fast) var(--ease);
    }
    .select-option:hover, .select-option[aria-current="true"] { background: var(--mat-regular); }
    .select-option .check-icon { color: var(--tint-blue); }

    .checkbox-row { display: inline-flex; align-items: center; gap: var(--s-2); cursor: pointer; }
    .checkbox {
      position: relative; width: 20px; height: 20px;
      border-radius: var(--r-1);
      border: 1px solid var(--separator-strong);
      background: transparent;
      display: inline-flex; align-items: center; justify-content: center;
      flex-shrink: 0;
      transition: all var(--dur-fast) var(--ease);
    }
    .checkbox > input { position: absolute; opacity: 0; pointer-events: none; }
    .checkbox.checked, .checkbox.indeterminate { background: var(--tint-blue); border-color: var(--tint-blue); }
    .checkbox-row:hover .checkbox:not(.checked):not(.indeterminate) { border-color: var(--label-2); }
    .checkbox-row:focus-within .checkbox { box-shadow: 0 0 0 3px var(--bg-blue); }
    .checkbox-row.disabled { opacity: 0.4; cursor: not-allowed; }
    .checkbox-label { color: var(--label-1); font: var(--t-body-weight) var(--t-body-size)/1.4 var(--font-text); }
    .checkbox-sm { width: 16px; height: 16px; }

    .radio-row { display: inline-flex; align-items: center; gap: var(--s-2); cursor: pointer; }
    .radio {
      position: relative; width: 20px; height: 20px;
      border-radius: var(--r-full);
      border: 1px solid var(--separator-strong);
      background: transparent;
      display: inline-flex; align-items: center; justify-content: center;
      flex-shrink: 0;
      transition: all var(--dur-fast) var(--ease);
    }
    .radio > input { position: absolute; opacity: 0; pointer-events: none; }
    .radio.checked { border-color: var(--tint-blue); }
    .radio-dot { width: 10px; height: 10px; border-radius: var(--r-full); background: var(--tint-blue); }

    .switch-row { display: inline-flex; align-items: center; gap: var(--s-3); cursor: pointer; }
    .switch {
      position: relative;
      width: 50px; height: 30px;
      border-radius: var(--r-full);
      background: var(--mat-thick);
      border: none; padding: 0;
      cursor: pointer;
      transition: background var(--dur-fast) var(--ease);
      flex-shrink: 0;
    }
    .switch-knob {
      position: absolute; top: 2px; left: 2px;
      width: 26px; height: 26px;
      border-radius: var(--r-full);
      background: #fff;
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
      transition: transform var(--dur-fast) var(--ease);
    }
    .switch.switch-on { background: var(--tint-green); }
    .switch.switch-on .switch-knob { transform: translateX(20px); }
    .switch:focus-visible { box-shadow: 0 0 0 3px var(--bg-green); }
    .switch:disabled, .switch-row.disabled .switch { opacity: 0.4; cursor: not-allowed; }

    .field { display: flex; flex-direction: column; gap: var(--s-1); }
    .field-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: var(--s-2); }
    .field-label {
      font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text);
      letter-spacing: var(--t-footnote-track);
      color: var(--label-2);
    }
    .field-marker {
      font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text);
      color: var(--label-3);
    }
    .field-helper {
      font: var(--t-caption-weight) var(--t-caption-size)/var(--t-caption-line) var(--font-text);
      color: var(--label-3);
      margin-top: var(--s-1);
    }
    .field-error {
      font: var(--t-caption-weight) var(--t-caption-size)/var(--t-caption-line) var(--font-text);
      color: var(--tint-red);
      margin-top: var(--s-1);
      display: flex; align-items: center; gap: var(--s-1);
    }
    .field-success {
      font: var(--t-caption-weight) var(--t-caption-size)/var(--t-caption-line) var(--font-text);
      color: var(--tint-green);
      margin-top: var(--s-1);
      display: flex; align-items: center; gap: var(--s-1);
    }

    .form      { display: flex; flex-direction: column; gap: var(--s-4); }
    .form-2col { display: grid; grid-template-columns: 1fr 1fr; gap: var(--s-4); }
    .form-2col .col-span-2 { grid-column: span 2; }
    .field-with-action { display: flex; gap: var(--s-2); align-items: stretch; }
    .field-with-action > .input, .field-with-action > .input-wrap { flex: 1; }

    .settings-list { display: flex; flex-direction: column; }
    .settings-list .field {
      display: grid; grid-template-columns: 200px 1fr;
      gap: var(--s-4); align-items: center;
      padding: var(--s-3) 0;
      border-bottom: 0.5px solid var(--separator);
    }
    .settings-list .field:last-child { border-bottom: none; }

    .dropzone {
      border: 1.5px dashed var(--separator-strong);
      background: var(--mat-ultra-thin);
      border-radius: var(--r-3);
      padding: var(--s-6);
      display: flex; flex-direction: column; align-items: center;
      gap: var(--s-2);
      cursor: pointer;
      transition: all var(--dur-fast) var(--ease);
      text-align: center;
    }
    .dropzone:hover { background: var(--mat-thin); }
    .dropzone.drag-over { border-color: var(--tint-blue); border-style: solid; background: var(--bg-blue); }
    .dropzone-title { font: var(--t-body-weight) var(--t-body-size)/1.4 var(--font-text); color: var(--label-1); }
    .dropzone-hint  { font: var(--t-footnote-weight) var(--t-footnote-size)/1.4 var(--font-text); color: var(--label-2); }
    .dropzone-meta  { font: var(--t-caption-weight) var(--t-caption-size)/1.4 var(--font-text); color: var(--label-3); margin-top: var(--s-2); }

    .modal-overlay {
      position: fixed; inset: 0;
      z-index: var(--z-overlay);
      background: rgba(0, 0, 0, 0.5);
      backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
      display: flex; align-items: center; justify-content: center;
      padding: var(--s-4);
      animation: backdrop-in var(--dur-base) var(--ease);
    }
    .modal-overlay[data-closing="true"] { animation: backdrop-out var(--dur-base) var(--ease) forwards; }
    
    .modal-overlay[data-size="alert"] { z-index: 100000; }
    @keyframes backdrop-in  { from { opacity: 0; } to { opacity: 1; } }
    @keyframes backdrop-out { from { opacity: 1; } to { opacity: 0; } }

    .modal-card {
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick); -webkit-backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-4);
      box-shadow: var(--shadow-4);
      display: flex; flex-direction: column;
      max-height: 90dvh; width: 100%;
      z-index: var(--z-modal);
      overflow: hidden;
      animation: modal-in var(--dur-base) var(--ease);
      position: relative;
    }
    .modal-overlay[data-closing="true"] .modal-card { animation: modal-out var(--dur-base) var(--ease) forwards; }
    @keyframes modal-in  { from { opacity: 0; transform: scale(0.96) translateY(-8px); } to { opacity: 1; transform: scale(1) translateY(0); } }
    @keyframes modal-out { from { opacity: 1; transform: scale(1) translateY(0); }     to { opacity: 0; transform: scale(0.96) translateY(-8px); } }

    .modal-overlay[data-size="alert"] .modal-card { max-width: 320px; }
    .modal-overlay[data-size="sm"]    .modal-card { max-width: 420px; }
    .modal-overlay[data-size="md"]    .modal-card { max-width: 560px; }
    .modal-overlay[data-size="lg"]    .modal-card { max-width: 820px; }

    .modal-header {
      padding: var(--s-5) var(--s-6) var(--s-4);
      display: flex; align-items: flex-start; justify-content: space-between;
      gap: var(--s-3);
      border-bottom: 0.5px solid var(--separator);
      flex-shrink: 0;
    }
    .modal-header-content { flex: 1; min-width: 0; }
    .modal-title {
      font: var(--t-title-3-weight) var(--t-title-3-size)/var(--t-title-3-line) var(--font-display);
      letter-spacing: var(--t-title-3-track);
      color: var(--label-1);
      margin: 0;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    .modal-description {
      font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text);
      letter-spacing: var(--t-footnote-track);
      color: var(--label-2);
      margin: var(--s-1) 0 0 0;
    }
    .modal-body {
      padding: var(--s-5) var(--s-6);
      overflow-y: auto;
      flex: 1; min-height: 0;
    }
    .modal-body::-webkit-scrollbar       { width: 8px; }
    .modal-body::-webkit-scrollbar-thumb { background: var(--separator-strong); border-radius: var(--r-full); }
    .modal-body::-webkit-scrollbar-thumb:hover { background: var(--mat-thick); }
    .modal-body > * + * { margin-top: var(--s-4); }

    .modal-footer {
      padding: var(--s-4) var(--s-6);
      display: flex; gap: var(--s-2);
      justify-content: flex-end; align-items: center;
      border-top: 0.5px solid var(--separator);
      flex-shrink: 0;
    }
    .modal-footer-spread { justify-content: space-between; }

    .modal-overlay[data-size="alert"] .modal-card { animation: alert-in var(--dur-base) var(--ease); }
    @keyframes alert-in { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } }
    .modal-alert-body {
      padding: var(--s-6);
      display: flex; flex-direction: column; align-items: center;
      text-align: center; gap: var(--s-2);
    }
    .modal-alert-title {
      font: var(--t-headline-weight) var(--t-headline-size)/var(--t-headline-line) var(--font-display);
      color: var(--label-1); margin: 0;
    }
    .modal-alert-description {
      font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text);
      color: var(--label-2); margin: 0;
    }
    .modal-alert-actions {
      margin-top: var(--s-3);
      display: flex; flex-direction: column; gap: var(--s-2);
      width: 100%;
    }

    .modal-split { display: flex; height: 100%; }
    .modal-split-side { width: 240px; flex-shrink: 0; border-right: 0.5px solid var(--separator); overflow-y: auto; }
    .modal-split-main { flex: 1; min-width: 0; overflow: hidden; display: flex; flex-direction: column; }

    .modal-card:has(.modal-table-host) .modal-body { padding: 0; display: flex; flex-direction: column; min-height: 0; }
    .modal-table-host { display: flex; flex-direction: column; min-height: 0; flex: 1; }
    .modal-toolbar {
      padding: var(--s-3) var(--s-6);
      display: flex; gap: var(--s-2); align-items: center;
      border-bottom: 0.5px solid var(--separator);
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      position: sticky; top: 0; z-index: 1;
    }

    .modal-progress { height: 2px; background: var(--mat-thin); overflow: hidden; }
    .modal-progress-fill { height: 100%; background: var(--tint-orange); transition: width var(--dur-base) var(--ease); }

    .stat-card-new {
      background: var(--mat-regular);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-3);
      padding: var(--s-5);
      transition: border-color var(--dur-fast) var(--ease),
                  transform var(--dur-fast) var(--ease),
                  box-shadow var(--dur-fast) var(--ease);
    }
    .stat-card-clickable { cursor: pointer; }
    .stat-card-clickable:hover {
      border-color: var(--separator-strong);
      transform: translateY(-2px);
      box-shadow: var(--shadow-2);
    }
    .stat-card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--s-5); }
    .stat-card-icon {
      width: 36px; height: 36px;
      border-radius: var(--r-2);
      display: flex; align-items: center; justify-content: center;
    }
    .stat-card-icon-blue   { background: var(--bg-blue);   color: var(--tint-blue); }
    .stat-card-icon-green  { background: var(--bg-green);  color: var(--tint-green); }
    .stat-card-icon-orange { background: var(--bg-orange); color: var(--tint-orange); }
    .stat-card-icon-red    { background: var(--bg-red);    color: var(--tint-red); }
    .stat-card-icon-purple { background: var(--bg-purple); color: var(--tint-purple); }
    .stat-card-value {
      font: var(--t-title-1-weight) var(--t-title-1-size)/var(--t-title-1-line) var(--font-display);
      letter-spacing: var(--t-title-1-track);
      color: var(--label-1);
    }
    .stat-card-label {
      font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text);
      color: var(--label-2);
      margin-top: var(--s-1);
      display: flex; align-items: center; gap: var(--s-2);
    }
    .stat-card-trend { display: inline-flex; align-items: center; gap: 2px; font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text); }
    .stat-card-trend.up   { color: var(--tint-green); }
    .stat-card-trend.down { color: var(--tint-red); }

    .card {
      background: var(--mat-regular);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-card);
      padding: var(--s-5);
    }
    .card-header {
      display: flex; align-items: center; justify-content: space-between;
      gap: var(--s-3); margin-bottom: var(--s-4);
    }
    .card-title {
      font: var(--t-headline-weight) var(--t-headline-size)/var(--t-headline-line) var(--font-display);
      letter-spacing: var(--t-headline-track);
      color: var(--label-1); margin: 0;
    }
    .card-description {
      font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text);
      color: var(--label-2); margin: var(--s-1) 0 0;
    }

    .action-card {
      display: grid; grid-template-columns: auto 1fr auto;
      gap: var(--s-3); align-items: center;
      background: var(--mat-regular);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-3);
      padding: var(--s-4) var(--s-5);
      cursor: pointer;
      transition: all var(--dur-fast) var(--ease);
      text-align: left;
    }
    .action-card:hover { border-color: var(--separator-strong); background: var(--mat-thick); }
    .action-card:active { transform: scale(0.99); }
    .action-card-content { display: flex; flex-direction: column; min-width: 0; }
    .action-card-title { font: var(--t-body-weight) var(--t-body-size)/1.2 var(--font-text); color: var(--label-1); }
    .action-card-desc  { font: var(--t-caption-weight) var(--t-caption-size)/1.3 var(--font-text); color: var(--label-2); margin-top: 2px; }
    .action-card-chevron { color: var(--label-3); }

    .badge {
      display: inline-flex; align-items: center;
      gap: var(--s-1);
      height: 22px; padding: 0 var(--s-2);
      border-radius: var(--r-full);
      font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text);
      letter-spacing: var(--t-caption-track);
      white-space: nowrap; flex-shrink: 0;
    }
    .badge-lg { height: 28px; padding: 0 var(--s-3); font-size: var(--t-footnote-size); }
    .badge-success  { background: var(--bg-green);  color: var(--tint-green);  border: 0.5px solid var(--success-border); }
    .badge-info     { background: var(--bg-blue);   color: var(--tint-blue);   border: 0.5px solid var(--info-border); }
    .badge-warning  { background: var(--bg-orange); color: var(--tint-orange); border: 0.5px solid var(--warn-border); }
    .badge-danger   { background: var(--bg-red);    color: var(--tint-red);    border: 0.5px solid var(--danger-border); }
    .badge-neutral  { background: var(--mat-thick); color: var(--label-2);     border: 0.5px solid var(--separator); }
    .badge-accent   { background: var(--bg-purple); color: var(--tint-purple); border: 0.5px solid var(--separator-purple); }
    .badge-dot { width: 6px; height: 6px; border-radius: var(--r-full); background: currentColor; flex-shrink: 0; }
    .badge-live { background: var(--bg-green); color: var(--tint-green); border-radius: var(--r-full); }
    .badge-live .badge-dot { animation: pulse 2s var(--ease) infinite; }
    @keyframes pulse { 50% { opacity: 0.4; } }

    .list-row {
      display: flex; align-items: center; gap: var(--s-3);
      min-height: 56px;
      padding: var(--s-3) var(--s-4);
      border-bottom: 0.5px solid var(--separator);
      transition: background var(--dur-fast) var(--ease);
    }
    .list-row:last-child { border-bottom: none; }
    .list-row:hover { background: var(--mat-ultra-thin); }
    .list-row[data-selected="true"] { background: var(--bg-blue); }
    .list-row[data-drag-over="true"] { background: var(--bg-blue); box-shadow: inset 0 2px 0 var(--tint-blue); }
    .list-row[data-dragging="true"] { opacity: 0.5; cursor: grabbing; }

    .list-row-content { flex: 1; min-width: 0; display: flex; flex-direction: column; }
    .list-row-title { font: var(--t-body-weight) var(--t-body-size)/1.2 var(--font-text); color: var(--label-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .list-row-meta  { font: var(--t-footnote-weight) var(--t-footnote-size)/1.2 var(--font-text); color: var(--label-2); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .list-row-trailing { color: var(--label-2); font: var(--t-footnote-weight) var(--t-footnote-size)/1 var(--font-text); flex-shrink: 0; }
    .list-row-actions {
      opacity: 0;
      display: flex; gap: var(--s-1);
      transition: opacity var(--dur-fast) var(--ease);
      flex-shrink: 0;
    }
    .list-row:hover .list-row-actions,
    .list-row:focus-within .list-row-actions { opacity: 1; }

    .drag-handle {
      width: 24px; height: 24px;
      display: flex; align-items: center; justify-content: center;
      color: var(--label-3); cursor: grab;
      background: transparent; border: none;
      border-radius: var(--r-1);
      transition: color var(--dur-fast) var(--ease);
    }
    .drag-handle:hover { color: var(--label-2); background: var(--mat-ultra-thin); }
    .drag-handle:active { cursor: grabbing; }

    .table-shell {
      background: var(--mat-regular);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-3);
      overflow: hidden;
      display: flex; flex-direction: column;
      position: relative;
    }
    .table-wrap { overflow-x: auto; overflow-y: auto; }
    .table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      font: var(--t-body-weight) var(--t-body-size)/1.4 var(--font-text);
      letter-spacing: var(--t-body-track);
    }

    .table thead th {
      position: sticky; top: 0;
      z-index: 2;
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      color: var(--label-2);
      font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text);
      letter-spacing: var(--t-caption-track);
      text-align: left;
      padding: var(--s-3) var(--s-4);
      border-bottom: 0.5px solid var(--separator);
      white-space: nowrap; user-select: none;
    }
    .table thead th[data-sortable] { cursor: pointer; }
    .table thead th[data-sortable]:hover { color: var(--label-1); }
    .table thead th .sort-icon { display: inline-flex; vertical-align: middle; margin-left: 4px; opacity: 0; transition: opacity var(--dur-fast) var(--ease); }
    .table thead th:hover .sort-icon { opacity: 0.5; }
    .table thead th[aria-sort="ascending"] .sort-icon,
    .table thead th[aria-sort="descending"] .sort-icon { opacity: 1; color: var(--tint-blue); }
    .table thead th[data-align="right"], .table tbody td[data-align="right"] { text-align: right; }
    .table thead th[data-align="center"], .table tbody td[data-align="center"] { text-align: center; }

    .table tbody td {
      padding: var(--s-3) var(--s-4);
      color: var(--label-1);
      border-bottom: 0.5px solid var(--separator);
      vertical-align: middle;
    }
    .table tbody tr:last-child td { border-bottom: none; }
    .table tbody tr { transition: background var(--dur-fast) var(--ease); }
    .table tbody tr:hover { background: var(--mat-ultra-thin); }
    .table tbody tr[aria-selected="true"] { background: var(--bg-blue); }
    .table tbody tr[data-clickable="true"] { cursor: pointer; }
    .table tbody tr[data-dimmed="true"] td { opacity: 0.4; }
    .table tbody tr[data-disabled="true"] td { opacity: 0.4; pointer-events: none; }

    .table td[data-type="mono"], .table th[data-type="mono"] { font-family: var(--font-mono); font-size: 12px; color: var(--label-2); }
    .table td[data-type="number"] { text-align: right; font-variant-numeric: tabular-nums; }
    .table td[data-type="actions"] { text-align: right; white-space: nowrap; width: 1%; }
    .table td[data-type="checkbox"], .table th[data-type="checkbox"] { width: 1%; padding-right: 0; }

    .table td[data-type="actions"] .row-actions {
      display: inline-flex; gap: var(--s-1);
      opacity: 0;
      transition: opacity var(--dur-fast) var(--ease);
    }
    .table tbody tr:hover .row-actions,
    .table tbody tr:focus-within .row-actions { opacity: 1; }

    .table tbody tr[data-status="success"] td:first-child { box-shadow: inset 2px 0 0 var(--tint-green); }
    .table tbody tr[data-status="error"]   td:first-child { box-shadow: inset 2px 0 0 var(--tint-red); }
    .table tbody tr[data-status="warning"] td:first-child { box-shadow: inset 2px 0 0 var(--tint-orange); }

    .cell-avatar { display: flex; align-items: center; gap: var(--s-3); min-width: 0; }
    .cell-avatar-content { display: flex; flex-direction: column; min-width: 0; }
    .cell-avatar-name { font: var(--t-body-weight) var(--t-body-size)/1.2 var(--font-text); color: var(--label-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .cell-avatar-meta { font: var(--t-caption-weight) var(--t-caption-size)/1.2 var(--font-text); color: var(--label-2); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

    .avatar { flex-shrink: 0; border-radius: var(--r-full); object-fit: cover; background: var(--mat-regular); }
    .avatar-fallback {
      display: inline-flex; align-items: center; justify-content: center;
      font: 600 var(--t-footnote-size) / 1 var(--font-display);
      color: #fff; text-transform: uppercase; letter-spacing: 0.2px;
    }
    .avatar-blue   { background: var(--tint-blue); }
    .avatar-green  { background: var(--tint-green); }
    .avatar-orange { background: var(--tint-orange); }
    .avatar-red    { background: var(--tint-red); }
    .avatar-purple { background: var(--tint-purple); }

    .table-toolbar {
      display: flex; align-items: center; gap: var(--s-2);
      padding: var(--s-3) var(--s-4);
      border-bottom: 0.5px solid var(--separator);
      background: var(--mat-thin);
    }
    .table-toolbar-search { flex: 1; max-width: 320px; }
    .table-toolbar-spacer { flex: 1; }
    .table-toolbar-actions { display: flex; gap: var(--s-2); align-items: center; }

    .table-bulk-bar {
      display: flex; align-items: center; gap: var(--s-3);
      padding: var(--s-3) var(--s-4);
      background: var(--bg-blue);
      border-bottom: 0.5px solid var(--separator);
      color: var(--tint-blue);
      font: var(--t-footnote-weight) var(--t-footnote-size)/1 var(--font-text);
      transform: translateY(-100%);
      transition: transform var(--dur-base) var(--ease);
      position: absolute; top: 0; left: 0; right: 0;
      z-index: 3;
    }
    .table-bulk-bar[data-active="true"] { transform: translateY(0); position: relative; }
    .table-bulk-count { font-weight: 600; color: var(--tint-blue); }
    .table-bulk-actions { display: flex; gap: var(--s-2); margin-left: auto; }

    .table-pagination {
      display: flex; align-items: center; justify-content: space-between;
      gap: var(--s-3);
      padding: var(--s-3) var(--s-4);
      border-top: 0.5px solid var(--separator);
      background: var(--mat-thin);
      font: var(--t-footnote-weight) var(--t-footnote-size)/1 var(--font-text);
      color: var(--label-2);
      flex-wrap: wrap;
    }
    .table-pagination-info { white-space: nowrap; }
    .table-pagination-controls { display: flex; gap: var(--s-2); align-items: center; margin-left: auto; }
    .table-pagination-page { color: var(--label-1); padding: 0 var(--s-2); }

    .table-empty { padding: var(--s-12) var(--s-4) !important; text-align: center !important; color: var(--label-3); }
    .table-empty-icon { margin: 0 auto var(--s-3); width: 48px; height: 48px; opacity: 0.4; }
    .table-empty-title { display: block; font: var(--t-headline-weight) var(--t-headline-size)/1 var(--font-display); color: var(--label-2); margin-bottom: var(--s-1); }
    .table-empty-hint { display: block; font: var(--t-footnote-weight) var(--t-footnote-size)/1.4 var(--font-text); color: var(--label-3); margin-bottom: var(--s-4); }

    .table-group-header td {
      position: sticky; top: 36px; z-index: 1;
      background: var(--mat-thick);
      backdrop-filter: var(--blur-thin);
      font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text);
      color: var(--label-2);
      padding: var(--s-2) var(--s-4) !important;
      display: flex; gap: var(--s-2); align-items: center;
    }

    .skeleton {
      display: inline-block;
      background: linear-gradient(90deg, var(--mat-thin) 0%, var(--mat-thick) 50%, var(--mat-thin) 100%);
      background-size: 200% 100%;
      animation: skeleton-pulse 1.5s var(--ease) infinite;
      border-radius: var(--r-1);
      height: 14px; width: 100%;
    }
    @keyframes skeleton-pulse {
      0%   { background-position: 200% 0; }
      100% { background-position: -200% 0; }
    }
    .skeleton-text   { height: 14px; width: 100%; }
    .skeleton-title  { height: 22px; width: 60%; }
    .skeleton-line   { height: 12px; width: 100%; }
    .skeleton-avatar { width: 36px; height: 36px; border-radius: var(--r-full); }
    .skeleton-button { height: 36px; width: 96px; border-radius: var(--r-2); }
    .skeleton-card   { height: 120px; width: 100%; border-radius: var(--r-3); }

    .card-list { display: flex; flex-direction: column; gap: var(--s-2); }
    .card-list-row {
      background: var(--mat-regular);
      border: 0.5px solid var(--separator);
      border-radius: var(--r-3);
      padding: var(--s-4);
      display: flex; flex-direction: column; gap: var(--s-2);
      transition: background var(--dur-fast) var(--ease);
    }
    .card-list-row:active { background: var(--mat-thick); }
    .card-list-primary { font: var(--t-headline-weight) var(--t-headline-size)/1.2 var(--font-display); color: var(--label-1); }
    .card-list-meta { display: flex; justify-content: space-between; gap: var(--s-3); }
    .card-list-meta-label { color: var(--label-2); font: var(--t-footnote-weight) var(--t-footnote-size)/1.2 var(--font-text); }
    .card-list-meta-value { color: var(--label-1); font: var(--t-footnote-weight) var(--t-footnote-size)/1.2 var(--font-text); text-align: right; }

    .sidebar-logo { height: 60px; padding: 0 var(--s-4); display: flex; align-items: center; gap: var(--s-3); }
    .sidebar-logo-icon { width: 32px; height: 32px; border-radius: var(--r-2); background: linear-gradient(180deg, rgba(255,255,255,0.16), rgba(255,255,255,0)), var(--tint-orange); display: flex; align-items: center; justify-content: center; color: var(--black); flex-shrink: 0; box-shadow: inset 0 0.5px 0 rgba(255,255,255,0.25), 0 4px 12px rgba(255,159,10,0.18); }
    .sidebar-logo-text { display: flex; flex-direction: column; min-width: 0; }
    .sidebar-logo-title { font: var(--t-headline-weight) var(--t-headline-size)/1 var(--font-display); color: var(--label-1); }
    .sidebar-logo-subtitle { font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text); color: var(--label-3); margin-top: 2px; }

    .sidebar-section { padding: var(--s-2) 0; }
    .sidebar-section-label {
      font: var(--t-caption-2-weight) var(--t-caption-2-size)/1 var(--font-text);
      letter-spacing: var(--t-caption-2-track);
      color: var(--label-3);
      padding: var(--s-3) var(--s-4) var(--s-1);
      display: block;
    }

    .sidebar-nav-item {
      display: flex; align-items: center; gap: var(--s-3);
      height: 36px;
      padding: 0 var(--s-4);
      margin: 0 var(--s-2);
      border-radius: var(--r-2);
      color: var(--label-2);
      text-decoration: none;
      cursor: pointer;
      background: transparent; border: none; width: calc(100% - var(--s-4)); text-align: left;
      transition: background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease), transform 60ms var(--ease);
    }
    .sidebar-nav-item:hover { background: var(--mat-ultra-thin); color: var(--label-1); }
    .sidebar-nav-item:active { transform: scale(0.99); }
    .sidebar-nav-item[data-active="true"] {
      background: var(--mat-thick); color: var(--label-1);
      box-shadow: inset 0 0.5px 0 var(--spec-hi-soft);
    }
    .sidebar-nav-item[data-active="true"] svg { color: var(--tint-orange); }
    .sidebar-nav-label {
      font: var(--t-body-weight) var(--t-body-size)/1 var(--font-text);
      letter-spacing: var(--t-body-track);
      flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .sidebar-nav-item .badge { margin-left: auto; }

    .sidebar-profile {
      padding: var(--s-3) var(--s-4);
      border-top: 0.5px solid var(--separator);
      display: flex; align-items: center; gap: var(--s-3);
      background: transparent; border-left: none; border-right: none; border-bottom: none;
      width: 100%; cursor: pointer;
      transition: background var(--dur-fast) var(--ease);
    }
    .sidebar-profile:hover { background: var(--mat-ultra-thin); }
    .sidebar-profile-text { flex: 1; display: flex; flex-direction: column; min-width: 0; text-align: left; }
    .sidebar-profile-name { font: var(--t-body-weight) var(--t-body-size)/1 var(--font-text); color: var(--label-1); }
    .sidebar-profile-role { font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-text); color: var(--label-2); margin-top: 2px; }

    .sidebar-backdrop { display: none; }

    .app-topbar-new {
      height: 56px;
      padding: 0 var(--s-5);
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      border-bottom: 0.5px solid var(--separator);
      display: flex; align-items: center; gap: var(--s-3);
      position: sticky; top: 0; z-index: var(--z-sticky);
    }
    .topbar-spacer { flex: 1; }
    .topbar-search { max-width: 320px; }
    .topbar-action-dot { width: 8px; height: 8px; border-radius: var(--r-full); background: var(--tint-red); position: absolute; top: 8px; right: 8px; }

    .tabs {
      position: relative;
      display: flex; gap: 0;
      border-bottom: 0.5px solid var(--separator);
      overflow-x: auto;
      scrollbar-width: none;
    }
    .tabs::-webkit-scrollbar { display: none; }
    .tabs-tab {
      flex-shrink: 0;
      display: inline-flex; align-items: center; gap: var(--s-2);
      height: 44px;
      padding: 0 var(--s-4);
      background: transparent; border: none;
      cursor: pointer; color: var(--label-2);
      font: var(--t-body-weight) var(--t-body-size)/1 var(--font-text);
      letter-spacing: var(--t-body-track);
      transition: color var(--dur-fast) var(--ease);
    }
    .tabs-tab:hover { color: var(--label-1); }
    .tabs-tab[data-active="true"] { color: var(--label-1); font-weight: 600; }
    .tabs-indicator {
      position: absolute; bottom: -0.5px;
      height: 2px;
      background: var(--tint-orange);
      border-radius: var(--r-full) var(--r-full) 0 0;
      transition: left var(--dur-base) var(--ease), width var(--dur-base) var(--ease);
    }

    .breadcrumb {
      display: flex; align-items: center; flex-wrap: wrap;
      font: var(--t-footnote-weight) var(--t-footnote-size)/1.4 var(--font-text);
      letter-spacing: var(--t-footnote-track);
    }
    .breadcrumb-item { color: var(--label-2); text-decoration: none; transition: color var(--dur-fast) var(--ease); }
    .breadcrumb-item:hover { color: var(--label-1); }
    .breadcrumb-current { color: var(--label-1); cursor: default; }
    .breadcrumb-sep { color: var(--label-3); margin: 0 var(--s-2); user-select: none; }

    .section-header { padding: var(--s-6) 0 var(--s-4); }
    .section-header-breadcrumb { margin-bottom: var(--s-2); }
    .section-header-row { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--s-4); flex-wrap: wrap; }
    .section-header-title { font: var(--t-title-1-weight) var(--t-title-1-size)/var(--t-title-1-line) var(--font-display); letter-spacing: var(--t-title-1-track); color: var(--label-1); margin: 0; }
    .section-header-description { font: var(--t-body-weight) var(--t-body-size)/1.4 var(--font-text); color: var(--label-2); margin: var(--s-2) 0 0; }
    .section-header-actions { display: flex; gap: var(--s-2); align-items: center; flex-shrink: 0; }

    .dropdown-menu-host { position: relative; display: inline-flex; }
    .dropdown-menu {
      position: absolute; z-index: var(--z-dropdown);
      min-width: 200px;
      background:
        linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0) 38%),
        var(--mat-elevated);
      backdrop-filter: var(--blur-thick); -webkit-backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-3);
      box-shadow: var(--shadow-3), inset 0 0.5px 0 var(--spec-hi);
      padding: var(--s-1);
      animation: dropdown-in var(--dur-fast) var(--ease);
    }
    .dropdown-menu-bottom-end   { top: calc(100% + 4px); right: 0; }
    .dropdown-menu-bottom-start { top: calc(100% + 4px); left: 0; }
    .dropdown-menu-top-end      { bottom: calc(100% + 4px); right: 0; }
    .dropdown-menu-top-start    { bottom: calc(100% + 4px); left: 0; }
    .dropdown-menu-item {
      display: flex; align-items: center; gap: var(--s-3);
      width: 100%; height: 32px;
      padding: 0 var(--s-3);
      border-radius: var(--r-1);
      background: transparent; border: none;
      cursor: pointer; color: var(--label-1);
      text-align: left;
      font: var(--t-body-weight) var(--t-body-size)/1 var(--font-text);
      transition: background var(--dur-fast) var(--ease);
    }
    .dropdown-menu-item:hover:not(:disabled) { background: var(--mat-regular); }
    .dropdown-menu-item:disabled { opacity: 0.4; cursor: not-allowed; }
    .dropdown-menu-item.destructive { color: var(--tint-red); }
    .dropdown-menu-shortcut { margin-left: auto; font: var(--t-caption-weight) var(--t-caption-size)/1 var(--font-mono); color: var(--label-3); }
    .dropdown-menu-divider { border: none; border-top: 0.5px solid var(--separator); margin: var(--s-1) 0; }

    .notifs-dropdown-new {
      position: absolute;
      top: calc(100% + 8px); right: 0;
      width: 360px; max-height: 480px;
      background:
        linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0) 38%),
        var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-3);
      box-shadow: var(--shadow-3), inset 0 0.5px 0 var(--spec-hi);
      z-index: var(--z-dropdown);
      display: flex; flex-direction: column;
      overflow: hidden;
      animation: dropdown-in var(--dur-fast) var(--ease);
    }
    .notifs-dropdown-header { display: flex; align-items: center; justify-content: space-between; padding: var(--s-3) var(--s-4); border-bottom: 0.5px solid var(--separator); }
    .notifs-dropdown-title { font: var(--t-headline-weight) var(--t-headline-size)/1 var(--font-display); color: var(--label-1); }
    .notifs-dropdown-list { flex: 1; overflow-y: auto; padding: var(--s-1) 0; }
    .notifs-dropdown-item {
      display: flex; gap: var(--s-3);
      padding: var(--s-3) var(--s-4);
      cursor: pointer; border: none; background: transparent;
      text-align: left; width: 100%;
      transition: background var(--dur-fast) var(--ease);
    }
    .notifs-dropdown-item:hover { background: var(--mat-ultra-thin); }
    .notifs-dropdown-item-title { font: var(--t-body-weight) var(--t-body-size)/1.3 var(--font-text); color: var(--label-1); display: block; }
    .notifs-dropdown-item-meta { font: var(--t-caption-weight) var(--t-caption-size)/1.3 var(--font-text); color: var(--label-2); display: block; margin-top: 2px; }

    .page-pagination { display: flex; align-items: center; gap: var(--s-1); font: var(--t-footnote-weight) var(--t-footnote-size)/1 var(--font-text); }
    .page-pagination-num {
      min-width: 32px; height: 32px; padding: 0 var(--s-2);
      background: transparent;
      border: 0.5px solid transparent;
      border-radius: var(--r-2);
      color: var(--label-2);
      cursor: pointer;
      transition: all var(--dur-fast) var(--ease);
    }
    .page-pagination-num:hover { background: var(--mat-ultra-thin); color: var(--label-1); }
    .page-pagination-num.active { background: var(--mat-thick); color: var(--label-1); font-weight: 600; border-color: var(--separator-strong); }
    .page-pagination-gap { color: var(--label-3); padding: 0 var(--s-1); }

    .toast-container {
      position: fixed;
      top: max(20px, calc(var(--safe-top) + 16px));
      left: 50%; transform: translateX(-50%);
      z-index: var(--z-toast);
      display: flex; flex-direction: column; gap: var(--s-2);
      pointer-events: none;
      width: max-content;
      max-width: calc(100vw - 32px);
    }
    .toast-container > * { pointer-events: auto; }

    .toast {
      position: relative;
      display: flex; align-items: flex-start; gap: var(--s-3);
      min-width: 320px; max-width: 480px;
      padding: var(--s-3) var(--s-4);
      background:
        linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0) 38%),
        var(--mat-elevated);
      backdrop-filter: var(--blur-thick); -webkit-backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-3);
      box-shadow: var(--shadow-3), inset 0 0.5px 0 var(--spec-hi);
      overflow: hidden;
      animation: toast-in var(--dur-base) var(--ease);
    }
    .toast[data-closing="true"] { animation: toast-out var(--dur-base) var(--ease) forwards; }
    @keyframes toast-in  { from { opacity: 0; transform: translateY(-12px) scale(0.96); } to { opacity: 1; transform: translateY(0) scale(1); } }
    @keyframes toast-out { from { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 0; transform: translateY(-12px) scale(0.96); } }

    .toast-icon {
      flex-shrink: 0; width: 28px; height: 28px;
      border-radius: var(--r-2);
      display: flex; align-items: center; justify-content: center;
    }
    .toast-success .toast-icon { background: var(--bg-green);  color: var(--tint-green); }
    .toast-error   .toast-icon { background: var(--bg-red);    color: var(--tint-red); }
    .toast-warning .toast-icon { background: var(--bg-orange); color: var(--tint-orange); }
    .toast-info    .toast-icon { background: var(--bg-blue);   color: var(--tint-blue); }

    .toast-content { flex: 1; min-width: 0; padding-top: 4px; }
    .toast-title { font: var(--t-body-weight) var(--t-body-size)/1.3 var(--font-text); color: var(--label-1); margin: 0; }
    .toast-subtitle { font: var(--t-footnote-weight) var(--t-footnote-size)/1.4 var(--font-text); color: var(--label-2); margin: var(--s-1) 0 0; }
    .toast-action { margin-top: var(--s-2); }
    .toast-close { flex-shrink: 0; margin-top: 2px; }

    .toast-progress {
      position: absolute; bottom: 0; left: 0;
      height: 2px;
      background: currentColor;
      opacity: 0.5;
      transition: width linear;
    }
    .toast-success .toast-progress { color: var(--tint-green); }
    .toast-error   .toast-progress { color: var(--tint-red); }
    .toast-warning .toast-progress { color: var(--tint-orange); }
    .toast-info    .toast-progress { color: var(--tint-blue); }

    .banner {
      display: flex; align-items: flex-start; gap: var(--s-3);
      padding: var(--s-4);
      border-radius: var(--r-3);
      border: 0.5px solid;
    }
    .banner-icon { flex-shrink: 0; width: 20px; height: 20px; margin-top: 2px; }
    .banner-content { flex: 1; min-width: 0; }
    .banner-title { font: 600 var(--t-body-size)/1.3 var(--font-text); color: var(--label-1); margin: 0; }
    .banner-subtitle { font: var(--t-footnote-weight) var(--t-footnote-size)/1.4 var(--font-text); color: var(--label-2); margin: var(--s-1) 0 0; }
    .banner-actions { flex-shrink: 0; display: flex; gap: var(--s-2); align-items: center; }
    .banner-info    { background: linear-gradient(135deg, var(--bg-blue),   rgba(255,255,255,0)), var(--mat-regular); border-color: var(--info-border);    box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .banner-info    .banner-icon { color: var(--tint-blue); }
    .banner-warning { background: linear-gradient(135deg, var(--bg-orange), rgba(255,255,255,0)), var(--mat-regular); border-color: var(--warn-border);    box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .banner-warning .banner-icon { color: var(--tint-orange); }
    .banner-error   { background: linear-gradient(135deg, var(--bg-red),    rgba(255,255,255,0)), var(--mat-regular); border-color: var(--danger-border);  box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .banner-error   .banner-icon { color: var(--tint-red); }
    .banner-success { background: linear-gradient(135deg, var(--bg-green),  rgba(255,255,255,0)), var(--mat-regular); border-color: var(--success-border); box-shadow: inset 0 0.5px 0 var(--spec-hi-soft); }
    .banner-success .banner-icon { color: var(--tint-green); }

    .empty-state {
      display: flex; flex-direction: column; align-items: center;
      text-align: center;
      padding: var(--s-12) var(--s-4);
      gap: var(--s-2);
    }
    .empty-state-icon { width: 48px; height: 48px; color: var(--label-3); opacity: 0.6; margin-bottom: var(--s-2); }
    .empty-state-title { font: var(--t-headline-weight) var(--t-headline-size)/1.2 var(--font-display); color: var(--label-1); margin: 0; }
    .empty-state-hint { font: var(--t-footnote-weight) var(--t-footnote-size)/var(--t-footnote-line) var(--font-text); color: var(--label-2); margin: 0; max-width: 320px; }
    .empty-state-action { margin-top: var(--s-4); }
    .empty-state-compact { padding: var(--s-8) var(--s-4); }
    .empty-state-compact .empty-state-icon { width: 32px; height: 32px; }
    .empty-state-in-card { padding: var(--s-6) var(--s-4); }
    .empty-state-in-card .empty-state-icon { width: 28px; height: 28px; }

    .progress {
      position: relative;
      height: 4px;
      background: var(--mat-thin);
      border-radius: var(--r-full);
      overflow: hidden;
    }
    .progress-bar {
      height: 100%;
      background: var(--tint-blue);
      border-radius: inherit;
      transition: width var(--dur-base) var(--ease);
    }
    .progress-success .progress-bar { background: var(--tint-green); }
    .progress-warning .progress-bar { background: var(--tint-orange); }
    .progress-error   .progress-bar { background: var(--tint-red); }
    .progress-indeterminate .progress-bar {
      width: 30%;
      animation: progress-indeterminate 1.4s var(--ease) infinite;
    }
    @keyframes progress-indeterminate {
      0%   { transform: translateX(-100%); }
      100% { transform: translateX(400%); }
    }

    .tooltip-host { position: relative; display: inline-flex; }
    .tooltip {
      position: absolute; z-index: var(--z-dropdown);
      padding: var(--s-2) var(--s-3);
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      border-radius: var(--r-2);
      color: var(--label-1);
      font: var(--t-caption-weight) var(--t-caption-size)/1.3 var(--font-text);
      letter-spacing: var(--t-caption-track);
      white-space: nowrap;
      max-width: 240px;
      pointer-events: none;
      box-shadow: var(--shadow-2);
      animation: tooltip-in 100ms var(--ease);
    }
    @keyframes tooltip-in { from { opacity: 0; transform: translate(-50%, 4px); } to { opacity: 1; transform: translate(-50%, 0); } }
    .tooltip-top    { bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%); }
    .tooltip-bottom { top: calc(100% + 6px); left: 50%; transform: translateX(-50%); }
    .tooltip-left   { right: calc(100% + 6px); top: 50%; transform: translateY(-50%); }
    .tooltip-right  { left: calc(100% + 6px); top: 50%; transform: translateY(-50%); }

    .pull-to-refresh {
      position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
      z-index: var(--z-sticky);
      width: 40px; height: 40px;
      border-radius: var(--r-full);
      background: var(--mat-elevated);
      backdrop-filter: var(--blur-thick);
      border: 0.5px solid var(--separator-strong);
      display: flex; align-items: center; justify-content: center;
      color: var(--label-1);
      transition: opacity var(--dur-fast) var(--ease);
    }

    @media (max-width: 1280px) { :root { --sidebar-w: 220px; } }
    @media (max-width: 1024px) { :root { --sidebar-w: 200px; } }

    @media (max-width: 768px) {
      
      .modal-overlay { padding: 0; align-items: flex-end; }
      .modal-card {
        max-width: 100% !important;
        width: 100%;
        border-radius: var(--r-4) var(--r-4) 0 0;
        max-height: 92dvh;
        animation: sheet-in var(--dur-slow) var(--ease);
      }
      .modal-overlay[data-closing="true"] .modal-card { animation: sheet-out var(--dur-base) var(--ease) forwards; }
      .modal-overlay[data-size="lg"] .modal-card { max-height: 100dvh; border-radius: 0; }
      .modal-overlay[data-size="alert"] { align-items: center; padding: var(--s-4); }
      .modal-overlay[data-size="alert"] .modal-card { border-radius: var(--r-4); animation: alert-in var(--dur-base) var(--ease); }
      .modal-footer > .btn { flex: 1; min-width: 0; }
      .modal-footer { padding-bottom: max(var(--s-4), calc(var(--safe-bottom) + var(--s-3))); }
      .modal-header { padding-top:    max(var(--s-5), calc(var(--safe-top)    + var(--s-3))); }
      .modal-card::before {
        content: "";
        position: absolute;
        top: var(--s-2); left: 50%; transform: translateX(-50%);
        width: 36px; height: 4px;
        background: var(--separator-strong);
        border-radius: var(--r-full);
        pointer-events: none;
      }
      .modal-overlay[data-size="alert"] .modal-card::before,
      .modal-overlay[data-size="lg"]    .modal-card::before { display: none; }

      .toast { min-width: 0; width: calc(100vw - 32px); }

      .form-2col { grid-template-columns: 1fr; }
      .form-2col .col-span-2 { grid-column: span 1; }

      .settings-list .field { grid-template-columns: 1fr; gap: var(--s-1); }

      .section-header-row { flex-direction: column; }
      .section-header-actions { width: 100%; }

      .sidebar-backdrop {
        display: block;
        position: fixed; inset: 0;
        background: rgba(0,0,0,0.5);
        backdrop-filter: blur(4px);
        z-index: calc(var(--z-modal) - 1);
        animation: backdrop-in var(--dur-fast) var(--ease);
      }

      .modal-split { flex-direction: column; }
      .modal-split-side { width: 100%; max-height: 200px; border-right: none; border-bottom: 0.5px solid var(--separator); }

      .btn-sm.btn-icon { position: relative; }
      .btn-sm.btn-icon::after { content: ""; position: absolute; inset: -8px; }
      .row-actions .btn-sm, .list-row-actions .btn-sm { position: relative; }
      .row-actions .btn-sm::after, .list-row-actions .btn-sm::after { content: ""; position: absolute; inset: -8px; }

      .hide-on-mobile { display: none !important; }
      .desktop-only-flex  { display: none; }
      .mobile-only-flex   { display: flex; }
      .desktop-only-block { display: none; }
      .mobile-only-block  { display: block; }

      .stat-card-new { padding: var(--s-4); }
    }

    @keyframes sheet-in  { from { transform: translateY(100%); } to { transform: translateY(0); } }
    @keyframes sheet-out { from { transform: translateY(0); } to { transform: translateY(100%); } }

    @media (max-height: 500px) and (orientation: landscape) {
      .modal-card { max-height: 95dvh; }
      .empty-state { padding: var(--s-6) var(--s-4); }
      .empty-state-icon { width: 36px; height: 36px; }
    }

    @media (hover: none) {
      .table td[data-type="actions"] .row-actions,
      .list-row-actions { opacity: 1; }
    }

    html, body, #root { margin: 0; padding: 0; width: 100%; height: 100%; background: var(--bg); overscroll-behavior-y: none; }
    body { -webkit-text-size-adjust: 100%; font-feature-settings: "ss01","cv11","kern"; }
    * { box-sizing: border-box; }
    ::selection { background: rgba(232,138,45,0.22); color: #fff; }
    
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 3px; }
    ::-webkit-scrollbar-thumb:hover { background: #363a52; }
    
    input[type="date"] { color-scheme: dark; }
    input[type="date"]::-webkit-calendar-picker-indicator { filter: invert(0.6); cursor: pointer; }
    input:focus, select:focus, textarea:focus { border-color: var(--tint-blue) !important; outline: none; box-shadow: 0 0 0 3px var(--bg-blue), inset 0 0.5px 0 var(--spec-hi-soft); transition: border-color var(--dur-fast) var(--ease), box-shadow var(--dur-fast) var(--ease); }
    select { -webkit-appearance: none; -moz-appearance: none; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23565a75' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 14px center; padding-right: 36px !important; cursor: pointer; }
    button { cursor: pointer; transition: all .15s cubic-bezier(.4,0,.2,1); font-family: inherit; }
    button:active { transform: scale(0.97); transition: transform .05s; }
    
    @keyframes fadeIn      { from { opacity:0 } to { opacity:1 } }
    @keyframes clickRing   { 0% { transform:scale(0.3); opacity:1; border-width:3px } 80% { opacity:0.6 } 100% { transform:scale(3.2); opacity:0; border-width:1px } }
    @keyframes clickRipple { 0% { transform:scale(0.5); opacity:0.7; border-width:2px } 100% { transform:scale(4.5); opacity:0; border-width:0.5px } }
    @keyframes clickFlash  { 0% { transform:scale(0.2); opacity:0.95 } 60% { opacity:0.4 } 100% { transform:scale(1.6); opacity:0 } }
    @keyframes slideUp     { from { opacity:0; transform:translateY(14px) } to { opacity:1; transform:translateY(0) } }
    @keyframes toastIn     { from { opacity:0; transform:translateX(-50%) translateY(-10px) } to { opacity:1; transform:translateX(-50%) translateY(0) } }
    @keyframes pulse       { 0%,100% { opacity:1 } 50% { opacity:.35 } }
    @keyframes toastProgress { from { width:100% } to { width:0% } }
    @keyframes shimmer     { 0% { background-position:-200px 0 } 100% { background-position:200px 0 } }
    @keyframes fadeInUp    { from { opacity:0; transform:translateY(10px) } to { opacity:1; transform:translateY(0) } }
    @keyframes fadeInScale { from { opacity:0; transform:scale(0.96) } to { opacity:1; transform:scale(1) } }
    @keyframes overlayIn   { from { opacity:0; backdrop-filter:blur(0) } to { opacity:1; backdrop-filter:blur(28px) saturate(140%) } }
    @keyframes slideInLeft { from { opacity:0; transform:translateX(-10px) } to { opacity:1; transform:translateX(0) } }
    
    .ios-stagger > * { opacity:0; animation: fadeInUp .4s var(--ease) forwards; }
    .ios-stagger > *:nth-child(1){ animation-delay:.02s }
    .ios-stagger > *:nth-child(2){ animation-delay:.06s }
    .ios-stagger > *:nth-child(3){ animation-delay:.10s }
    .ios-stagger > *:nth-child(4){ animation-delay:.14s }
    .ios-stagger > *:nth-child(5){ animation-delay:.18s }
    .ios-stagger > *:nth-child(6){ animation-delay:.22s }
    .ios-stagger > *:nth-child(n+7){ animation-delay:.26s }
    @media (prefers-reduced-motion: reduce){ .ios-stagger > *{ animation:none; opacity:1 } }
    .ios-press{ transition: transform 60ms var(--ease); }
    .ios-press:active:not(:disabled){ transform: scale(0.98); }
    
    .ios-press[data-tone="neutral"]:hover:not(:disabled) { background: var(--mat-regular); }
    .ios-press[data-tone="danger"]:hover:not(:disabled)  { background: var(--bg-red); color: var(--tint-red); }
    .ios-press[data-tone="warn"]:hover:not(:disabled)    { background: var(--bg-orange); color: var(--tint-orange); }
    .ios-press[data-tone="success"]:hover:not(:disabled) { background: var(--bg-green); color: var(--tint-green); }
    .ios-press[data-tone="info"]:hover:not(:disabled)    { background: var(--bg-blue); color: var(--tint-blue); }
    .ios-glass:hover{ border-color: var(--separator-strong) !important; }
    
    .ios-card-stagger > *{ opacity:0; animation: fadeInUp .35s var(--ease) forwards; }
    .ios-card-stagger > *:nth-child(1){ animation-delay:0s }
    .ios-card-stagger > *:nth-child(2){ animation-delay:.05s }
    .ios-card-stagger > *:nth-child(3){ animation-delay:.10s }
    .ios-card-stagger > *:nth-child(4){ animation-delay:.15s }
    .ios-card-stagger > *:nth-child(5){ animation-delay:.20s }
    .ios-card-stagger > *:nth-child(n+6){ animation-delay:.25s }
    @media (prefers-reduced-motion: reduce){ .ios-card-stagger > *{ animation:none; opacity:1 } }
    
    .ios-thead-sticky thead th{
      position: sticky; top: 0; z-index: 1;
      background: var(--mat-thick);
      backdrop-filter: var(--blur-thin); -webkit-backdrop-filter: var(--blur-thin);
      box-shadow: inset 0 -0.5px 0 var(--separator);
    }
    
    .ios-overlay{
      position: fixed; inset: 0; z-index: var(--z-modal);
      background: rgba(0,0,0,0.55);
      backdrop-filter: blur(28px) saturate(140%); -webkit-backdrop-filter: blur(28px) saturate(140%);
      display: flex; align-items: center; justify-content: center; padding: var(--s-6);
      animation: overlayIn var(--dur-base) var(--ease);
    }
    .ios-overlay--mobile-sheet{ align-items: flex-end; padding: 0; }
    
    .ios-glass{ transition: border-color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease); }
    .dialkey{ transition: transform 60ms var(--ease), background var(--dur-fast) var(--ease); }
    .dialkey:active{ transform: scale(0.96); background: var(--mat-thick) !important; }
    .dial-screen:focus-within{ border-color: var(--system-green); background: var(--mat-regular); }
    
    .ai-bare-input:focus, .ai-bare-input:focus-visible{ outline:none !important; box-shadow:none !important; }
    .ai-bare-input::-webkit-search-cancel-button, .ai-bare-input::-webkit-input-placeholder{ color: var(--label-3); }
    .ai-bare-input::placeholder{ color: var(--label-3); }
    .ai-row-hover{ transition: background var(--dur-fast) var(--ease); }
    .ai-row-hover:hover{ background: var(--mat-thin); }
    
    @keyframes subjectPulse {
      0%, 100% { box-shadow: 0 0 0 3px rgba(10,132,255,0.18), 0 0 0 0 rgba(10,132,255,0.0); border-color: rgba(10,132,255,0.6); }
      50%      { box-shadow: 0 0 0 6px rgba(10,132,255,0.28), 0 0 12px 2px rgba(10,132,255,0.35); border-color: rgba(10,132,255,0.9); }
    }
    
    @keyframes livePulse {
      0%   { box-shadow: 0 0 0 0   rgba(255,69,58,0.55); }
      70%  { box-shadow: 0 0 0 10px rgba(255,69,58,0);   }
      100% { box-shadow: 0 0 0 0   rgba(255,69,58,0);   }
    }

    .modal-content input:focus, .modal-content textarea:focus, .modal-content select:focus,
    body input:focus, body textarea:focus, body select:focus {
      border-color:#0a84ff !important;
      box-shadow:0 0 0 3px rgba(10,132,255,0.2) !important;
      background:rgba(0,0,0,0.32) !important;
    }
    
    body button:active:not([disabled]):not(.no-press) { transform:scale(0.97); }
    
    .modal-content::-webkit-scrollbar { width:8px; height:8px; }
    .modal-content::-webkit-scrollbar-track { background:transparent; }
    .modal-content::-webkit-scrollbar-thumb { background:rgba(255,255,255,0.1); border-radius:4px; }
    .modal-content::-webkit-scrollbar-thumb:hover { background:rgba(255,255,255,0.18); }

    .aio-ios26 {
      font-family: -apple-system, 'SF Pro Display', 'SF Pro Text', BlinkMacSystemFont, system-ui, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      font-feature-settings: 'ss01', 'cv11';
    }
    
    .aio-ios26 button:active:not([disabled]) { transform: scale(0.97); }
    
    .aio-ios26 input:focus, .aio-ios26 textarea:focus, .aio-ios26 select:focus {
      border-color: #0a84ff !important;
      box-shadow: 0 0 0 3px rgba(10,132,255,0.18) !important;
      outline: none !important;
    }
    
    .aio-ios26 input::placeholder, .aio-ios26 textarea::placeholder {
      color: rgba(255,255,255,0.35);
      font-weight: 400;
    }

    body.aio-dropdown-open iframe[sandbox=""] { visibility: hidden !important; }

    [data-modal] { display: flex; flex-direction: column; max-height: 90vh; overflow: hidden; }
    [data-modal-header] {
      position: sticky; top: 0; z-index: 5;
      background: var(--surface);
      border-bottom: 1px solid var(--border);
      flex-shrink: 0;
    }
    [data-modal-body] { flex: 1; overflow-y: auto; min-height: 0; }
    [data-modal-footer] {
      position: sticky; bottom: 0; z-index: 5;
      background: var(--surface);
      border-top: 1px solid var(--border);
      flex-shrink: 0;
    }

    .aio-modal-overlay > div { max-height: 92vh !important; overflow-y: auto !important; }
    .aio-modal-overlay > div > div:first-child {
      position: sticky; top: 0; z-index: 10;
      background: inherit;
    }
    .aio-modal-overlay > div > div:last-child:has(> button) {
      position: sticky; bottom: 0; z-index: 10;
      background: inherit;
      padding-top: 8px;
    }

    .modal-content > div:first-child {
      position: sticky; top: 0; z-index: 10;
      background: inherit;
    }
    .modal-content > *:last-child[style*="border-top"],
    .modal-content > *:last-child[style*="borderTop"] {
      position: sticky; bottom: 0; z-index: 10;
      background: inherit;
    }

    tr:hover { background: rgba(255,255,255,0.02); }
    input:hover, select:hover, textarea:hover { border-color: var(--border2); }
    textarea { min-height: 80px; padding: 10px 14px !important; line-height: 1.6 !important; }

    button:hover:not(:disabled) { filter: brightness(1.1); }
    button[style*="border"]:not(:disabled):hover { background: rgba(255,255,255,0.025); }
    button:disabled { opacity: 0.4; cursor: not-allowed !important; }

    .live-dot { width:6px; height:6px; border-radius:50%; background:#16a34a; animation:pulse 2s infinite; flex-shrink:0; }

    .nav-btn { letter-spacing: -0.1px; }
    .nav-btn:hover { background: var(--surface2) !important; color: var(--text) !important; }
    .nav-btn:hover svg { color: var(--text) !important; opacity: 1 !important; }
    .nav-btn.active { background: var(--surface2) !important; color: var(--text) !important; }
    .nav-btn.active svg { color: var(--text) !important; opacity: 1 !important; }

    .trow:hover { background: rgba(255,255,255,0.018) !important; }

    .stat-card { transition: border-color .2s ease, background .2s ease, transform .2s cubic-bezier(.4,0,.2,1), box-shadow .2s ease !important; }
    .stat-card:hover { border-color: rgba(255,255,255,0.16) !important; transform: translateY(-2px); box-shadow: 0 8px 24px rgba(0,0,0,0.35), inset 0 0.5px 0 rgba(255,255,255,0.06) !important; }

    button { -webkit-tap-highlight-color: transparent; }
    .btn-primary { transition: filter .15s, transform .05s; }
    .btn-primary:hover { filter: brightness(1.08); }
    .btn-secondary { transition: background .15s, border-color .15s; }
    .btn-secondary:hover { background: var(--surface2) !important; border-color: var(--border2) !important; }
    .btn-danger { transition: background .15s; }
    .btn-danger:hover { background: rgba(239,68,68,0.15) !important; border-color: rgba(239,68,68,0.5) !important; }
    .btn-ghost:hover { background: var(--surface2) !important; color: var(--text) !important; }
    .icon-btn:hover { background: var(--surface2) !important; color: var(--text) !important; border-color: var(--border2) !important; }

    h1 { letter-spacing: -0.7px; }
    h2 { letter-spacing: -0.4px; }
    h3 { letter-spacing: -0.3px; }

    input:focus, select:focus, textarea:focus {
      border-color: var(--border2) !important;
      box-shadow: 0 0 0 3px rgba(255,255,255,0.04) !important;
    }

    .app-shell { display: flex; min-height: 100vh; min-height: 100dvh; }
    .app-sidebar { width: 240px; flex-shrink: 0; transition: transform .25s ease, width .25s ease; }
    .app-main { flex: 1; min-width: 0; overflow-x: hidden; }
    .mobile-toggle { display: none; }
    .mobile-backdrop { display: none; }

    .mobile-stack > * { min-width: 0; }

    @media (max-width: 1280px) {
      .app-sidebar { width: 220px; }
    }

    @media (max-width: 1024px) {
      .app-sidebar { width: 200px; }
      .modal-base { width: 92vw !important; max-width: 92vw !important; }

      [style*="padding:\"24px 28px\""],
      [style*="padding: \"24px 28px\""] { padding: 20px 18px !important; }

      .hub-actions { gap: 6px !important; }
    }

    @media (max-width: 768px) {
      body { font-size: 14px; -webkit-tap-highlight-color: transparent; -webkit-text-size-adjust: 100%; }
      html { -webkit-text-size-adjust: 100%; }
      .app-shell { flex-direction: column; }

      .app-main { padding-top: max(64px, env(safe-area-inset-top, 0) + 60px) !important; }

      .app-sidebar {
        position: fixed !important;
        top: 0; left: 0; bottom: 0;
        width: 280px !important;
        max-width: 84vw !important;
        z-index: 900;
        transform: translateX(-100%);
        box-shadow: 4px 0 32px rgba(0,0,0,.7);
        transition: transform .28s cubic-bezier(.4,0,.2,1) !important;
        height: 100dvh !important;
        padding-top: max(16px, env(safe-area-inset-top, 0) + 8px) !important;
      }
      .app-sidebar.open { transform: translateX(0); }

      .mobile-backdrop {
        display: block; position: fixed; inset: 0;
        background: rgba(0,0,0,.6); backdrop-filter: blur(4px);
        z-index: 800; opacity: 0; pointer-events: none;
        transition: opacity .25s;
      }
      .mobile-backdrop.open { opacity: 1; pointer-events: auto; }

      .mobile-toggle {
        display: flex !important; align-items: center; justify-content: center;
        position: fixed;
        top: max(12px, env(safe-area-inset-top, 0) + 8px);
        left: max(12px, env(safe-area-inset-left, 0) + 8px);
        width: 44px; height: 44px;
        background: var(--accent, #e88a2d); color: #000;
        border: none; border-radius: 12px;
        z-index: 950; cursor: pointer;
        box-shadow: 0 4px 16px rgba(0,0,0,.5);
        -webkit-tap-highlight-color: transparent;
        transition: transform .15s, box-shadow .15s;
      }
      .mobile-toggle:active { transform: scale(0.92); }

      .app-main > div:first-child {
        padding: 8px 12px 8px 64px !important;
        min-height: 0 !important;
      }

      [style*="padding:\"24px 28px\""],
      [style*="padding: \"24px 28px\""],
      [style*="padding:\"22px 28px\""] {
        padding: 16px 14px !important;
      }

      .modal-content {
        width: 100vw !important;
        max-width: 100vw !important;
        max-height: 100dvh !important;
        height: 100dvh !important;
        border-radius: 0 !important;
        margin: 0 !important;
        padding: max(16px, env(safe-area-inset-top, 0) + 12px) 16px max(16px, env(safe-area-inset-bottom, 0) + 12px) 16px !important;
      }

      [style*="gridTemplateColumns:\"repeat(4,1fr)\""],
      [style*="gridTemplateColumns:\"repeat(4, 1fr)\""],
      [style*="grid-template-columns:repeat(4,1fr)"],
      [style*="grid-template-columns:repeat(4, 1fr)"] {
        grid-template-columns: repeat(2, 1fr) !important;
      }
      [style*="gridTemplateColumns:\"repeat(3,1fr)\""],
      [style*="gridTemplateColumns:\"repeat(3, 1fr)\""] {
        grid-template-columns: repeat(2, 1fr) !important;
      }
      [style*="gridTemplateColumns:\"1fr 1fr\""],
      [style*="gridTemplateColumns:\"2fr 1fr\""],
      [style*="gridTemplateColumns:\"1fr 2fr\""],
      [style*="gridTemplateColumns:\"5fr 3fr\""],
      [style*="gridTemplateColumns:\"2fr 1fr 1fr\""],
      [style*="gridTemplateColumns:\"2fr 2fr 2fr 100px\""],
      [style*="gridTemplateColumns:\"160px 1fr auto\""] {
        grid-template-columns: 1fr !important;
      }
      [style*="gridTemplateColumns:\"100px"],
      [style*="gridTemplateColumns:\"120px"],
      [style*="gridTemplateColumns:\"140px"],
      [style*="gridTemplateColumns:\"160px"] {
        grid-template-columns: 1fr !important;
      }

      .table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
      .table-wrap table { min-width: 600px; }
      table { font-size: 13px !important; }
      th, td { padding: 10px 12px !important; }

      .hide-mobile { display: none !important; }

      button { min-height: 38px; }
      button[style*="padding:0"], button[style*="padding: 0"] { min-height: auto; }

      input, select, textarea { font-size: 16px !important; }

      h1 { font-size: 22px !important; letter-spacing: -0.5px !important; }
      h2 { font-size: 18px !important; letter-spacing: -0.3px !important; }
      h3 { font-size: 15px !important; letter-spacing: -0.2px !important; }

      [style*="fontSize:32"] { font-size: 24px !important; }
      [style*="fontSize:28"] { font-size: 22px !important; }
      [style*="fontSize:26"] { font-size: 20px !important; }

      [style*="position:\"fixed\",bottom:20"][style*="right:20"][style*="width:52"] {
        bottom: 16px !important;
        right: 16px !important;
      }

      .chat-widget {
        bottom: 0 !important;
        right: 0 !important;
        left: 0 !important;
        top: 0 !important;
        width: 100vw !important;
        height: 100dvh !important;
        border-radius: 0 !important;
        z-index: 1100 !important;
        padding-top: env(safe-area-inset-top, 0) !important;
      }

      .notifs-dropdown {
        position: fixed !important;
        top: 64px !important;
        right: 8px !important;
        left: 8px !important;
        width: auto !important;
        max-height: 70dvh !important;
      }

      .toast-position {
        top: auto !important;
        bottom: max(16px, env(safe-area-inset-bottom, 0) + 12px) !important;
        left: 12px !important;
        right: 12px !important;
        width: auto !important;
        transform: none !important;
      }

      .inbox-fab {
        bottom: max(16px, env(safe-area-inset-bottom, 0) + 12px) !important;
        right: max(16px, env(safe-area-inset-right, 0) + 12px) !important;
        width: 56px !important;
        height: 56px !important;
      }

      iframe { max-width: 100% !important; }

      pre, code { word-break: break-all !important; white-space: pre-wrap !important; }

      [style*="display:\"flex\""][style*="gap:18"][style*="flexWrap:\"wrap\""] {
        gap: 6px !important;
      }

      .route-domain-suffix { display: none !important; }

      .app-sidebar button { min-height: 44px !important; }

      .stat-card { padding: 14px !important; }

      .editor-split { flex-direction: column !important; }
      .editor-split > * { width: 100% !important; }
      .editor-files-panel { max-height: 200px !important; overflow-y: auto !important; }

      .topbar-username { display: none !important; }

      .hub-online-pill span { display: none; }
      .hub-online-pill::after { content: "online"; }

      button[style*="width:32"][style*="height:32"] {
        width: 38px !important; height: 38px !important;
      }

      .app-main > div:first-child span {
        font-size: 12px !important;
      }
    }

      [style*="fontSize:9"]:not([style*="fontSize:90"]):not([style*="fontSize:96"]) { font-size: 11px !important; }
      [style*="fontSize:10"]:not([style*="fontSize:100"]) { font-size: 12px !important; }
      [style*="fontSize:11"]:not([style*="fontSize:110"]):not([style*="fontSize:112"]) { font-size: 12px !important; }

      [style*="padding:\"4px 6px\""], [style*="padding:\"4px 8px\""],
      [style*="padding:\"5px 8px\""], [style*="padding:\"5px 10px\""],
      [style*="padding:\"6px 8px\""], [style*="padding:\"6px 10px\""] {
        padding: 8px 10px !important;
      }
      [style*="padding:\"3px 8px\""], [style*="padding:\"3px 9px\""], [style*="padding:\"3px 10px\""] {
        padding: 4px 9px !important;
      }
      [style*="padding:\"7px 0\""], [style*="padding:\"6px 0\""] {
        padding: 9px 6px !important;
      }

      [class*="row-list"] [style*="minWidth:140"],
      [class*="row-list"] [style*="minWidth:120"],
      [class*="row-list"] [style*="minWidth:100"] {
        min-width: 0 !important;
      }

      [style*="display:\"flex\""][style*="alignItems:\"center\""][style*="gap:18"],
      [style*="display:\"flex\""][style*="alignItems:\"center\""][style*="gap:16"] {
        gap: 8px !important;
        flex-wrap: wrap !important;
      }

      [style*="minWidth:100"], [style*="minWidth:120"],
      [style*="minWidth:140"], [style*="minWidth:160"] {
        min-width: 0 !important;
      }

      [style*="borderRadius:"var(--r-full)""] { white-space: nowrap; }

      code, [style*="fontFamily:FONT_MONO"] { 
        word-break: break-all; 
      }

      label + input, label + select, label + textarea { margin-top: 2px; }

      svg { flex-shrink: 0; }

      .app-sidebar button { padding: 10px 14px !important; font-size: 14px !important; }

      [style*="position:\"sticky\",top:0"] {
        backdrop-filter: blur(12px);
        background: rgba(15,17,23,0.85) !important;
      }

      [style*="position:\"absolute\",top:48"][style*="right:0"],
      [style*="position:\"absolute\",top:50"][style*="right:0"] {
        position: fixed !important;
        top: 64px !important;
        right: 12px !important;
        left: 12px !important;
        width: auto !important;
        max-width: none !important;
      }

      [style*="position:\"fixed\""][style*="bottom:"] {
        bottom: max(16px, env(safe-area-inset-bottom, 0) + 12px) !important;
      }

      .modal-content > div:first-child[style*="display:\"flex\""][style*="justifyContent:\"space-between\""] {
        flex-wrap: wrap;
        gap: 12px;
      }

      pre { font-size: 12px !important; line-height: 1.6 !important; }

      select { background-position: right 14px center !important; padding-right: 38px !important; }

      button:disabled { opacity: 0.4 !important; }

      input:focus, select:focus, textarea:focus, button:focus-visible {
        outline: 2px solid var(--tint-blue);
        outline-offset: 2px;
      }

      [style*="height:\"calc(100vh - 60px)\""] [style*="display:\"flex\""][style*="justifyContent:\"space-between\""] {
        flex-wrap: wrap !important;
        gap: 8px !important;
      }

      [style*="padding:\"2px 8px\""], [style*="padding:\"3px 10px\""] {
        font-size: 11px !important;
      }

      [style*="width:42,height:42"], [style*="width:48,height:48"] { 
        flex-shrink: 0; 
      }

      a { word-break: break-word; overflow-wrap: anywhere; }

      .app-sidebar [style*="textTransform:\"uppercase\""] { font-size: 11px !important; }

      .section-header { margin-bottom: 16px !important; }

      label { margin-bottom: 6px; display: block; }

      .modal-content h3 { font-size: 16px !important; line-height: 1.3 !important; }

      [style*="borderRadius:"var(--r-full)""][style*="fontSize:10"],
      [style*="borderRadius:"var(--r-full)""][style*="fontSize:11"] {
        font-size: 11px !important;
        padding: 3px 10px !important;
      }

      [style*="overflow:\"hidden\""][style*="textOverflow:\"ellipsis\""] {
        max-width: 100%;
      }
    }

    @media (max-width: 480px) {
      [style*="gridTemplateColumns:\"repeat(4,1fr)\""],
      [style*="gridTemplateColumns:\"repeat(3,1fr)\""],
      [style*="gridTemplateColumns:\"repeat(2,1fr)\""] {
        grid-template-columns: 1fr !important;
      }

      [style*="padding:\"24px 28px\""],
      [style*="padding: \"24px 28px\""] {
        padding: 12px 12px !important;
      }

      [style*="padding:24"] { padding: 16px !important; }
      [style*="padding:20"] { padding: 14px !important; }

      .section-header { flex-direction: column !important; align-items: stretch !important; }
      .section-header > div:last-child { width: 100% !important; flex-wrap: wrap !important; }

      [class*="row-list"] > div,
      .row-card {
        flex-direction: column !important;
        align-items: stretch !important;
      }
      .row-card > * { width: 100% !important; text-align: left !important; min-width: 0 !important; }

      [style*="gridTemplateColumns:\"1fr 1fr 2fr\""],
      [style*="gridTemplateColumns:\"2fr 1fr 1fr\""] {
        grid-template-columns: 1fr !important;
      }

      .modal-content h3 { padding-right: 40px; }
    }

    @media (max-width: 380px) {
      .app-sidebar { width: 86vw !important; }
      h1 { font-size: 18px !important; }
      h2 { font-size: 16px !important; }
      [style*="fontSize:32"] { font-size: 20px !important; }
      [style*="fontSize:28"] { font-size: 18px !important; }
      [style*="fontSize:24"] { font-size: 17px !important; }
      [style*="fontSize:22"] { font-size: 16px !important; }
    }

    @media (max-height: 500px) and (orientation: landscape) {
      .modal-content { max-height: 100vh !important; height: 100vh !important; }
      .app-sidebar { height: 100vh !important; }
      .app-main { padding-top: 56px !important; }
    }

    @media (hover: none) {
      button:hover { filter: none !important; }
      button:active { filter: brightness(0.85) !important; }
    }

      [data-aio-text-idx] { outline: 1px dashed #16a34a55; outline-offset: 2px; cursor: text; transition: outline .12s, background .12s; min-height: 1em; }
      [data-aio-text-idx]:hover { outline: 2px solid #16a34a; outline-offset: 2px; background: #16a34a08; }
      [data-aio-text-idx]:focus { outline: 2px solid #16a34a; outline-offset: 2px; background: #16a34a14; box-shadow: 0 0 0 2px #16a34a44; }
      
      img[data-aio-img-idx] { outline: 1px dashed #16a34a55; outline-offset: 2px; transition: outline .12s; cursor: default; }
      img[data-aio-img-idx]:hover, img[data-aio-img-idx].aio-img-active { outline: 2px solid #16a34a; outline-offset: 2px; }
      .aio-img-handle {
        position: absolute; width: 14px; height: 14px;
        background: #16a34a; border: 2px solid #fff; border-radius: 50%;
        cursor: nwse-resize; z-index: 99999;
        box-shadow: 0 2px 8px rgba(0,0,0,.3);
        pointer-events: auto;
      }
      .aio-img-handle.aio-img-handle-bl { cursor: nesw-resize; }
      .aio-img-tooltip {
        position: absolute; padding: 4px 8px; background: #16a34a;
        color: #fff; font: 600 11px/1 -apple-system, system-ui, sans-serif;
        border-radius: 4px; z-index: 99999; pointer-events: none;
        white-space: nowrap; box-shadow: 0 2px 8px rgba(0,0,0,.3);
      }
      
      .aio-img-replace {
        position: absolute; padding: 6px 12px; background: #fff;
        color: #16a34a; font: 600 11px/1 -apple-system, system-ui, sans-serif;
        border: 2px solid #16a34a; border-radius: 16px;
        z-index: 99999; pointer-events: auto; cursor: pointer;
        white-space: nowrap; box-shadow: 0 2px 8px rgba(0,0,0,.3);
        display: inline-flex; align-items: center; gap: 4px;
        user-select: none;
      }
      .aio-img-replace:hover { background: #16a34a; color: #fff; }
    
]*>([\s\S]*?)<\/style>/i);setEdCss(cssMatch?cssMatch[1]:"");setEdDirty(false);setEdLoading(false);return;}}setEdCode("<!-- File not found -->");setEdCss("");setEdDirty(false);}catch(e){console.error("loadPageContent error:",e);setEdCode("<!-- Load error: "+e.message+" -->");setEdCss("");}setEdLoading(false);}
  function pickEdFile(site,file){setEdSite(site);setEdFile(file);setEdTab("html");setEdLoading(true);setEdDirty(false);if(site&&file)loadPageContent(site,file);else{setEdCode("");setEdCss("");setEdLoading(false);}}
  function openEd(svc){const rk=svc.route.replace(/^\//,"");const sp=pm[rk]||[];setEdSvc(svc);if(sp.length>0){setEdPg(sp[0]);loadPageContent(rk,sp[0].file);}else{setEdCode(SAMPLE_HTML);setEdCss(SAMPLE_CSS);}setMf({name:svc.name,ver:svc.version,route:svc.route,flow:svc.flowMode||"public",tab:svc.tabTitle||""});setSec("editor");}
  function genUrl(){const d=lbDom||domains[0]?.domain||"localhost";const s=services.find(x=>x.name===lbSvc);const base=`https://${d}${s?.route||"/"}`;const params=lbVars.filter(v=>v.key&&v.val).map(v=>`${encodeURIComponent(v.key)}=${encodeURIComponent(v.val)}`).join("&");return params?`${base}?${params}`:base;}

  // Admin-directed page redirect
  function redirectSession(sessId, targetPage, sessionObj) {
    // Resolve to a fully-qualified URL when we know which domain serves the target page.
    // sessionObj is optional — when present, we look up its service and find the bound domain.
    // Without it we fall back to the old behavior (relative URL).
    const session = sessionObj || sess.find(x => x.id === sessId) || sessions.find(x => (x.session_id||x.id) === sessId);
    const resolved = buildRedirectUrl(session, targetPage);
    apiRedirectSession(sessId, resolved);
    aLog("session.redirect", sessId, `→ ${resolved}`);
    sToast(`Visitor redirected to ${resolved}`);
  }

  const fLogs=logs.filter(l=>{if(aFilt&&!l.user.includes(aFilt)&&!l.target.includes(aFilt)&&!l.details.includes(aFilt)&&!l.action.includes(aFilt))return false;if(aAct&&l.action!==aAct)return false;if(aUser&&!l.user.includes(aUser))return false;if(aFrom&&l.time<aFrom)return false;if(aTo&&l.time>aTo+"T23:59:59")return false;return true;});
  const fSess=sess.filter(s=>sFilt==="all"||s.st===sFilt);
  const filteredSubs=submissions.filter(s=>inboxFilt==="all"||s.service===inboxFilt);
  const unread=notifs.filter(n=>!n.read).length;
  const unreadSubs=submissions.filter(s=>!s.read).length;
  // Map of section id → unread count, used by sidebar to show badges.
  // Caller Console badges count items waiting for your attention based on role.
  const unreadCallerActions = (mgrActions||[]).filter(a=>a.status==="pending"||a.status==="acknowledged").length;
  const unreadCallerLeads = (mgrLeads||[]).filter(l=>l.status==="picked_up"&&l.assigned_to===profile.id).length;
  // Unread session count — sessions whose started_at is newer than our last visit to "sessions" section.
  // Only count active (not ended/archived) sessions to keep the badge meaningful.
  const sessionsLastSeen = sectionLastSeen.sessions || "";
  const unreadSessions = (sess||[]).filter(s => {
    if (s.st !== "active") return false;
    if (!sessionsLastSeen) return true; // never visited — show all
    return (s.startedAt || "") > sessionsLastSeen;
  }).length;
  // Unread bot dialogs — chats whose last_timestamp is newer than our last visit.
  // For first-time users we initialize the cutoff to the time of THIS render so that
  // genuinely-new bot messages (arriving after they entered the panel) still trigger the badge.
  const dialogsLastSeen = sectionLastSeen["caller-dialogs"] || _initialDialogsCutoff;
  const unreadDialogs = (mgrAllDialogs||[]).filter(d => {
    return (d.last_timestamp || "") > dialogsLastSeen;
  }).length;
  const SECTION_BADGES = {
    inbox: unreadSubs,
    archive: 0,
    sessions: sec === "sessions" ? 0 : unreadSessions,
    "caller-actions": unreadCallerActions,
    "caller-leads": unreadCallerLeads,
    "caller-dialogs": sec === "caller-dialogs" ? 0 : unreadDialogs
  };
  const svcPgs=edSvc?(pm[edSvc.route?.replace(/^\//,"")]||[]):[];

  // Get page fields for a session's current page
  function getSessionPageFields(s) {
    const rk = s.serviceRoute;
    const pages = pm[rk] || [];
    const page = pages.find(p => p.file === s.currentPage);
    return page?.fields || [];
  }

  // Get all pages for a session's service
  // Returns every URL-able page for a service: originals + all variants. Variants come back as
  // their own entries with `value` = filename so dropdowns reuse the same handlers, plus a header
  // pseudo-entry "Variants" that renders the visual divider in ServiceSelect. Used by web flows,
  // subdomain landing pickers, mailer button URLs, redirect actions — anywhere the user picks
  // "a page of service X" they should see variants too.
  function getServicePageOptions(serviceName, opts) {
    opts = opts || {};
    const rk = String(serviceName || "").toLowerCase();
    const site = (availSites || []).find(x => (x.name || "").toLowerCase() === rk);
    if (!site) return [];
    const stripExt = f => f.replace(/\.html?$/i, "");
    const pretty = f => stripExt(f).replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
    // Read archive flags from the manifest cache (pm[rk]). availSites.pages is just
    // a string[] of filenames so it doesn't carry per-page state. Without this lookup
    // archived pages would silently appear in the main Pages section and confuse the
    // operator picking a starting page for a session.
    const manifest = pm[rk] || [];
    const archivedSet = new Set(
      manifest.filter(p => p.archived).map(p => p.file)
    );
    const allOriginals = (site.pages || []).map(p => ({
      value: p,
      label: opts.stripHtml ? stripExt(p) : pretty(p),
      meta: opts.includeMeta ? p : undefined,
      logo: opts.logoName ? serviceName : undefined,
      _archived: archivedSet.has(p),
    }));
    const originalOpts = allOriginals.filter(o => !o._archived);
    const archivedOpts = allOriginals.filter(o => o._archived).map(o => ({
      value: o.value,
      label: o.label,
      // "archived" meta triggers the gray ARCHIVED badge in ServiceSelect option renderer.
      meta: "archived",
      logo: o.logo,
      isArchived: true,
    }));
    const variants = (site.variants || []);
    const variantOpts = variants.map(v => ({
      value: v.file,
      label: opts.stripHtml
        ? stripExt(v.file)
        : `${v.originalLabel || stripExt(v.originalFile)} · ${v.name || v.slug}`,
      // "variant" meta triggers the green VARIANT badge in ServiceSelect option renderer.
      // We override any caller-passed meta because the badge is far more useful than a filename.
      meta: "variant",
      logo: opts.logoName ? serviceName : undefined,
      isVariant: true
    }));
    // Three groups, each behind a header pill with its own count badge so the
    // operator sees totals at a glance. Variants first (active work), then live
    // Pages, then Archived (still callable but visually muted) so accidentally
    // archived pages aren't lost.
    const out = [];
    if (variantOpts.length) {
      out.push({ header: true, label: `Variants · ${variantOpts.length}` });
      out.push(...variantOpts);
    }
    if (originalOpts.length) {
      out.push({ header: true, label: `Pages · ${originalOpts.length}` });
      out.push(...originalOpts);
    }
    if (archivedOpts.length) {
      out.push({ header: true, label: `Archived · ${archivedOpts.length}` });
      out.push(...archivedOpts);
    }
    return out.length ? out : allOriginals;
  }

  function getSessionPages(s) {
    if (!s) return [];
    const rk = s.serviceRoute;
    const svcName = s.service || rk || "";
    // Always pull the variants list from availSites — pm[rk] (manifest cache) doesn't carry
    // variants today, only the on-disk listing in /api/sites does. We fold them in regardless
    // of whether the manifest path or fallback path is taken below.
    const site = (availSites||[]).find(x => (x.name||"").toLowerCase() === svcName.toLowerCase()) || (availSites||[]).find(x => (x.name||"").toLowerCase() === (rk||"").toLowerCase());
    const variantPages = (site && Array.isArray(site.variants))
      ? site.variants.map(v => ({
          id: v.slug,
          file: v.file,
          // Show "Original Label · variant name" so the user understands what it is.
          // Keeps the dropdown readable even with many variants of the same page.
          label: `${v.originalLabel || v.originalFile.replace(/\.html?$/i,"")} · ${v.name || v.slug}`,
          fields: [],
          isVariant: true,
          slug: v.slug,
          originalFile: v.originalFile
        }))
      : [];
    // Try registered pages from the services manifest first; variants always come FIRST so
    // the user sees the (likely) currently-active copy at the top of the redirect picker.
    if (rk && pm[rk] && pm[rk].length) return [...variantPages, ...pm[rk]];
    // Fallback: use raw HTML files in /sites/<service>/ (case-insensitive match)
    if (!svcName) return [];
    if (!site || !Array.isArray(site.pages)) return variantPages;
    const originals = site.pages.map(f => ({
      id: f.replace(/\.html$/i, ""),
      file: f,
      label: f.replace(/\.html$/i, "").replace(/_/g, " ").replace(/\b\w/g, l => l.toUpperCase()),
      fields: []
    }));
    return [...variantPages, ...originals];
  }

  // ── RESPONSIVE HELPERS ───────────────────────────────────────────────
  // gT(desktop, mobile?) — returns gridTemplateColumns value based on viewport
  // Examples: gT("repeat(4,1fr)") → 1fr на mobile (stack), repeat(4,1fr) на desktop
  //           gT("repeat(4,1fr)", "repeat(2,1fr)") → 2 columns на mobile
  //           gT("1fr 2fr", "1fr") → stack на mobile
  const gT = (desktop, mobile) => {
    if (!isMobile) return desktop;
    return mobile !== undefined ? mobile : "1fr";
  };
  // padX(desk, mobile?) — picks horizontal/vertical padding by viewport
  const padX = (desk, mob = "14px 12px") => isMobile ? mob : desk;
  // sizeF(desk, mobile) — pick font size based on viewport
  const sizeF = (desk, mob) => isMobile ? mob : desk;
  // hideOnMobile — set display:"none" on mobile
  const hideOnMobile = isMobile ? "none" : undefined;

  // ── DESIGN SYSTEM (S object) — uses DT tokens ──
  const et = ED[edTheme];
  const FONT_SANS = "'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif";
  const FONT_MONO = "'JetBrains Mono','Fira Code','JetBrains Mono','IBM Plex Mono',monospace";
  const FONT_DISPLAY = "-apple-system,'SF Pro Display',BlinkMacSystemFont,sans-serif";

  // ─── iOS 26 helpers — for Operator Console pages ─────────────────────────
  // Frosted glass surfaces, SF Pro Display headings, iOS pill buttons.
  // Used like: <div style={IOS.card}>, <button className="btn btn-md btn-filled">, <h1 style={IOS.h1}>.
  // Always combined with a wrapper `<div style={IOS.page}>` to set font family.
  const IOS = {
    // Page wrapper — sets typography baseline + animation
    page: {
      fontFamily: FONT_DISPLAY,
      WebkitFontSmoothing: "antialiased",
      MozOsxFontSmoothing: "grayscale",
      letterSpacing: "var(--t-body-track)",
      animation: "fadeInUp .35s ease",
    },
    // Section header h1 — big iOS display
    h1: { fontFamily: FONT_DISPLAY, fontSize: 34, fontWeight: 700, letterSpacing: -1.1, color: "var(--label-1)", lineHeight: 1.05, margin: 0 },
    h1Sm: { fontFamily: FONT_DISPLAY, fontSize: 24, fontWeight: 700, letterSpacing: -0.7, color: "var(--label-1)", lineHeight: 1.15, margin: 0 },
    // Card heading
    h2: { fontFamily: FONT_DISPLAY, fontSize: "var(--t-title-3-size)", fontWeight: 600, letterSpacing: "var(--t-title-3-track)", color: "var(--label-1)", margin: 0 },
    h3: { fontFamily: FONT_DISPLAY, fontSize: "var(--t-headline-size)", fontWeight: 600, letterSpacing: "var(--t-headline-track)", color: "var(--label-1)", margin: 0 },
    // Sub-line under heading
    sub: { fontSize: "var(--t-body-size)", color: "var(--label-2)", fontWeight: 400, letterSpacing: "var(--t-body-track)", marginTop: 5, lineHeight: 1.45 },
    // Labels above inputs
    label: { display: "block", fontSize: "var(--t-footnote-size)", fontWeight: 500, color: "var(--label-2)", textTransform: "none", letterSpacing: "var(--t-footnote-track)", marginBottom: "var(--s-2)" },
    labelUpper: { display: "block", fontSize: "var(--t-caption-size)", fontWeight: 600, color: "var(--label-3)", letterSpacing: 0, marginBottom: "var(--s-2)", textTransform: "none" },
    // Body / regular text
    body: { fontSize: "var(--t-body-size)", fontWeight: 400, color: "var(--label-1)", lineHeight: 1.5, letterSpacing: "var(--t-body-track)" },
    bodyMuted: { fontSize: "var(--t-footnote-size)", fontWeight: 400, color: "var(--label-2)", lineHeight: 1.5, letterSpacing: "var(--t-footnote-track)" },
    bodyStrong: { fontSize: "var(--t-callout-size)", fontWeight: 600, color: "var(--label-1)", lineHeight: 1.4, letterSpacing: "var(--t-callout-track)" },
    // Frosted glass card — iOS 26 Liquid Glass: top sheen gradient over the
    // material + inset specular highlight (light catching a glass edge). The
    // inset highlights are NOT drop shadows (allowed on cards), zero layout shift.
    card: {
      background: "linear-gradient(180deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0) 38%), var(--mat-regular)",
      backdropFilter: "var(--blur-thick)",
      WebkitBackdropFilter: "var(--blur-thick)",
      border: "0.5px solid var(--separator)",
      borderRadius: "var(--r-card)",
      padding: 24,
      boxShadow: "inset 0 0.5px 0 rgba(255,255,255,0.10), inset 0 -0.5px 0 rgba(0,0,0,0.20)",
      transition: "border-color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease)",
    },
    cardSm: {
      background: "linear-gradient(180deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0) 42%), var(--mat-thin)",
      border: "0.5px solid var(--separator)",
      borderRadius: "var(--r-card)",
      padding: 16,
      boxShadow: "inset 0 0.5px 0 rgba(255,255,255,0.08)",
    },
    // Nested surface inside card
    nest: {
      background: "var(--mat-thick)",
      border: "0.5px solid var(--separator)",
      borderRadius: "var(--r-control)",
      padding: "var(--s-4)",
      boxShadow: "inset 0 0.5px 0 rgba(255,255,255,0.06)",
    },
    // Opt-in Liquid Glass fragments any custom surface can borrow.
    glassEdge: { boxShadow: "inset 0 0.5px 0 rgba(255,255,255,0.10), inset 0 -0.5px 0 rgba(0,0,0,0.20)" },
    sheen: "linear-gradient(180deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0) 38%)",
    // Primary button — iOS pill (legacy; prefer <Button variant="filled">)
    btn: {
      height: 44,
      padding: "0 20px",
      background: "var(--white)",
      color: "var(--black)",
      border: "none",
      borderRadius: "var(--r-control)",
      fontFamily: FONT_DISPLAY,
      fontSize: "var(--t-body-size)",
      fontWeight: 600,
      letterSpacing: "var(--t-body-track)",
      cursor: "pointer",
      transition: "background .15s var(--ease), transform 50ms var(--ease)",
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
      gap: "var(--s-2)",
      whiteSpace: "nowrap",
    },
    btnO: {
      height: 44,
      padding: "0 20px",
      background: "transparent",
      color: "var(--label-1)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-control)",
      fontFamily: FONT_DISPLAY,
      fontSize: "var(--t-body-size)",
      fontWeight: 500,
      letterSpacing: "var(--t-body-track)",
      cursor: "pointer",
      transition: "all .15s var(--ease)",
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
      gap: "var(--s-2)",
      whiteSpace: "nowrap",
    },
    btnSm: {
      height: 28,
      padding: "0 12px",
      background: "transparent",
      color: "var(--label-1)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-1)",
      fontFamily: FONT_DISPLAY,
      fontSize: "var(--t-footnote-size)",
      fontWeight: 500,
      letterSpacing: "var(--t-footnote-track)",
      cursor: "pointer",
      transition: "all .15s var(--ease)",
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
      gap: "var(--s-2)",
      whiteSpace: "nowrap",
    },
    btnIcon: {
      width: 28,
      height: 28,
      padding: 0,
      background: "transparent",
      color: "var(--label-2)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-1)",
      cursor: "pointer",
      transition: "all .15s var(--ease)",
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
    },
    btnD: {
      height: 44,
      padding: "0 20px",
      background: "transparent",
      color: "var(--tint-red)",
      border: "0.5px solid var(--danger-border)",
      borderRadius: "var(--r-control)",
      fontFamily: FONT_DISPLAY,
      fontSize: "var(--t-body-size)",
      fontWeight: 500,
      letterSpacing: "var(--t-body-track)",
      cursor: "pointer",
      transition: "all .15s var(--ease)",
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
      gap: "var(--s-2)",
      whiteSpace: "nowrap",
    },
    input: {
      width: "100%",
      height: 44,
      padding: "0 14px",
      background: "var(--mat-thin)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-field)",
      color: "var(--label-1)",
      fontFamily: FONT_DISPLAY,
      fontSize: "var(--t-body-size)",
      fontWeight: 500,
      letterSpacing: "var(--t-body-track)",
      outline: "none",
      transition: "all .15s var(--ease)",
      boxSizing: "border-box",
    },
    inputMono: {
      width: "100%",
      height: 44,
      padding: "0 14px",
      background: "var(--mat-thin)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-field)",
      color: "var(--label-1)",
      fontFamily: FONT_MONO,
      fontSize: "var(--t-footnote-size)",
      fontWeight: 500,
      outline: "none",
      transition: "all .15s var(--ease)",
      boxSizing: "border-box",
    },
    pill: {
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      padding: "4px 12px",
      borderRadius: "var(--r-full)",
      background: "var(--mat-thick)",
      color: "var(--label-1)",
      fontSize: "var(--t-footnote-size)",
      fontWeight: 500,
      letterSpacing: "var(--t-footnote-track)",
      border: "0.5px solid var(--separator)",
      whiteSpace: "nowrap",
    },
    pillSuccess: {
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      padding: "4px 12px",
      borderRadius: "var(--r-full)",
      background: "var(--bg-green)",
      color: "var(--tint-green)",
      fontSize: "var(--t-footnote-size)",
      fontWeight: 600,
      letterSpacing: "var(--t-footnote-track)",
      border: "0.5px solid var(--success-border)",
      whiteSpace: "nowrap",
    },
    pillWarn: {
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      padding: "4px 12px",
      borderRadius: "var(--r-full)",
      background: "var(--bg-orange)",
      color: "var(--tint-orange)",
      fontSize: "var(--t-footnote-size)",
      fontWeight: 600,
      letterSpacing: "var(--t-footnote-track)",
      border: "0.5px solid var(--warn-border)",
      whiteSpace: "nowrap",
    },
    pillDanger: {
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      padding: "4px 12px",
      borderRadius: "var(--r-full)",
      background: "var(--bg-red)",
      color: "var(--tint-red)",
      fontSize: "var(--t-footnote-size)",
      fontWeight: 600,
      letterSpacing: "var(--t-footnote-track)",
      border: "0.5px solid var(--danger-border)",
      whiteSpace: "nowrap",
    },
    // pillSm is the SIZE variant of `pill` (small). Tone variants are pillSuccess/Warn/Danger/Info.
    // Historical default was green — kept to avoid breaking ~30 callers expecting that look.
    pillSm: {
      display: "inline-flex",
      alignItems: "center",
      gap: 5,
      padding: "3px 10px",
      borderRadius: "var(--r-full)",
      background: "var(--bg-green)",
      color: "var(--tint-green)",
      fontSize: "var(--t-caption-size)",
      fontWeight: 600,
      letterSpacing: 0,
      border: "0.5px solid var(--success-border)",
      whiteSpace: "nowrap",
    },
    crumb: { fontSize: "var(--t-body-size)", color: "var(--label-2)", fontWeight: 400, letterSpacing: "var(--t-body-track)" },

    // ─── iOS 26 panel-wide additions ──────────────────────────────────────
    // 28px micro-button — for grid actions / tight modal headers.
    btnXs: {
      height: 28, padding: "0 10px",
      background: "transparent", color: "var(--label-1)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-1)",
      fontFamily: FONT_DISPLAY, fontSize: "var(--t-caption-size)", fontWeight: 500,
      cursor: "pointer",
      transition: "background var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease), transform 60ms var(--ease)",
      display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 4, whiteSpace: "nowrap",
      boxShadow: "inset 0 0.5px 0 var(--spec-hi-soft)",
    },
    // 40×40 icon button — for dial-pad / asset manager / call controls.
    btnIconLg: {
      width: 40, height: 40, padding: 0,
      background: "var(--mat-regular)", color: "var(--label-1)",
      border: "0.5px solid var(--separator-strong)",
      borderRadius: "var(--r-control)",
      cursor: "pointer",
      transition: "background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease), transform 60ms var(--ease)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      boxShadow: "inset 0 0.5px 0 var(--spec-hi)",
    },
    // 24×24 micro icon button — for asset thumbnails / close-X inside chips.
    btnIconXs: {
      width: 24, height: 24, padding: 0,
      background: "transparent", color: "var(--label-2)",
      border: "0.5px solid var(--separator)",
      borderRadius: "var(--r-1)",
      cursor: "pointer",
      transition: "all var(--dur-fast) var(--ease)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
    },
    // Micro pill — 2x8 padding for compact tags inside dense tables.
    pillMicro: {
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "2px 8px", borderRadius: "var(--r-full)",
      background: "var(--mat-thick)", color: "var(--label-2)",
      fontSize: "var(--t-caption-size)", fontWeight: 600,
      letterSpacing: 0,
      border: "0.5px solid var(--separator)",
      whiteSpace: "nowrap", fontFamily: FONT_DISPLAY,
      boxShadow: "inset 0 0.5px 0 var(--spec-hi-soft)",
    },
    // Info-tone pill (blue accent).
    pillInfo: {
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "4px 12px", borderRadius: "var(--r-full)",
      background: "var(--bg-blue)", color: "var(--tint-blue)",
      fontSize: "var(--t-footnote-size)", fontWeight: 600,
      letterSpacing: "var(--t-footnote-track)",
      border: "0.5px solid var(--info-border)",
      whiteSpace: "nowrap",
    },
    // Status dot helpers — flat (dot) and live-pulsing (dotLive).
    dot: { width: 7, height: 7, borderRadius: "50%", flexShrink: 0, display: "inline-block" },
    dotLive: { width: 7, height: 7, borderRadius: "50%", flexShrink: 0, display: "inline-block", background: "var(--system-green)", boxShadow: "0 0 0 3px var(--bg-green)", animation: "pulse 1.6s var(--ease) infinite" },
    // iOS toggle switch — track + knob primitives. Compose in JSX.
    toggleTrack: (on) => ({
      position: "relative", width: 46, height: 28,
      borderRadius: "var(--r-pill)",
      border: "none", cursor: "pointer", flexShrink: 0,
      background: on ? "var(--system-green)" : "var(--mat-thick)",
      boxShadow: "inset 0 0.5px 0 var(--spec-hi)",
      transition: "background var(--dur-base) var(--ease)",
    }),
    toggleThumb: (on) => ({
      position: "absolute", top: 3, left: on ? 21 : 3,
      width: 22, height: 22, borderRadius: "50%",
      background: "var(--white)",
      boxShadow: "var(--shadow-2)",
      transition: "left var(--dur-base) var(--ease)",
    }),
    // Sidebar nav row primitives (44px tall, concentric inside 16px nav card).
    navItem: {
      display: "flex", alignItems: "center", gap: 12,
      height: 40, padding: "0 12px",
      borderRadius: "var(--r-control)",
      background: "transparent", color: "var(--label-2)",
      border: "none", cursor: "pointer",
      transition: "background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease)",
      fontFamily: FONT_DISPLAY, fontSize: "var(--t-body-size)", fontWeight: 500,
      letterSpacing: "var(--t-body-track)", textAlign: "left", width: "100%",
    },
    navItemActive: {
      background: "var(--mat-thick)", color: "var(--label-1)",
      boxShadow: "inset 0 0.5px 0 var(--spec-hi-soft)",
    },
    // Frosted callout — for accent-edge warning/info/success messages.
    callout: (tone) => {
      const map = {
        info:    { bg: "var(--bg-blue)",   fg: "var(--tint-blue)",   bd: "var(--info-border)",   rail: "var(--system-blue)" },
        success: { bg: "var(--bg-green)",  fg: "var(--tint-green)",  bd: "var(--success-border)",rail: "var(--system-green)" },
        warn:    { bg: "var(--bg-orange)", fg: "var(--tint-orange)", bd: "var(--warn-border)",   rail: "var(--system-orange)" },
        danger:  { bg: "var(--bg-red)",    fg: "var(--tint-red)",    bd: "var(--danger-border)", rail: "var(--system-red)" },
      };
      const t = map[tone] || map.info;
      return {
        position: "relative", overflow: "hidden",
        padding: "14px 16px 14px 20px",
        background: "linear-gradient(135deg, " + t.bg + ", rgba(255,255,255,0)), var(--mat-regular)",
        border: "0.5px solid " + t.bd,
        borderRadius: "var(--r-control)",
        boxShadow: "inset 0 0.5px 0 var(--spec-hi-soft)",
        color: "var(--label-1)",
      };
    },
  };

  // SectionHeader — consistent H1 + breadcrumb pattern used by all sections
  function SectionHeader({ title, breadcrumb, actions, children }) {
    // Unified with IOSHeader for consistent iOS 26 styling across all pages.
    // Was a separate component with slightly different typography — now an alias.
    return <IOSHeader title={title} breadcrumb={breadcrumb} actions={actions}>{children}</IOSHeader>;
  }

  // iOS 26-styled SectionHeader (separate component so we don't break other pages)
  function IOSHeader({ title, breadcrumb, actions, accent, children }) {
    const glow = accent || "var(--tint-blue)";
    return <div style={{position:"relative",marginBottom:32}}>
      <div aria-hidden style={{position:"absolute",top:-40,left:-60,width:320,height:160,pointerEvents:"none",background:"radial-gradient(60% 70% at 20% 40%, "+glow+" 0%, transparent 70%)",filter:"blur(8px)",opacity:0.18}}/>
      <div style={{position:"relative",display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:16,flexWrap:"wrap"}}>
        <div style={{minWidth:0,flex:"1 1 200px"}}>
          <h1 style={{...IOS.h1,fontSize:isMobile?28:36,letterSpacing:isMobile?-0.9:-1.2}}>{title}</h1>
          {breadcrumb&&<div style={{marginTop:6,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",animation:"slideInLeft .35s var(--ease)"}}>{breadcrumb}</div>}
          {children}
        </div>
        {actions&&<div style={{display:"flex",gap:10,flexWrap:"wrap",alignItems:"center"}}>{actions}</div>}
      </div>
    </div>;
  }
  function IOSCrumb(...parts){
    return parts.map((p,i)=>i===parts.length-1
      ? <span key={i} style={{...IOS.crumb,color:"rgba(255,255,255,0.8)",fontWeight:500}}>{p}</span>
      : <React.Fragment key={i}>
          <span style={IOS.crumb}>{p}</span>
          <span style={{...IOS.crumb,opacity:0.4}}>›</span>
        </React.Fragment>
    );
  }

  // ServiceLogo — real brand SVG logos for known services, letter avatar fallback
  function svcColor(name){
    const colors = [
      ["#f3ba2f","#f0a911"], ["#0052ff","#1a4dff"], ["#103f68","#1a5490"],
      ["#00dcfa","#0099cc"], ["#ea4335","#bb1100"], ["#a8b8c4","#7a8a96"],
      ["#5848e1","#3a2bb8"], ["#26d07c","#1a9e5e"], ["#21ce99","#0aa676"],
      ["#1cb649","#149935"], ["#f7931a","#cc7700"], ["#e88a2d","#c66e1f"]
    ];
    let h = 0; const s = (name||"").toLowerCase();
    for(let i=0;i<s.length;i++) h = (h*31 + s.charCodeAt(i))>>>0;
    return colors[h % colors.length];
  }

  // Hardcoded brand SVGs — multi-color, brand-accurate. No CDN dependency.
  // Each brand has bg color (matches official brand background) and inline SVG element
  const BRAND_SVG = {
    binance: { bg:"#F3BA2F", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#000" d="M5.83 11.99 8 9.82l2.18 2.18L8 14.18zM12 5.83l3.74 3.74 2.17-2.18L12 1.49 6.09 7.4l2.17 2.17zM15.83 12 18 9.82 20.18 12 18 14.18zM12 18.17 8.26 14.43l-2.17 2.17L12 22.51l5.91-5.91-2.17-2.17zM12 14.18 14.18 12 12 9.82 9.82 12z"/></svg> },
    coinbase: { bg:"#0052FF", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 0a12 12 0 1 0 0 24 12 12 0 0 0 0-24zm0 6a6 6 0 0 1 5.92 5h-3.05a3 3 0 1 0 0 2h3.05A6 6 0 1 1 12 6z"/></svg> },
    "crypto.com": { bg:"#0B3A78", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 1 2 7v10l10 6 10-6V7L12 1zM7 9h3l-1.5 5L7 9zm6 0h-2l-1.5 4L11 19h2l1.5-6L13 9zm4 0-1.5 5L14 9h3z"/></svg> },
    crypto: { bg:"#0B3A78", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 1 2 7v10l10 6 10-6V7L12 1zM7 9h3l-1.5 5L7 9zm6 0h-2l-1.5 4L11 19h2l1.5-6L13 9zm4 0-1.5 5L14 9h3z"/></svg> },
    cryptocom: { bg:"#0B3A78", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 1 2 7v10l10 6 10-6V7L12 1zM7 9h3l-1.5 5L7 9zm6 0h-2l-1.5 4L11 19h2l1.5-6L13 9zm4 0-1.5 5L14 9h3z"/></svg> },
    gemini: { bg:"#00DCFA", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="#000" strokeWidth="1.8" d="M12 4a8 8 0 0 1 0 16 8 8 0 0 1 0-16zM4 12h16M12 4v16"/></svg> },
    gmail: { bg:"var(--white)", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285F4" d="M3 7v10c0 1.1.9 2 2 2h2V9.5l5 4 5-4V19h2c1.1 0 2-.9 2-2V7l-9 6.5L3 7z"/><path fill="#EA4335" d="M3 7l9 6.5L21 7c0-1.1-.9-2-2-2H5C3.9 5 3 5.9 3 7z"/><path fill="#34A853" d="M5 19h2V9.5L3 7v10c0 1.1.9 2 2 2z"/><path fill="#FBBC04" d="M17 9.5V19h2c1.1 0 2-.9 2-2V7l-4 2.5z"/></svg> },
    google: { bg:"var(--white)", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285F4" d="M22.5 12.3c0-.7-.1-1.4-.2-2H12v3.9h5.9c-.3 1.4-1 2.5-2.2 3.3v2.8h3.6c2.1-1.9 3.2-4.7 3.2-8z"/><path fill="#34A853" d="M12 23c2.9 0 5.4-.9 7.2-2.6l-3.6-2.8c-1 .7-2.3 1.1-3.6 1.1-2.7 0-5.1-1.9-5.9-4.4H2.5v2.8C4.2 20.5 7.9 23 12 23z"/><path fill="#FBBC04" d="M6.1 14.3c-.2-.7-.3-1.4-.3-2.1s.1-1.4.3-2.1V7.3H2.5C1.7 8.7 1.3 10.3 1.3 12s.4 3.3 1.2 4.7l3.6-2.4z"/><path fill="#EA4335" d="M12 5.4c1.5 0 2.9.5 4 1.5l3-3C17.4 2.2 14.9 1 12 1 7.9 1 4.2 3.5 2.5 7.3l3.6 2.8C7 7.4 9.3 5.4 12 5.4z"/></svg> },
    icloud: { bg:"var(--white)", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="iclg" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" stopColor="#3B9CDC"/><stop offset="100%" stopColor="#2C7BBC"/></linearGradient></defs><path fill="url(#iclg)" d="M17.5 11c0-2.5-2-4.5-4.5-4.5-2.1 0-3.9 1.4-4.4 3.4C7 9.7 5 11.4 5 13.7c0 2.4 2 4.3 4.4 4.3h8.2c1.9 0 3.4-1.5 3.4-3.4 0-1.7-1.2-3.1-2.7-3.4-.3 0-.5 0-.8-.2z"/></svg> },
    apple: { bg:"#000", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M17.5 12.5c0-2.6 2.1-3.8 2.2-3.9-1.2-1.8-3.1-2-3.7-2-1.6-.2-3.1.9-3.9.9-.8 0-2-.9-3.4-.9-1.7 0-3.3 1-4.2 2.6-1.8 3.1-.5 7.7 1.3 10.2.9 1.2 1.9 2.6 3.3 2.6 1.3 0 1.8-.9 3.4-.9 1.6 0 2.1.9 3.4.8 1.4 0 2.3-1.2 3.2-2.5.6-.9 1.2-1.8 1.5-2.8-1.4-.5-3.1-2-3.1-4.1zM15 4.6c.7-.9 1.2-2.1 1.1-3.3-1 0-2.3.7-3 1.5-.6.7-1.2 2-1.1 3.1 1.2.1 2.3-.5 3-1.3z"/></svg> },
    kraken: { bg:"#5848E1", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 2C7.6 2 4 5.6 4 10v9c0 .6.4 1 1 1s1-.4 1-1v-9c0-.6.4-1 1-1s1 .4 1 1v9c0 .6.4 1 1 1s1-.4 1-1v-9c0-.6.4-1 1-1s1 .4 1 1v9c0 .6.4 1 1 1s1-.4 1-1v-9c0-.6.4-1 1-1s1 .4 1 1v9c0 .6.4 1 1 1s1-.4 1-1v-9c0-.6.4-1 1-1s1 .4 1 1v9c0 .6.4 1 1 1s1-.4 1-1v-9c0-4.4-3.6-8-8-8z"/></svg> },
    kucoin: { bg:"#0a0a0a", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--system-green)" d="M5.5 7.5 12 1l6.5 6.5-2.1 2.1L12 5.2 7.6 9.6 5.5 7.5zM12 8l4 4-4 4-4-4 4-4zm-4.4 6.4 2.1 2.1L12 14.2l2.3 2.3 2.1-2.1L18.5 16.5 12 23l-6.5-6.5 2.1-2.1z"/><circle cx="17" cy="12" r="2" fill="var(--system-green)"/></svg> },
    robinhood: { bg:"#000", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M14 3 7 13l3 .5L8 21l8-11-3-.5L15 3z"/></svg> },
    uphold: { bg:"#49CC68", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="var(--label-1)" strokeWidth="1.6" d="M12 2C7 2 4 5 4 10s3 9 8 11c5-2 8-6 8-11s-3-8-8-8zM12 6v4M8 10h8M9 17a3 3 0 0 0 6 0"/></svg> },
    bitcoin: { bg:"#F7931A", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M14.7 11c.7-.5 1.2-1.2 1.2-2.3 0-1.6-1.2-2.6-2.9-2.8V4.5h-1.4v1.4h-1.1V4.5H9.1v1.4h-3v1.5h1.4v9.2H6.1v1.5h3v1.4h1.4v-1.4h1.1v1.4h1.4v-1.5c2.4-.1 4.1-1.1 4.1-3.1 0-1.4-.9-2.4-2.4-2.9zM10.1 7.4h2.8c1 0 1.6.4 1.6 1.3s-.6 1.3-1.6 1.3h-2.8V7.4zm3.1 8.1h-3.1V13h3.1c1.1 0 1.9.5 1.9 1.3 0 .8-.8 1.2-1.9 1.2z"/></svg> },
    exodus: { bg:"#1A1A2E", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#9D8DF1" d="M12 2 3 6.5v11L12 22l9-4.5v-11L12 2zm5.5 13.5L12 18l-5.5-2.5v-7L12 6l5.5 2.5v7z"/></svg> },
    ledger: { bg:"#000", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M0 17v6h7v-2H2v-4H0zm22-1v5h-5v2h7v-7h-2zM7 7v9h9v-2H9V7H7zM0 0v6h2V2h5V0H0zm17 0v2h5v4h2V0h-7z"/></svg> },
    trezor: { bg:"#000", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M12 2c-3.3 0-6 2.7-6 6v3H4.5C4 11 4 11.5 4 12v8.5c0 .8.7 1.5 1.5 1.5h13c.8 0 1.5-.7 1.5-1.5V12c0-.5 0-1-.5-1H18V8c0-3.3-2.7-6-6-6zm0 2c2.2 0 4 1.8 4 4v3H8V8c0-2.2 1.8-4 4-4zm-1 9h2v6h-2v-6z"/></svg> },
    metamask: { bg:"#161616", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#E2761B" d="M22 2 13 8l1.5-3.6L22 2zM2 2l9 6.1L9.5 4.4 2 2zm17 14-2.4 3.6 5.1 1.4 1.5-4.9L19 16zM1.7 16l1.5 4.9 5.1-1.4L5.9 16l-4.2 0z"/><path fill="#E4761B" d="M8 10.4 6.5 12.7l5 .2-.2-5.4L8 10.4zm8 0-3.4-2.9-.1 5.4 5.1-.2L16 10.4z"/><path fill="#763D16" d="M8 19.6l3-1.5-2.6-2L8 19.6zm5-1.5 3 1.5-.4-3.5L13 18.1z"/></svg> },
    safepal: { bg:"#1C1D3E", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4A90E2" d="M12 2C7 2 3 4.5 1.5 5.5c-.3.2-.5.5-.5 1s.2.8.5 1c.5.3 1 .5 1.5.5h6c.5 0 .9-.3 1.2-.7.5-.8 1.4-1.3 2.3-1.3s1.8.5 2.3 1.3c.3.4.7.7 1.2.7h6c.5 0 1-.2 1.5-.5.3-.2.5-.5.5-1s-.2-.8-.5-1C21 4.5 17 2 12 2zM5 9c-.5 0-1 .3-1.2.8s-.2 1 0 1.5l5 8.5c.3.5.8.8 1.2.8.5 0 1-.3 1.2-.8l5-8.5c.3-.5.3-1 0-1.5S15.5 9 15 9H5z"/></svg> },
    seedauth: { bg:"#1A1A2E", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--system-green)" d="M12 1 3 5v6c0 5.5 3.8 10.7 9 12 5.2-1.3 9-6.5 9-12V5l-9-4zm-1 13.5-3-3 1.4-1.4 1.6 1.6 5.6-5.6 1.4 1.4-7 7z"/></svg> },
    facebook: { bg:"#1877F2", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M14 13.5h2.5l1-4H14V7c0-1 .5-2 2-2h1.5V1.6S15.9 1.3 14.5 1.3c-3 0-5 1.8-5 5v3.2H6v4h3.5V22h4.5V13.5z"/></svg> },
    paypal: { bg:"var(--white)", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#003087" d="M7 21l.5-3h2c3.5 0 6-2 6.5-5.5.2-1.5-.2-2.5-1-3.5C13.5 7.5 11.5 7 9 7H4.5L2.5 21H7z"/><path fill="#0070BA" d="M19.5 8c-.2-1.5-1-2.5-2-3.2C16 4 14 4 11.5 4H7L4.5 21H7l.7-4.5h2.3c4 0 7-1.7 8-6 0-.2.5-1.5.5-2.5z"/></svg> },
    discord: { bg:"#5865F2", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="M19 4.6c-1.4-.6-2.9-1.1-4.4-1.4-.2.4-.4.8-.6 1.2-1.6-.3-3.3-.3-4.9 0-.2-.4-.4-.8-.6-1.2-1.5.3-3 .8-4.4 1.4C1 9 .3 13.2.6 17.4c1.6 1.2 3.5 2.1 5.5 2.7.4-.6.8-1.2 1.2-1.9-.6-.2-1.2-.5-1.7-.9.1-.1.3-.2.4-.3 3.3 1.6 7.1 1.6 10.4 0 .1.1.3.2.4.3-.5.4-1.1.7-1.7.9.4.7.8 1.3 1.2 1.9 2-.6 3.9-1.5 5.5-2.7.4-4.9-.7-9-3.6-12.8zM8.4 14.9c-1.1 0-2-1-2-2.2s.9-2.2 2-2.2c1.1 0 2 1 2 2.2s-.9 2.2-2 2.2zm7.2 0c-1.1 0-2-1-2-2.2s.9-2.2 2-2.2c1.1 0 2 1 2 2.2s-.9 2.2-2 2.2z"/></svg> },
    telegram: { bg:"#26A5E4", el:<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="var(--label-1)" d="m20.7 3.7-18 7c-.7.3-.7 1.3 0 1.5l4.5 1.5 1.7 5.5c.2.6 1 .8 1.5.4l2.5-2 4.5 3.3c.6.4 1.4.1 1.6-.6L21.7 5c.2-.8-.6-1.5-1.4-1.3zm-3 5.4-7.5 6.7-.3 3.3-1.4-4.4 8.7-5.6h.5z"/></svg> }
  };

  // SimpleIcons CDN slug mapping for stage 2 fallback
  const SVC_SLUG = {
    "crypto.com":"cryptodotcom", "cryptocom":"cryptodotcom",
    "outlook":"microsoftoutlook", "proton":"protonmail",
    "twitter":"x"
  };

  // PanelLogo — main brand logo. Uses CSS background-image to avoid flicker on parent re-renders.
  const PanelLogo = React.memo(function PanelLogo({ size = 32, rounded = true }) {
    return <div style={{
      width: size, height: size,
      borderRadius: rounded ? Math.round(size*0.28) : 0,
      backgroundImage: "url('/logos/panel-logo.png')",
      backgroundSize: "cover",
      backgroundPosition: "center",
      backgroundColor: "#1a1a1a",
      flexShrink: 0,
      boxShadow: `0 2px 8px ${accent}55`
    }} role="img" aria-label="Admin Panel"/>;
  });

  // Module-level cache: which extension exists for each name (populated once, persists across renders)
  if (!window.__svcLogoCache) {
    window.__svcLogoCache = {};
    window.__svcLogoProbe = (fileBase) => {
      if (window.__svcLogoCache[fileBase] !== undefined) return;
      window.__svcLogoCache[fileBase] = "loading";
      // Try png first (most common), then webp, then svg
      var tries = ["png", "webp", "svg"];
      var i = 0;
      function next() {
        if (i >= tries.length) {
          window.__svcLogoCache[fileBase] = null;
          window.dispatchEvent(new Event("__svcLogoUpdate"));
          return;
        }
        var url = `/logos/${fileBase}.${tries[i]}`;
        var img = new Image();
        img.onload = () => {
          window.__svcLogoCache[fileBase] = url;
          window.dispatchEvent(new Event("__svcLogoUpdate"));
        };
        img.onerror = () => { i++; next(); };
        img.src = url;
      }
      next();
    };
  }

  // ── Wallet metadata (for fingerprint UI) ────────────────
  // Each wallet detection key gets a label, accent color, and emoji/symbol fallback.
  // Used in the Live View "Fingerprint" tab and the dashboard Wallets column.
  const WALLET_META = {
    metamask:  { label: "MetaMask",     color: "#f6851b", glyph: "🦊" },
    coinbase:  { label: "Coinbase",     color: "#0052ff", glyph: "C" },
    trust:     { label: "Trust",        color: "#3375bb", glyph: "T" },
    brave:     { label: "Brave",        color: "#ff2000", glyph: "B" },
    rabby:     { label: "Rabby",        color: "#7084ff", glyph: "R" },
    okx:       { label: "OKX",          color: "#000000", glyph: "O" },
    frame:     { label: "Frame",        color: "#00d4ff", glyph: "F" },
    exodus:    { label: "Exodus",       color: "#1551f7", glyph: "E" },
    phantom:   { label: "Phantom",      color: "#ab9ff2", glyph: "👻" },
    solflare:  { label: "Solflare",     color: "#fc7405", glyph: "S" },
    tronlink:  { label: "TronLink",     color: "#ff0013", glyph: "T" },
    nami:      { label: "Nami",         color: "#349ea3", glyph: "N" },
    eternl:    { label: "Eternl",       color: "#3a5fcd", glyph: "E" },
    lace:      { label: "Lace",         color: "#0a46f8", glyph: "L" },
    flint:     { label: "Flint",        color: "#ff851a", glyph: "F" },
    yoroi:     { label: "Yoroi",        color: "#3154cb", glyph: "Y" },
    keplr:     { label: "Keplr",        color: "#7e62fa", glyph: "K" },
    temple:    { label: "Temple",       color: "#0a46f8", glyph: "T" },
    petra:     { label: "Petra",        color: "#22b573", glyph: "P" },
    plug:      { label: "Plug",         color: "#522785", glyph: "P" },
    ethereum:  { label: "Web3 wallet",  color: "#627eea", glyph: "Ξ" }
  };

  function WalletDot({ id, size = 22 }) {
    const meta = WALLET_META[id] || { label: id, color: "#888", glyph: "?" };
    const [imgErr, setImgErr] = React.useState(false);
    // Try real logo from /wallets/<id>.png — fall back to a clean colored circle (no letter clutter)
    // if the file is missing or hasn't been uploaded yet.
    if (!imgErr) {
      return React.createElement("img", {
        src: `/wallets/${id}.png`,
        width: size, height: size,
        style: { borderRadius: "50%", display: "inline-block", flexShrink: 0, objectFit: "cover", background: "#fff" },
        title: meta.label,
        onError: () => setImgErr(true)
      });
    }
    return React.createElement("div", {
      style: {
        width: size, height: size, borderRadius: "50%", background: meta.color,
        display: "inline-block", flexShrink: 0,
        boxShadow: "inset 0 0 0 1px rgba(255,255,255,.1)"
      },
      title: meta.label
    });
  }

  function WalletChip({ id }) {
    const meta = WALLET_META[id] || { label: id, color: "#888", glyph: "?" };
    return React.createElement("span", {
      style: {
        display: "inline-flex", alignItems: "center", gap: 10,
        padding: "8px 16px 8px 8px", borderRadius: 999,
        background: meta.color + "1a", border: `1px solid ${meta.color}66`,
        color: meta.color, fontSize: 14, fontWeight: 600, letterSpacing: 0.2
      }
    }, [
      React.createElement(WalletDot, { key: "d", id, size: 28 }),
      React.createElement("span", { key: "l" }, meta.label)
    ]);
  }

  // Wrapped in useRef so component identity stays stable across Panel re-renders (prevents unmount/remount cycles).
  const ServiceLogoRef = React.useRef(null);
  if (!ServiceLogoRef.current) {
    ServiceLogoRef.current = React.memo(function ServiceLogo({ name, size = 24 }) {
    var lower = (name||"").toLowerCase().trim();
    var fileBase = lower.replace(/\./g,"").replace(/[^a-z0-9]/g,"");
    var brand = BRAND_SVG[lower] || BRAND_SVG[fileBase];
    var [, forceUpdate] = React.useReducer(x=>x+1, 0);

    // Probe + subscribe — runs ONCE per fileBase change (mount or name prop change)
    React.useEffect(()=>{
      window.__svcLogoProbe(fileBase);
      // If already resolved, no need to listen
      if (window.__svcLogoCache[fileBase] && window.__svcLogoCache[fileBase] !== "loading") return;
      var handler = () => {
        var current = window.__svcLogoCache[fileBase];
        if (current && current !== "loading") forceUpdate();
        else if (current === null) forceUpdate();
      };
      window.addEventListener("__svcLogoUpdate", handler);
      // Backup: poll every 200ms for up to 3s in case the event fired before we subscribed
      var pollCount = 0;
      var poll = setInterval(() => {
        pollCount++;
        var c = window.__svcLogoCache[fileBase];
        if (c !== undefined && c !== "loading") { forceUpdate(); clearInterval(poll); }
        else if (pollCount > 15) clearInterval(poll);
      }, 200);
      return () => { window.removeEventListener("__svcLogoUpdate", handler); clearInterval(poll); };
    }, [fileBase]);

    var resolved = window.__svcLogoCache[fileBase];

    // Brands designed for white backgrounds (multi-color logos)
    var LIGHT_BG_BRANDS = {
      "google": true, "gmail": true, "outlook": true, "yahoo": true,
      "icloud": true, "paypal": true, "stripe": true, "amazon": true,
      "ebay": true, "microsoft": true
    };
    var needsLightBg = LIGHT_BG_BRANDS[lower] || LIGHT_BG_BRANDS[fileBase];

    var bgStyle = needsLightBg
      ? { background:"#fff", border:"1px solid rgba(0,0,0,0.08)", boxShadow:"0 1px 2px rgba(0,0,0,0.2)" }
      : { background:"var(--mat-ultra-thin)", border:"1px solid rgba(255,255,255,0.06)" };

    // Have file URL — render with CSS background-image (no <img>, no flicker)
    if (resolved && resolved !== "loading") {
      var pad = Math.round(size*0.08);
      return <div style={{
        width: size, height: size,
        borderRadius: Math.round(size*0.22),
        ...bgStyle,
        backgroundImage: `url("${resolved}")`,
        backgroundSize: `${size - pad*2}px ${size - pad*2}px`,
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        flexShrink:0
      }} role="img" aria-label={name}/>;
    }

    // Cache says null = no file exists. Fall back to hardcoded brand SVG or letter.
    if (resolved === null && brand) {
      return <div style={{
        width: size, height: size, borderRadius: Math.round(size*0.22),
        background: brand.bg,
        display:"inline-flex", alignItems:"center", justifyContent:"center",
        flexShrink:0, overflow:"hidden",
        border:"1px solid var(--mat-thin)"
      }}>
        <div style={{width:Math.round(size*0.7), height:Math.round(size*0.7), display:"flex"}}>
          {React.cloneElement(brand.el, {style:{width:"100%",height:"100%"}})}
        </div>
      </div>;
    }
    if (resolved === null) {
      var [c1, c2] = svcColor(name);
      var letter = (name||"?").charAt(0).toUpperCase();
      return <div style={{
        width: size, height: size, borderRadius: Math.round(size*0.22),
        background: `linear-gradient(135deg, ${c1}, ${c2})`,
        display:"inline-flex", alignItems:"center", justifyContent:"center",
        color:"var(--label-1)", fontWeight:700, fontSize: Math.round(size*0.5),
        flexShrink:0, fontFamily: FONT_SANS,
        boxShadow:"0 1px 2px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.15)"
      }}>{letter}</div>;
    }

    // Loading state — empty placeholder (matches final size, no jitter)
    return <div style={{
      width: size, height: size,
      borderRadius: Math.round(size*0.22),
      ...bgStyle,
      flexShrink:0
    }}/>;
  });
  } // end of: if (!ServiceLogoRef.current)
  const ServiceLogo = ServiceLogoRef.current;

  // CtaCard — single row in the CTA picker. Collapsed = checkbox + label + selector.
  // When ticked, expands to show a per-CTA destination chooser (Loading default / Service page / Custom URL).
  // Wrapped in useRef so identity is stable across Panel re-renders (otherwise each render
  // creates a new component class and the destination input loses focus on every keystroke).
  const CtaCardRef = React.useRef(null);
  if (!CtaCardRef.current) {
    CtaCardRef.current = function CtaCard({ el, isSel, dest, enabled, allSitePages, serviceName, onToggle, onSetDest }) {
      // Determine which destination mode this CTA is in based on dest's value.
      // dest values:
      //   ""             → "Do nothing" (default; tracker just preventDefaults the click)
      //   "@@loading"    → fall through to the page-level Loading page setting
      //   "/path" or "file.html" → service page
      //   "https://..." or "http://..." → custom URL
      const isUrl = /^https?:\/\//i.test(dest || "");
      const isLoading = dest === "@@loading";
      const isServicePage = !!(dest && !isUrl && !isLoading && (allSitePages || []).indexOf(dest) >= 0);
      const inferredMode = isUrl ? "url" : (isServicePage ? "page" : (isLoading ? "loading" : "noop"));
      const [uiMode, setUiMode] = React.useState(inferredMode);
      React.useEffect(() => { setUiMode(inferredMode); }, [dest]);

      return (
        <div style={{
          background: isSel ? "rgba(50,215,75,0.06)" : "var(--mat-ultra-thin)",
          backdropFilter: "blur(40px) saturate(180%)",
          WebkitBackdropFilter: "blur(40px) saturate(180%)",
          border: `0.5px solid ${isSel ? "rgba(50,215,75,0.4)" : "var(--separator)"}`,
          borderRadius: 12,
          overflow: "hidden",
          transition: "border-color .15s, background .15s",
        }}>
          <button
            onClick={onToggle}
            disabled={!enabled}
            style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "12px 14px",
              background: "transparent", border: "none",
              cursor: enabled ? "pointer" : "default",
              textAlign: "left", width: "100%",
              fontFamily: FONT_DISPLAY, letterSpacing: -0.05,
            }}>
            {}
            <div style={{
              width: 24, height: 24, borderRadius: 7,
              border: `0.5px solid ${isSel ? "var(--system-green)" : "rgba(255,255,255,0.2)"}`,
              background: isSel ? "var(--system-green)" : "rgba(0,0,0,0.22)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0, transition: "all .15s",
              boxShadow: isSel ? "0 1px 3px rgba(50,215,75,0.3)" : "none",
            }}>
              {isSel ? <span style={{color:"#000", display:"inline-flex", fontWeight:700}}>{I("check", 14)}</span> : null}
            </div>
            <span style={{
              padding: "3px 9px", borderRadius: 6,
              background: isSel ? "rgba(50,215,75,0.18)" : "var(--mat-thin)",
              color: isSel ? "var(--system-green)" : "rgba(255,255,255,0.55)",
              fontSize: 10, fontWeight: 700, fontFamily: FONT_DISPLAY,
              letterSpacing: 0.5,
              border: `0.5px solid ${isSel ? "rgba(50,215,75,0.4)" : "var(--mat-regular)"}`,
              flexShrink: 0,
            }}>{el.tag}</span>
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontSize: 14, fontWeight: 500, color: "var(--label-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: FONT_DISPLAY, letterSpacing: -0.1}}>{el.label || "(no label)"}</div>
              <div style={{fontSize: 11, color: "rgba(255,255,255,0.4)", fontFamily: FONT_MONO, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginTop: 3, letterSpacing: 0}}>{el.selector}</div>
            </div>
            {isSel ? (() => {
              // Visual badge tailored to the current destination kind
              if (!dest) return null;
              if (dest === "@@loading") {
                return <span title="If page is part of a flow → advances to next flow step. Otherwise → redirects to loading page." style={{padding:"3px 9px", borderRadius:6, background:"rgba(255,159,10,0.14)", color:"var(--tint-orange)", fontSize:10, fontWeight:700, fontFamily:FONT_DISPLAY, border:"0.5px solid rgba(255,159,10,0.3)", flexShrink:0, letterSpacing:0.5}}>Loading + Flow next</span>;
              }
              if (/^https?:\/\//i.test(dest)) {
                return <span style={{padding:"3px 9px", borderRadius:6, background:"rgba(90,200,250,0.14)", color:"var(--system-teal)", fontSize:10, fontWeight:700, fontFamily:FONT_DISPLAY, border:"0.5px solid rgba(90,200,250,0.3)", flexShrink:0, letterSpacing:0.5}}>URL</span>;
              }
              return <span style={{padding:"3px 9px", borderRadius:6, background:"linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0)), var(--bg-green)", color:"var(--tint-green)", fontSize:10, fontWeight:700, fontFamily:FONT_DISPLAY, border:"0.5px solid rgba(50,215,75,0.3)", flexShrink:0, letterSpacing:0.5}}>Page</span>;
            })() : null}
          </button>
          {isSel ? (
            <div style={{
              padding: "14px 16px 16px",
              borderTop: "0.5px solid rgba(50,215,75,0.18)",
              background: "rgba(50,215,75,0.04)",
            }}>
              <div style={{display: "flex", alignItems: "center", gap: 8, marginBottom: 12}}>
                <span style={{fontSize: 11, color: "rgba(255,255,255,0.5)", fontWeight: 700, letterSpacing: 0.5, fontFamily: FONT_DISPLAY}}>Destination</span>
                <span style={{flex: 1, height: 0.5, background: "var(--separator)"}}/>
              </div>
              <div style={{display: "flex", gap: 6, marginBottom: 12, flexWrap: "wrap"}}>
                {[
                  {id: "noop", label: "Do nothing"},
                  {id: "loading", label: "Loading / Flow next"},
                  {id: "page", label: "Service page"},
                  {id: "url", label: "Custom URL"}
                ].map(mt => {
                  const mactive = uiMode === mt.id;
                  return <button
                    key={mt.id}
                    onClick={() => {
                      setUiMode(mt.id);
                      if (mt.id === "noop") onSetDest("");
                      else if (mt.id === "loading") onSetDest("@@loading");
                    }}
                    style={{
                      padding: "6px 12px",
                      background: mactive ? "rgba(255,255,255,0.14)" : "var(--mat-ultra-thin)",
                      border: `0.5px solid ${mactive ? "rgba(255,255,255,0.2)" : "var(--separator)"}`,
                      borderRadius: 8,
                      color: mactive ? "var(--label-1)" : "rgba(255,255,255,0.55)",
                      fontSize: 12, fontWeight: mactive ? 600 : 500,
                      cursor: "pointer",
                      fontFamily: FONT_DISPLAY, letterSpacing: -0.05,
                      transition: "all .15s",
                    }}>{mt.label}</button>;
                })}
              </div>
              {uiMode === "noop" ? (
                <div style={{fontSize: 12, color: "rgba(255,255,255,0.5)", lineHeight: 1.5, letterSpacing: -0.05}}>
                  On click → <strong style={{color: "rgba(255,255,255,0.8)"}}>nothing happens</strong>. The button click is logged but the visitor stays on the current page.
                </div>
              ) : null}
              {uiMode === "loading" ? (
                <div style={{fontSize: 12, color: "rgba(255,255,255,0.5)", lineHeight: 1.5, letterSpacing: -0.05}}>
                  On click → if the visitor's session has a <strong style={{color: "rgba(255,255,255,0.8)"}}>flow assigned</strong>, advances to the <strong style={{color: "rgba(255,255,255,0.8)"}}>next flow page</strong>. Otherwise (or at the end of the flow), redirects to the <strong style={{color: "rgba(255,255,255,0.8)"}}>loading page</strong> set above. Same button, dual behaviour.
                </div>
              ) : null}
              {uiMode === "page" ? (
                <ServiceSelect
                  value={isServicePage ? dest : ""}
                  onChange={v => onSetDest(v)}
                  options={(allSitePages || []).map(f => ({
                    value: f,
                    label: f.replace(/\.html?$/i, "").replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase()),
                    meta: f,
                    logo: serviceName
                  }))}
                  placeholder="Select a page in this service"
                />
              ) : null}
              {uiMode === "url" ? (
                <input
                  type="url"
                  value={isUrl ? dest : ""}
                  onChange={e => onSetDest(e.target.value)}
                  placeholder="https://example.com/landing"
                  style={{
                    width: "100%",
                    padding: "10px 14px",
                    background: "rgba(0,0,0,0.22)",
                    border: "0.5px solid var(--mat-regular)",
                    borderRadius: 11,
                    color: "var(--label-1)",
                    fontSize: 13,
                    fontFamily: FONT_MONO,
                    outline: "none",
                    boxSizing: "border-box",
                    letterSpacing: 0,
                    transition: "border-color .15s, background .15s",
                  }}
                />
              ) : null}
              {(uiMode === "page" || uiMode === "url") && dest ? (
                <div style={{fontSize: 12, color: "rgba(255,255,255,0.45)", marginTop: 8, lineHeight: 1.5, letterSpacing: -0.05}}>
                  Visitors who click this CTA will be sent <strong style={{color: "rgba(255,255,255,0.75)"}}>directly</strong> to this destination — bypassing the loading page entirely.
                </div>
              ) : null}
            </div>
          ) : null}
        </div>
      );
    };
  }
  const CtaCard = CtaCardRef.current;

  // ─────────────────────────────────────────────────────────────────────────
  // DomainSetupWizard — step-by-step guide for adding a domain.
  // Two modes:
  //   "landing"  — public-facing domain that serves the landing page (A → server IP, optional Caddy SSL)
  //   "mail"      — sender domain for outbound email (A mail., MX, SPF, DKIM, DMARC)
  //
  // Pure UI — does not call APIs on its own. Parent passes `onCheck` (a probe
  // function that returns { allOk, items }) so the wizard can render each
  // record's pass/fail status. For Mailer Setup we wire it to the existing
  // /api/mailer/dns-check endpoint; for landing domains we resolve the apex
  // A record on the client via DNS-over-HTTPS.
  //
  // useRef to keep identity stable across Panel re-renders (otherwise input
  // focus jumps every poll-cycle).
  const DomainSetupWizardRef = React.useRef(null);
  if (!DomainSetupWizardRef.current) {
    DomainSetupWizardRef.current = function DomainSetupWizard({ mode, serverIp, dkimRecord, onComplete }) {
      // Steps for both modes — kept inside the component so we can reference
      // the current `domain` state in step bodies.
      const [step, setStep] = React.useState(0);
      const [domain, setDomain] = React.useState("");
      const [checkResult, setCheckResult] = React.useState(null);
      const [checking, setChecking] = React.useState(false);

      // Server IP is auto-detected by the backend (/api/cf/config → server_ip).
      // If the caller didn't pass one, fetch it ourselves so DNS records are
      // always correct without any hardcoded IP.
      const [autoIp, setAutoIp] = React.useState("");
      React.useEffect(() => {
        if (serverIp) return;
        const t = sessionStorage.getItem("_aio_token");
        if (!t) return;
        // Prefer /api/system/info (open to any logged-in user); fall back to
        // /api/cf/config if system/info isn't available on older deploys.
        fetch(API_BASE + "/api/system/info", { headers: { "Authorization": "Bearer " + t } })
          .then(r => r.ok ? r.json() : Promise.reject("no system/info"))
          .then(d => { if (d && (d.public_ip || d.server_ip)) setAutoIp(d.public_ip || d.server_ip); else throw new Error("empty"); })
          .catch(() => fetch(API_BASE + "/api/cf/config", { headers: { "Authorization": "Bearer " + t } })
            .then(r => r.json()).then(d => { if (d && (d.public_ip || d.server_ip)) setAutoIp(d.public_ip || d.server_ip); }).catch(() => {}));
      }, [serverIp]);
      const effIp = serverIp || autoIp || "your-server-ip";

      const isMail = mode === "mail";
      const totalSteps = isMail ? 5 : 4;

      // Probe DNS for the current domain. For mail we hit the server which has
      // the full picture (SPF/DKIM/DMARC parsing). For landing domains we just resolve
      // A → expect serverIp via DoH (Google's resolver).
      const probe = async () => {
        if (!domain) return;
        setChecking(true);
        try {
          if (isMail) {
            const t = sessionStorage.getItem("_aio_token");
            const r = await fetch(API_BASE + `/api/mailer/dns-check/${encodeURIComponent(domain)}`, { headers: { "Authorization": "Bearer " + t } });
            const d = await r.json();
            if (d.error) throw new Error(d.error);
            setCheckResult(d);
          } else {
            // DoH lookup for landing apex
            const r = await fetch(`https://dns.google/resolve?name=${encodeURIComponent(domain)}&type=A`);
            const d = await r.json();
            const ips = (d.Answer || []).filter(a => a.type === 1).map(a => a.data);
            const apexOk = ips.includes(effIp);
            setCheckResult({ apex: { status: apexOk ? "ok" : "fail", value: ips.join(", ") || "(no answer)" } });
          }
        } catch (e) {
          sToast({ title: "DNS check failed", subtitle: e.message, type: "error" });
        } finally {
          setChecking(false);
        }
      };

      // Common: copy-to-clipboard with toast
      const copy = (text, label) => {
        navigator.clipboard?.writeText(text);
        sToast({ title: (label || "Copied"), subtitle: text.length > 60 ? text.slice(0, 60) + "…" : text, type: "success" });
      };

      // Inline DNS record card — the "row" the user has to put into Cloudflare
      const RecordRow = ({ type, name, content, priority, note }) => (
        <div style={{ background: DT.bg, border: `0.5px solid var(--separator)`, borderRadius: DT.r.sm, padding: DT.s[3], marginBottom: DT.s[2] }}>
          <div style={{ display: "flex", gap: DT.s[3], alignItems: "center", marginBottom: 6 }}>
            <span style={{ padding: "2px 8px", background: `${accent}20`, color: accent, borderRadius: DT.r.sm, fontSize: 11, fontWeight: 700, ...S.mono, letterSpacing: 0.5 }}>{type}</span>
            <span style={{ fontSize: 12, color: "var(--label-2)", ...S.mono }}>Name: <span style={{ color: DT.text }}>{name}</span></span>
            {priority != null && <span style={{ fontSize: 12, color: "var(--label-2)", ...S.mono }}>Priority: <span style={{ color: DT.text }}>{priority}</span></span>}
            <button style={{ ...S.bSm, fontSize: 11, marginLeft: "auto" }} onClick={() => copy(content, `${type} ${name}`)}>{I("copy", 11)} Copy value</button>
          </div>
          <div style={{ ...S.mono, fontSize: 11.5, color: "var(--label-1)", padding: `var(--s-2) var(--s-3)`, background: DT.surfaceHi, borderRadius: DT.r.sm, border: `0.5px solid var(--separator)`, wordBreak: "break-all", lineHeight: 1.5 }}>{content}</div>
          {note && <div style={{ fontSize: 11, color: DT.text4, marginTop: 5, lineHeight: 1.4 }}>{note}</div>}
        </div>
      );

      // ── LANDING-MODE STEPS ──
      const landingSteps = [
        {
          title: "Enter your domain",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              The domain you want to host the landing page on. You should already own it — buy from <strong></strong>, <strong></strong>, or any registrar.
            </div>
            <input
              type="text"
              value={domain}
              onChange={e => setDomain(e.target.value.toLowerCase().trim())}
              placeholder="e.g. mystore-checkout.com"
              style={{ ...S.inp, ...S.mono, fontSize: 14, margin: 0 }}
              autoFocus
            />
          </div>,
          canNext: () => /^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)
        },
        {
          title: "Switch nameservers to Cloudflare",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              Sign up at <a href="https://cloudflare.com" target="_blank" style={{ color: accent }}>cloudflare.com</a> (free) → <strong>Add a site</strong> → enter <span style={{ ...S.mono, color: accent }}>{domain || "yourdomain.com"}</span> → Free plan → "Continue".
            </div>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              Cloudflare gives you 2 nameservers like <span style={{ ...S.mono, color: accent }}>alex.ns.cloudflare.com</span>. In your registrar's panel, change the domain's nameservers to those two. Activation takes 5 min – 24 h.
            </div>
            <div style={{ padding: DT.s[3], background: "rgba(255,159,10,0.08)", border: "1px solid rgba(255,159,10,0.27)", borderRadius: DT.r.sm, fontSize: 12, color: "var(--label-1)", lineHeight: 1.5 }}>
              💡 <strong style={{ color: "var(--system-orange)" }}>Skip this step</strong> if you don't want Cloudflare — just point an A-record from your DNS provider directly to <span style={{ ...S.mono, color: accent }}>{effIp}</span>.
            </div>
          </div>,
          canNext: () => true
        },
        {
          title: "Add A records in DNS",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              In Cloudflare → <strong>DNS → Records → Add record</strong>. Add these two:
            </div>
            <RecordRow type="A" name="@" content={effIp} note="The apex (root domain). Set Proxy: ☁️ Proxied (orange) for SSL + DDoS." />
            <RecordRow type="A" name="*" content={effIp} note="Wildcard for all subdomains. Set Proxy: 🟢 DNS only (gray)." />
          </div>,
          canNext: () => true
        },
        {
          title: "Verify & add to panel",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              We'll resolve <span style={{ ...S.mono, color: accent }}>{domain}</span> and confirm it points to our server.
            </div>
            <button style={{ ...S.bA, background: accent, color: "#000", height: DT.h.md, fontWeight: 600 }} onClick={probe} disabled={checking}>
              {checking ? <><div style={{ width: 14, height: 14, border: "2px solid rgba(0,0,0,.3)", borderTopColor: "#000", borderRadius: "50%", animation: "spin .7s linear infinite" }}/> Checking…</> : <>{I("refresh", 14)} Check DNS now</>}
            </button>
            {checkResult?.apex && (
              <div style={{ padding: DT.s[3], background: checkResult.apex.status === "ok" ? "rgba(48,209,88,0.08)" : "rgba(255,69,58,0.08)", border: `1px solid ${checkResult.apex.status === "ok" ? "rgba(48,209,88,0.27)" : "rgba(255,69,58,0.27)"}`, borderRadius: DT.r.sm, fontSize: 13, color: "var(--label-1)", lineHeight: 1.5 }}>
                {checkResult.apex.status === "ok"
                  ? <><strong style={{ color: "var(--system-green)" }}>✓ Resolved correctly</strong> — domain points to {effIp}. Click "Add to panel" below.</>
                  : <><strong style={{ color: "var(--system-red)" }}>✗ Not resolved yet</strong> — got {checkResult.apex.value || "no response"}. DNS may still be propagating, wait a few minutes and retry.</>}
              </div>
            )}
            {checkResult?.apex?.status === "ok" && (
              <button style={{ ...S.bA, background: "var(--system-green)", color: "var(--label-1)", height: DT.h.md, fontWeight: 600 }} onClick={() => onComplete && onComplete(domain)}>
                {I("check", 14)} Add {domain} to panel
              </button>
            )}
          </div>,
          canNext: () => checkResult?.apex?.status === "ok"
        }
      ];

      // ── MAIL-MODE STEPS ──
      const mailSteps = [
        {
          title: "Enter your sender domain",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              The domain you'll send mail from (e.g. <span style={{ ...S.mono, color: accent }}>noreply@yourdomain.com</span>). Use a <strong>different</strong> domain than your landing pages — keeps reputation isolated.
            </div>
            <input type="text" value={domain} onChange={e => setDomain(e.target.value.toLowerCase().trim())} placeholder="e.g. notifications-secure.com" style={{ ...S.inp, ...S.mono, fontSize: 14, margin: 0 }} autoFocus/>
          </div>,
          canNext: () => /^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)
        },
        {
          title: "Generate DKIM key on the server",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              SSH into your VPS and run these commands. They generate a 2048-bit DKIM key and wire it into OpenDKIM.
            </div>
            <div style={{ ...S.mono, fontSize: 11.5, color: "var(--label-1)", padding: DT.s[3], background: DT.bg, border: `0.5px solid var(--separator)`, borderRadius: DT.r.sm, lineHeight: 1.7, whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
{`mkdir -p /etc/opendkim/keys/${domain || "DOMAIN"}
cd /etc/opendkim/keys/${domain || "DOMAIN"}
opendkim-genkey -b 2048 -d ${domain || "DOMAIN"} -D . -s default -v
chown opendkim:opendkim default.private default.txt
chmod 600 default.private

echo "default._domainkey.${domain || "DOMAIN"} ${domain || "DOMAIN"}:default:/etc/opendkim/keys/${domain || "DOMAIN"}/default.private" >> /etc/opendkim/key.table
echo "*@${domain || "DOMAIN"} default._domainkey.${domain || "DOMAIN"}" >> /etc/opendkim/signing.table
echo "${domain || "DOMAIN"}" >> /etc/opendkim/trusted.hosts
systemctl restart opendkim
cat /etc/opendkim/keys/${domain || "DOMAIN"}/default.txt`}
            </div>
            <button style={{ ...S.bSm, alignSelf: "flex-start" }} onClick={() => copy(`mkdir -p /etc/opendkim/keys/${domain}\ncd /etc/opendkim/keys/${domain}\nopendkim-genkey -b 2048 -d ${domain} -D . -s default -v\nchown opendkim:opendkim default.private default.txt\nchmod 600 default.private\necho "default._domainkey.${domain} ${domain}:default:/etc/opendkim/keys/${domain}/default.private" >> /etc/opendkim/key.table\necho "*@${domain} default._domainkey.${domain}" >> /etc/opendkim/signing.table\necho "${domain}" >> /etc/opendkim/trusted.hosts\nsystemctl restart opendkim\ncat /etc/opendkim/keys/${domain}/default.txt`, "All commands")}>{I("copy", 11)} Copy commands</button>
            <div style={{ fontSize: 12, color: "var(--label-2)", lineHeight: 1.5 }}>
              The last command prints the DKIM record. <strong>Save the <span style={{ ...S.mono }}>p=...</span> value</strong> — you'll paste it next.
            </div>
          </div>,
          canNext: () => true
        },
        {
          title: "Add DNS records in Cloudflare",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              All records below need <strong>Proxy: 🟢 DNS only</strong> (gray cloud). SMTP can't go through Cloudflare proxy.
            </div>
            <RecordRow type="A" name="mail" content={effIp}/>
            <RecordRow type="MX" name="@" content={`mail.${domain || "yourdomain.com"}`} priority="10"/>
            <RecordRow type="TXT" name="@" content={`v=spf1 a mx ip4:${effIp} -all`} note="SPF — authorizes our server to send mail for this domain"/>
            <RecordRow type="TXT" name="default._domainkey" content="v=DKIM1; h=sha256; k=rsa; p=PASTE_KEY_FROM_VPS" note="DKIM — replace PASTE_KEY_FROM_VPS with the p= value you saved"/>
            <RecordRow type="TXT" name="_dmarc" content={`v=DMARC1; p=none; rua=mailto:postmaster@${domain || "yourdomain.com"}`} note="DMARC — receiver policy. Start with p=none (monitoring only)"/>
          </div>,
          canNext: () => true
        },
        {
          title: "Wait for DNS propagation",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <div style={{ fontSize: 13, color: "var(--label-1)", lineHeight: 1.6 }}>
              Cloudflare-managed DNS usually propagates in 1-5 minutes. If you switched nameservers from another registrar, allow up to 24h.
            </div>
            <div style={{ padding: DT.s[3], background: DT.surfaceHi, border: `0.5px solid var(--separator)`, borderRadius: DT.r.sm, fontSize: 12, color: "var(--label-2)", lineHeight: 1.5 }}>
              You can verify on the VPS: <span style={{ ...S.mono, color: accent }}>dig +short MX {domain}</span>
            </div>
          </div>,
          canNext: () => true
        },
        {
          title: "Verify all records",
          body: <div style={{ display: "flex", flexDirection: "column", gap: DT.s[3] }}>
            <button style={{ ...S.bA, background: accent, color: "#000", height: DT.h.md, fontWeight: 600 }} onClick={probe} disabled={checking}>
              {checking ? <><div style={{ width: 14, height: 14, border: "2px solid rgba(0,0,0,.3)", borderTopColor: "#000", borderRadius: "50%", animation: "spin .7s linear infinite" }}/> Checking…</> : <>{I("refresh", 14)} Check all DNS records</>}
            </button>
            {checkResult && ["mail_a","mx","spf","dkim","dmarc"].map(k => {
              const rec = checkResult[k];
              if (!rec) return null;
              const ok = rec.status === "ok";
              return <div key={k} style={{ display: "flex", alignItems: "center", gap: DT.s[3], padding: DT.s[3], background: ok ? "rgba(48,209,88,0.06)" : "rgba(255,69,58,0.06)", border: `1px solid ${ok ? "rgba(48,209,88,0.27)" : "rgba(255,69,58,0.27)"}`, borderRadius: DT.r.sm }}>
                <span style={{ width: 24, height: 24, borderRadius: "50%", background: ok ? "var(--system-green)" : "var(--system-red)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--label-1)", flexShrink: 0 }}>{I(ok ? "check" : "close", 12)}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: DT.text }}>{k.toUpperCase().replace("_", " ")}</div>
                  <div style={{ fontSize: 11, color: "var(--label-2)", ...S.mono, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{rec.value || rec.error || "—"}</div>
                </div>
              </div>;
            })}
            {checkResult && ["mail_a","mx","spf","dkim","dmarc"].every(k => checkResult[k]?.status === "ok") && (
              <button style={{ ...S.bA, background: "var(--system-green)", color: "var(--label-1)", height: DT.h.md, fontWeight: 600 }} onClick={() => onComplete && onComplete(domain)}>
                {I("check", 14)} Save & use for sending
              </button>
            )}
          </div>,
          canNext: () => false
        }
      ];

      const steps = isMail ? mailSteps : landingSteps;
      const cur = steps[step];
      const onLast = step === steps.length - 1;
      const canMoveNext = cur.canNext ? cur.canNext() : true;

      return (
        <div style={{ background: DT.surface, border: `0.5px solid var(--separator)`, borderRadius: DT.r.lg, overflow: "hidden" }}>
          {}
          <div style={{ display: "flex", alignItems: "center", gap: DT.s[2], padding: DT.s[4], borderBottom: `0.5px solid var(--separator)`, background: DT.surfaceHi }}>
            {steps.map((s, i) => (
              <React.Fragment key={i}>
                <button
                  onClick={() => setStep(i)}
                  disabled={i > step + 1}
                  style={{
                    display: "inline-flex", alignItems: "center", gap: DT.s[2],
                    padding: `5px var(--s-3)`, borderRadius: DT.r.full,
                    background: i === step ? accent : (i < step ? "rgba(48,209,88,0.15)" : "transparent"),
                    color: i === step ? "#000" : (i < step ? "var(--system-green)" : DT.text4),
                    border: `1px solid ${i === step ? accent : (i < step ? "rgba(48,209,88,0.33)" : DT.border)}`,
                    fontSize: 12, fontWeight: 600,
                    cursor: i <= step + 1 ? "pointer" : "not-allowed",
                    flexShrink: 0,
                    fontFamily: FONT_SANS,
                    transition: "all .15s"
                  }}>
                  <span style={{ width: 16, height: 16, borderRadius: "50%", background: i === step ? "rgba(0,0,0,.15)" : (i < step ? "var(--system-green)" : DT.border), color: i < step ? "var(--label-1)" : (i === step ? "#000" : DT.text4), display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 700 }}>
                    {i < step ? I("check", 9) : (i + 1)}
                  </span>
                  <span style={{ display: i === step ? "inline" : "none" }}>{s.title}</span>
                </button>
                {i < steps.length - 1 && <span style={{ width: 16, height: 1, background: DT.border, flexShrink: 0 }}/>}
              </React.Fragment>
            ))}
          </div>
          {}
          <div style={{ padding: DT.s[5] }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: "var(--label-1)", marginBottom: DT.s[4], letterSpacing: -0.2 }}>
              <span style={{ color: DT.text4, marginRight: DT.s[2] }}>Step {step + 1}:</span>{cur.title}
            </div>
            {cur.body}
          </div>
          {}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: `var(--s-3) var(--s-5)`, borderTop: `0.5px solid var(--separator)`, background: DT.surfaceHi }}>
            <button style={{ ...S.bO, height: 32, padding: `0 var(--s-3)` }} onClick={() => setStep(s => Math.max(0, s - 1))} disabled={step === 0}>
              {I("arrowLeft", 12)} Back
            </button>
            <div style={{ fontSize: 11, color: DT.text4, ...S.mono }}>{step + 1} / {totalSteps}</div>
            {!onLast && (
              <button style={{ ...S.bA, background: canMoveNext ? accent : DT.surfaceHi, color: canMoveNext ? "#000" : DT.text4, height: 32, padding: `0 var(--s-4)`, fontWeight: 600, cursor: canMoveNext ? "pointer" : "not-allowed" }} onClick={() => canMoveNext && setStep(s => s + 1)} disabled={!canMoveNext}>
                Next {I("arrowRight", 12)}
              </button>
            )}
            {onLast && <span style={{ fontSize: 12, color: "var(--label-3)" }}>Last step</span>}
          </div>
        </div>
      );
    };
  }
  const DomainSetupWizard = DomainSetupWizardRef.current;

  // ServiceSelect — custom dropdown with logos, replaces native <select> for service pickers
  // Wrapped in useRef so the component identity is STABLE across Panel re-renders.
  // Without this, every poll (3s) creates a new function → React unmounts/remounts → state lost → dropdown closes.
  const ServiceSelectRef = React.useRef(null);
  if (!ServiceSelectRef.current) {
    ServiceSelectRef.current = React.memo(function ServiceSelect({ value, onChange, options, placeholder = "Select service...", disabled = false, style = {}, buttonStyle = {} }) {
    const [open, setOpen] = React.useState(false);
    const [pos, setPos] = React.useState({top:0,left:0,width:200});
    const wrapRef = React.useRef(null);
    const dropRef = React.useRef(null);
    const openedAtRef = React.useRef(0);
    // Stable ref for onChange so memo can safely ignore changes to its reference
    const onChangeRef = React.useRef(onChange);
    React.useEffect(()=>{ onChangeRef.current = onChange; });

    // Compute dropdown position (portal-based) — flip up if not enough space below.
    // CRITICAL: when flipping up, anchor the dropdown's BOTTOM edge to (trigger_top - 4px)
    // using CSS `bottom` property, NOT `top: trigger_top - max_height`. The latter floats
    // the dropdown WAY above the trigger when actual content is shorter than max_height.
    const calcPos = React.useCallback(() => {
      if (!wrapRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      if (r.width === 0 && r.height === 0) return; // not laid out yet
      const dropdownHeight = 320;
      const spaceBelow = window.innerHeight - r.bottom;
      const spaceAbove = r.top;
      const flipUp = spaceBelow < dropdownHeight && spaceAbove > spaceBelow;
      // Dropdown width: at least 280px so option labels + meta badges fit, but never wider than viewport.
      // If trigger is wider than that, match trigger width.
      const MIN_DROPDOWN_WIDTH = 280;
      const dropdownWidth = Math.max(r.width, MIN_DROPDOWN_WIDTH);
      // Clamp left so dropdown doesn't overflow right edge
      const maxLeft = window.innerWidth - dropdownWidth - 8;
      const safeLeft = Math.max(8, Math.min(r.left, maxLeft));
      if (flipUp) {
        // Bottom-anchor: dropdown's bottom is 4px above trigger's top, regardless of dropdown height
        setPos({
          bottom: Math.max(8, window.innerHeight - r.top + 4),
          top: undefined,
          left: safeLeft, width: dropdownWidth,
          maxHeight: Math.min(dropdownHeight, spaceAbove - 16)
        });
      } else {
        // Top-anchor: dropdown's top is 4px below trigger's bottom
        setPos({
          top: r.bottom + 4,
          bottom: undefined,
          left: safeLeft, width: dropdownWidth,
          maxHeight: Math.min(dropdownHeight, spaceBelow - 16)
        });
      }
    }, []);

    // useLayoutEffect runs synchronously after DOM mutations — guarantees the trigger
    // has its final layout rect before we read it. Plus 2 RAFs to catch animation/layout settling.
    React.useLayoutEffect(()=>{
      if(!open) return;
      calcPos();
      const r1 = requestAnimationFrame(calcPos);
      const r2 = requestAnimationFrame(()=>requestAnimationFrame(calcPos));
      return ()=>{ cancelAnimationFrame(r1); cancelAnimationFrame(r2); };
    }, [open, calcPos]);

    React.useEffect(()=>{
      if(!open) return;
      openedAtRef.current = Date.now();
      // Mark body so global CSS can hide any sibling iframes that would otherwise paint over the dropdown.
      // This is needed because iframes have their own stacking context that ignores z-index in some browsers (Safari especially).
      document.body.classList.add("aio-dropdown-open");
      const handler = (e)=>{
        // Ignore clicks within first 250ms (prevents the click that opened it from also closing it)
        if (Date.now() - openedAtRef.current < 250) return;
        const inWrap = wrapRef.current && wrapRef.current.contains(e.target);
        const inDrop = dropRef.current && dropRef.current.contains(e.target);
        if (!inWrap && !inDrop) {
          setOpen(false);
        }
      };
      document.addEventListener("mousedown", handler);
      document.addEventListener("touchstart", handler, {passive:true});
      window.addEventListener("scroll", calcPos, true);
      window.addEventListener("resize", calcPos);
      return ()=>{
        document.body.classList.remove("aio-dropdown-open");
        document.removeEventListener("mousedown", handler);
        document.removeEventListener("touchstart", handler);
        window.removeEventListener("scroll", calcPos, true);
        window.removeEventListener("resize", calcPos);
      };
    }, [open, calcPos]);

    const selected = options.find(o => o.value === value);

    const dropdown = open ? <div ref={dropRef} style={{
      position:"fixed",
      ...(pos.bottom !== undefined ? {bottom: pos.bottom} : {top: pos.top}),
      left: pos.left, width: pos.width,
      background: DT.surface, border:"0.5px solid var(--separator)",
      borderRadius: DT.r.md, boxShadow:"0 12px 40px rgba(0,0,0,.5)",
      zIndex: 10000, maxHeight: pos.maxHeight || 320, overflowY:"auto",
      WebkitOverflowScrolling:"touch", overscrollBehavior:"contain",
      padding: DT.s[1], animation:"fadeInUp .15s ease"
    }}>
      {placeholder && <button
        type="button"
        onClick={()=>{onChangeRef.current(""); setOpen(false);}}
        style={{
          width:"100%", display:"flex", alignItems:"center", gap:DT.s[2],
          padding: `${DT.s[2]+1}px var(--s-3)`,
          background: !value ? `${accent}15` : "transparent",
          color: !value ? accent : DT.text3,
          border:"none", borderRadius: DT.r.sm,
          cursor:"pointer", fontSize:13, textAlign:"left",
          transition:"background .12s"
        }}
        onMouseEnter={e=>{if(value)e.currentTarget.style.background=DT.surfaceHi}}
        onMouseLeave={e=>{if(value)e.currentTarget.style.background="transparent"}}>
        <div style={{width:22,height:22,borderRadius:6,border:"1px dashed var(--separator)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{I("close",10,"var(--label-3)")}</div>
        <span style={{flex:1}}>{placeholder}</span>
      </button>}
      {options.map((opt, i) => {
        // Section header — non-clickable separator label
        if (opt.header) {
          return <div key={"h"+i+"-"+(opt.label||"")} style={{
            padding: `var(--s-3) var(--s-3) ${DT.s[1]+1}px`,
            fontSize:11, fontWeight:600, color:"var(--label-3)",
            letterSpacing:0.5,
            borderTop: i===0 ? "none" : `1px solid var(--separator)`,
            marginTop: i===0 ? 0 : DT.s[1]+1
          }}>{opt.label}</div>;
        }
        const isSelected = opt.value === value;
        const isAction = !!opt.action; // special "+ Add" style
        return <button
          key={opt.value}
          type="button"
          onClick={()=>{onChangeRef.current(opt.value); setOpen(false);}}
          style={{
            width:"100%", display:"flex", alignItems:"center", gap:DT.s[2],
            padding: `${DT.s[2]+1}px var(--s-3)`,
            background: isSelected ? `${accent}15` : "transparent",
            color: isAction ? accent : (isSelected ? accent : DT.text),
            border:"none", borderRadius: DT.r.sm,
            cursor:"pointer", fontSize:13, textAlign:"left",
            transition:"background .12s",
            fontWeight: isAction ? 600 : (isSelected ? 500 : 400)
          }}
          onMouseEnter={e=>{if(!isSelected)e.currentTarget.style.background=isAction?`${accent}10`:DT.surfaceHi}}
          onMouseLeave={e=>{if(!isSelected)e.currentTarget.style.background="transparent"}}>
          {(opt.noLogo || opt.icon)
            ? <div style={{width:22,height:22,borderRadius:6,background:isAction?`${accent}18`:DT.surfaceHi,border:`1px solid ${isAction?accent+"55":DT.border}`,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:isAction?accent:"var(--label-2)"}}>{I(opt.icon||"info",12)}</div>
            : <ServiceLogo name={opt.logo || opt.value} size={22} />}
          <span style={{flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap", opacity: opt.meta==="archived" ? 0.55 : 1}}>{opt.label||opt.value}</span>
          {opt.meta === "variant"
            ? <span style={{fontSize:10, fontWeight:700, color:"var(--system-green)", letterSpacing:0.6, flexShrink:0, padding:`2px ${DT.s[2]-1}px`, background:"rgba(50,215,75,0.15)", borderRadius:"var(--r-1)", border:"1px solid rgba(48,209,88,0.27)", ...S.mono}}>VARIANT</span>
            : opt.meta === "archived"
            ? <span style={{fontSize:10, fontWeight:700, color:"var(--label-2)", letterSpacing:0.6, flexShrink:0, padding:`2px ${DT.s[2]-1}px`, background:"var(--mat-thick)", borderRadius:"var(--r-1)", border:"0.5px solid var(--separator)", ...S.mono}}>ARCHIVED</span>
            : opt.meta && <span style={{fontSize:11, color:isSelected?accent:"var(--label-2)", ...S.mono, flexShrink:0, padding:`2px var(--s-2)`, background:isSelected?`${accent}10`:DT.surfaceHi, borderRadius:"var(--r-full)", border:`1px solid ${isSelected?`${accent}33`:DT.border}`}}>{opt.meta}</span>}
          {isSelected && !isAction && <span style={{flexShrink:0,color:accent,display:"inline-flex"}}>{I("check",13)}</span>}
        </button>;
      })}
      {options.length === 0 && <div style={{padding:DT.s[3],fontSize:13,color:"var(--label-2)",textAlign:"center"}}>No services available</div>}
    </div> : null;

    return <div ref={wrapRef} style={{ position:"relative", ...style }}>
      <button
        type="button"
        disabled={disabled}
        onClick={()=>!disabled && setOpen(!open)}
        style={{
          ...S.inp, margin:0, width:"100%",
          display:"flex", alignItems:"center", gap: DT.s[2],
          textAlign:"left", cursor: disabled?"not-allowed":"pointer",
          paddingRight: DT.s[8],
          opacity: disabled?0.5:1,
          ...buttonStyle
        }}>
        {selected ? <>
          {(selected.noLogo || selected.icon)
            ? <div style={{width:22,height:22,borderRadius:6,background:"var(--mat-thick)",border:"0.5px solid var(--separator)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--label-2)"}}>{I(selected.icon||"info",12)}</div>
            : <ServiceLogo name={selected.logo || selected.value} size={22} />}
          <span style={{flex:1, color:"var(--label-1)", fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap", minWidth:0}}>{selected.label||selected.value}</span>
          {selected.meta === "variant"
            ? <span style={{fontSize:10, fontWeight:700, color:"var(--system-green)", letterSpacing:0.6, flexShrink:0, padding:`2px ${DT.s[2]-1}px`, background:"rgba(50,215,75,0.15)", borderRadius:"var(--r-1)", border:"1px solid rgba(48,209,88,0.27)", ...S.mono}}>VARIANT</span>
            : selected.meta === "archived"
            ? <span style={{fontSize:10, fontWeight:700, color:"var(--label-2)", letterSpacing:0.6, flexShrink:0, padding:`2px ${DT.s[2]-1}px`, background:"var(--mat-thick)", borderRadius:"var(--r-1)", border:"0.5px solid var(--separator)", ...S.mono}}>ARCHIVED</span>
            : selected.meta && <span style={{fontSize:12, color:"var(--label-2)", ...S.mono, flexShrink:1, minWidth:0, maxWidth:120, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{selected.meta}</span>}
        </> : <span style={{flex:1, color:"var(--label-3)"}}>{placeholder}</span>}
        <span style={{position:"absolute", right:DT.s[3], top:"50%", transform:`translateY(-50%) ${open?"rotate(180deg)":""}`, transition:"transform .15s", color:"var(--label-2)", pointerEvents:"none",display:"inline-flex"}}>{I("chevronDown",14)}</span>
      </button>
      {dropdown && ReactDOM.createPortal(dropdown, document.body)}
    </div>;
  }, (prev, next) => {
    // Custom equality: ignore onChange (we use ref). Re-render only if value/options/placeholder/disabled changed.
    if (prev.value !== next.value) return false;
    if (prev.disabled !== next.disabled) return false;
    if (prev.placeholder !== next.placeholder) return false;
    const a = prev.options || [], b = next.options || [];
    if (a.length !== b.length) return false;
    for (let i = 0; i < a.length; i++) {
      if (!a[i] || !b[i]) return false;
      if (a[i].value !== b[i].value || a[i].label !== b[i].label || a[i].logo !== b[i].logo || a[i].meta !== b[i].meta) return false;
      if (a[i].header !== b[i].header || a[i].action !== b[i].action || a[i].noLogo !== b[i].noLogo || a[i].icon !== b[i].icon) return false;
    }
    return true; // skip re-render
  });
  } // end of: if (!ServiceSelectRef.current)
  const ServiceSelect = ServiceSelectRef.current;

  // Universal iOS26-styled dropdown for plain {value, label} options — no logos,
  // no service icons. Use this anywhere a native <select> would be used in the
  // panel UI. Renders the popup via React portal so it never gets clipped by
  // parent overflow/transform contexts.
  function IOSSelect({ value, onChange, options, placeholder = "Select…", style = {}, fullWidth = true }) {
    const [open, setOpen] = React.useState(false);
    const [pos, setPos] = React.useState({ top: 0, left: 0, width: 200 });
    const wrapRef = React.useRef(null);
    const dropRef = React.useRef(null);
    const openedAt = React.useRef(0);

    const selected = options.find(o => String(o.value) === String(value)) || null;

    const recalc = React.useCallback(() => {
      if (!wrapRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      if (!r.width) return;
      const H = 280;
      const spaceBelow = window.innerHeight - r.bottom;
      const spaceAbove = r.top;
      const flipUp = spaceBelow < H && spaceAbove > spaceBelow;
      const W = Math.max(r.width, 220);
      const maxLeft = window.innerWidth - W - 8;
      const left = Math.max(8, Math.min(r.left, maxLeft));
      setPos(flipUp
        ? { bottom: Math.max(8, window.innerHeight - r.top + 4), top: undefined, left, width: W, maxHeight: Math.min(H, spaceAbove - 16) }
        : { top: r.bottom + 4, bottom: undefined, left, width: W, maxHeight: Math.min(H, spaceBelow - 16) });
    }, []);

    React.useLayoutEffect(() => {
      if (!open) return;
      recalc();
      const r1 = requestAnimationFrame(recalc);
      const r2 = requestAnimationFrame(() => requestAnimationFrame(recalc));
      return () => { cancelAnimationFrame(r1); cancelAnimationFrame(r2); };
    }, [open, recalc]);

    React.useEffect(() => {
      if (!open) return;
      openedAt.current = Date.now();
      const close = (e) => {
        if (Date.now() - openedAt.current < 250) return;
        if (wrapRef.current && wrapRef.current.contains(e.target)) return;
        if (dropRef.current && dropRef.current.contains(e.target)) return;
        setOpen(false);
      };
      const onScroll = () => recalc();
      document.addEventListener("mousedown", close);
      document.addEventListener("touchstart", close, { passive: true });
      window.addEventListener("scroll", onScroll, true);
      window.addEventListener("resize", onScroll);
      return () => {
        document.removeEventListener("mousedown", close);
        document.removeEventListener("touchstart", close);
        window.removeEventListener("scroll", onScroll, true);
        window.removeEventListener("resize", onScroll);
      };
    }, [open, recalc]);

    const triggerStyle = {
      ...IOS.input,
      cursor: "pointer",
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      gap: 8,
      width: fullWidth ? "100%" : "auto",
      ...style,
    };

    return (
      <>
        <div ref={wrapRef} style={triggerStyle} onClick={() => setOpen(o => !o)}>
          <span style={{
            color: selected ? "var(--label-1)" : "rgba(255,255,255,0.45)",
            fontSize: 14, letterSpacing: -0.1,
            overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1,
          }}>{selected ? selected.label : placeholder}</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, transform: open ? "rotate(180deg)" : "none", transition: "transform .15s" }}>
            <polyline points="6 9 12 15 18 9"/>
          </svg>
        </div>
        {open && ReactDOM.createPortal(
          <div ref={dropRef} style={{
            position: "fixed",
            ...pos,
            background: "rgba(30, 30, 32, 0.92)",
            backdropFilter: "blur(60px) saturate(180%)",
            WebkitBackdropFilter: "blur(60px) saturate(180%)",
            border: "0.5px solid var(--mat-regular)",
            borderRadius: 14,
            boxShadow: "0 16px 48px rgba(0, 0, 0, 0.45), inset 0 0.5px 0 var(--separator)",
            padding: 5,
            zIndex: 999999,
            overflowY: "auto",
            fontFamily: FONT_DISPLAY,
            animation: "iosSelectFadeIn 180ms cubic-bezier(0.32, 0.72, 0, 1)",
          }}>
            <style>{`
              @keyframes iosSelectFadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }
            `}
{bCSS(accent)}
{bCSS(accent)}
{bCSS(accent)}
${edCss}

                [data-aio-text-idx] { position: relative; cursor: text; transition: outline .12s, background .12s; }
                [data-aio-text-idx]:hover { outline: 2px solid #16a34a88; outline-offset: 2px; background: #16a34a0a; border-radius: 3px; }
                [data-aio-text-idx][data-aio-edited="1"] { outline: 2px solid #16a34a; outline-offset: 2px; background: #16a34a14; border-radius: 3px; }
