<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Top Live Rock Bands & Gigs in New York | ShowABand</title>
  <meta name="description" content="Discover top live Rock bands, concert dates, and venue schedules in New York. Direct booking, verified setlists, and live gig discovery on ShowABand.">
  <link rel="canonical" href="https://showaband.com/directory/new%20york/rock">
  <link rel="icon" type="image/svg+xml" href="/favicon.svg">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;600;700;800;900&family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;700;800&display=swap" rel="stylesheet">
  <!-- Permitted CDN: Tailwind CSS stylesheet (CSP compliant) -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
  <link rel="stylesheet" href="/css/modern-theme.css?v=3.0">
  <style>
    :root {
      --bg-porcelain: #f8fafc;
      --card-porcelain: #ffffff;
      --sub-panel: #f1f5f9;
      --border-porcelain: #e2e8f0;
      --text-obsidian: #0f172a;
      --text-muted: #64748b;
      --accent-amber: #d97706;
      --accent-hover: #b45309;
      --accent-green: #059669;
      --accent-blue: #0284c7;
      --shadow-card: 0 4px 20px -2px rgba(15, 23, 42, 0.05), 0 2px 6px -1px rgba(15, 23, 42, 0.03);
      --shadow-hover: 0 20px 30px -10px rgba(15, 23, 42, 0.08), 0 6px 12px -2px rgba(15, 23, 42, 0.04);
      --radius-card: 16px;
    }

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body {
      background-color: var(--bg-porcelain);
      color: var(--text-obsidian);
      font-family: 'Plus Jakarta Sans', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      min-height: 100vh;
      line-height: 1.5;
    }

    /* Clean Porcelain Header */
    .directory-header {
      background: #ffffff;
      border-bottom: 1px solid var(--border-porcelain);
      padding: 14px 28px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 100;
      box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.03);
    }

    .brand-group {
      display: flex;
      align-items: center;
      gap: 12px;
      text-decoration: none;
      color: var(--text-obsidian);
    }

    .brand-badge {
      background: var(--accent-amber);
      color: #ffffff;
      font-size: 11px;
      font-weight: 800;
      padding: 4px 8px;
      border-radius: 6px;
      letter-spacing: 0.5px;
    }

    .brand-title {
      font-size: 17px;
      font-weight: 900;
      letter-spacing: -0.4px;
      color: var(--text-obsidian);
    }

    .header-nav-links {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .nav-btn {
      padding: 7px 14px;
      font-size: 13px;
      font-weight: 700;
      border-radius: 8px;
      text-decoration: none;
      transition: all 0.15s ease;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }

    .nav-btn-outline {
      background: #ffffff;
      color: var(--text-obsidian);
      border: 1px solid var(--border-porcelain);
    }

    .nav-btn-outline:hover, .nav-btn-outline.active {
      background: var(--sub-panel);
      border-color: #cbd5e1;
    }

    .nav-btn-primary {
      background: var(--accent-amber);
      color: #ffffff;
      border: 1px solid var(--accent-hover);
    }

    .nav-btn-primary:hover {
      background: var(--accent-hover);
    }

    /* Layout Container with Left Navigation Rail */
    .directory-layout-wrapper {
      max-width: 1320px;
      margin: 0 auto;
      padding: 24px 20px 80px;
      display: grid;
      grid-template-columns: 240px minmax(0, 1fr);
      gap: 24px;
      align-items: start;
    }

    @media (max-width: 960px) {
      .directory-layout-wrapper {
        grid-template-columns: 1fr;
      }
    }

    .directory-left-rail {
      position: sticky;
      top: 84px;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .rail-nav-box {
      background: #ffffff;
      border: 1px solid var(--border-porcelain);
      border-radius: 16px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .rail-nav-link {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 10px;
      padding: 8px 12px;
      border-radius: 8px;
      font-size: 13px;
      font-weight: 500;
      color: #0f172a;
      text-decoration: none;
      border: 1px solid transparent;
      transition: all 0.15s ease;
    }

    .rail-nav-link:hover {
      background: #f1f5f9;
      color: #0f172a;
      border-color: transparent;
    }

    .rail-nav-link.active {
      background: #fef3c7;
      color: #92400e;
      border-color: #fde68a;
      font-weight: 600;
    }

    .rail-nav-link.active svg {
      color: #d97706;
      stroke: #d97706;
    }

    .classified-pill {
      background: #f8fafc;
      border: 1px solid var(--border-porcelain);
      color: #334155;
      padding: 7px 15px;
      font-size: 12px;
      font-weight: 700;
      border-radius: 9999px;
      cursor: pointer;
      transition: all 0.15s ease;
      white-space: nowrap;
      user-select: none;
      outline: none;
    }

    .classified-pill:hover {
      background: #e2e8f0;
      color: #0f172a;
    }

    .classified-pill.active {
      background: var(--accent-amber);
      color: #ffffff;
      border-color: var(--accent-hover);
      box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);
    }

    .classified-card {
      background: var(--card-porcelain);
      border: 1px solid var(--border-porcelain);
      border-radius: 16px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
      padding: 22px;
      transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
    }

    .classified-card:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.08);
      border-color: #cbd5e1;
    }

    .classified-dropzone.drag-active {
      border-color: var(--accent-amber) !important;
      background: #fef3c7 !important;
    }

    /* Container Fallback */
    .directory-container {
      max-width: 100%;
      margin: 0;
      padding: 0;
    }

    /* Hero Banner */
    .directory-hero {
      background: #ffffff;
      border: 1px solid var(--border-porcelain);
      border-radius: var(--radius-card);
      padding: 36px 32px;
      margin-bottom: 28px;
      box-shadow: var(--shadow-card);
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 24px;
      flex-wrap: wrap;
    }

    .hero-info {
      max-width: 780px;
    }

    .hero-eyebrow {
      font-family: 'JetBrains Mono', monospace;
      font-size: 11px;
      font-weight: 800;
      text-transform: uppercase;
      color: var(--accent-amber);
      letter-spacing: 1px;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .hero-title {
      font-size: 30px;
      font-weight: 900;
      letter-spacing: -0.8px;
      color: var(--text-obsidian);
      margin-bottom: 8px;
      line-height: 1.2;
    }

    .hero-subtitle {
      font-size: 15px;
      color: var(--text-muted);
      line-height: 1.6;
    }

    .hero-stats-pill {
      background: var(--sub-panel);
      border: 1px solid var(--border-porcelain);
      border-radius: 12px;
      padding: 16px 20px;
      display: flex;
      align-items: center;
      gap: 20px;
    }

    .stat-item {
      display: flex;
      flex-direction: column;
    }

    .stat-value {
      font-size: 20px;
      font-weight: 900;
      color: var(--text-obsidian);
      font-family: 'JetBrains Mono', monospace;
    }

    .stat-label {
      font-size: 11px;
      font-weight: 700;
      color: var(--text-muted);
      text-transform: uppercase;
    }

    /* Filter Bar */
    .filter-bar-card {
      background: #ffffff;
      border: 1px solid var(--border-porcelain);
      border-radius: var(--radius-card);
      padding: 20px 24px;
      margin-bottom: 32px;
      box-shadow: var(--shadow-card);
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .filter-inputs-row {
      display: flex;
      gap: 12px;
      align-items: center;
      flex-wrap: wrap;
    }

    .search-input-wrap {
      flex: 1;
      min-width: 280px;
      position: relative;
    }

    .search-input-wrap svg {
      position: absolute;
      left: 14px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-muted);
      pointer-events: none;
    }

    .directory-search-input {
      width: 100%;
      padding: 11px 14px 11px 42px;
      font-size: 14px;
      font-family: inherit;
      border: 1px solid var(--border-porcelain);
      border-radius: 10px;
      background: var(--bg-porcelain);
      color: var(--text-obsidian);
      outline: none;
      transition: all 0.15s ease;
    }

    .directory-search-input:focus {
      background: #ffffff;
      border-color: var(--accent-amber);
      box-shadow: 0 0 0 3px rgba(217, 119, 6, 0.12);
    }

    .location-filter-wrap {
      min-width: 200px;
    }

    .directory-select {
      width: 100%;
      padding: 11px 14px;
      font-size: 14px;
      font-family: inherit;
      border: 1px solid var(--border-porcelain);
      border-radius: 10px;
      background: var(--bg-porcelain);
      color: var(--text-obsidian);
      outline: none;
      cursor: pointer;
    }

    .directory-select:focus {
      background: #ffffff;
      border-color: var(--accent-amber);
    }

    .available-toggle-label {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 9px 14px;
      background: #ecfdf5;
      border: 1px solid #a7f3d0;
      border-radius: 10px;
      cursor: pointer;
      font-size: 13px;
      font-weight: 700;
      color: var(--accent-green);
      user-select: none;
      white-space: nowrap;
    }

    .available-toggle-label input {
      accent-color: var(--accent-green);
      cursor: pointer;
      width: 16px;
      height: 16px;
    }

    /* Role Pills Row */
    .filter-pills-row {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      border-top: 1px solid var(--border-porcelain);
      padding-top: 14px;
    }

    .filter-pill {
      background: var(--bg-porcelain);
      border: 1px solid var(--border-porcelain);
      color: #334155;
      padding: 6px 14px;
      font-size: 12px;
      font-weight: 700;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.12s ease;
      white-space: nowrap;
      user-select: none;
    }

    .filter-pill:hover {
      background: #e2e8f0;
      color: var(--text-obsidian);
    }

    .filter-pill.active {
      background: var(--accent-amber);
      color: #ffffff;
      border-color: var(--accent-hover);
      box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);
    }

    /* Talent Domain Category Chips (Music / Comedy / Acting / Variety / Crew) */
    .category-chips-row {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      padding-bottom: 14px;
      border-bottom: 1px solid var(--border-porcelain);
      margin-bottom: 4px;
    }

    .category-chip {
      background: #ffffff;
      border: 1px solid var(--border-porcelain);
      color: #334155;
      padding: 8px 18px;
      font-size: 12.5px;
      font-weight: 800;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.12s ease;
      white-space: nowrap;
      user-select: none;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      letter-spacing: 0.01em;
    }

    .category-chip:hover {
      background: #f1f5f9;
      border-color: #cbd5e1;
      color: var(--text-obsidian);
    }

    .category-chip.active {
      background: var(--text-obsidian);
      color: #ffffff;
      border-color: var(--text-obsidian);
      box-shadow: 0 2px 8px rgba(15, 23, 42, 0.18);
    }

    .category-chip .chip-domain-dot {
      width: 7px;
      height: 7px;
      border-radius: 50%;
      flex-shrink: 0;
    }

    /* Craft badge on talent cards (primary craft / domain) */
    .craft-badge {
      background: #fffbeb;
      color: #b45309;
      border: 1px solid #fde68a;
    }

    .craft-badge.craft-crew {
      background: #eff6ff;
      color: #1d4ed8;
      border-color: #bfdbfe;
    }

    .craft-badge.craft-comedy {
      background: #fef3c7;
      color: #92400e;
      border-color: #fcd34d;
    }

    .craft-badge.craft-acting {
      background: #f5f3ff;
      color: #6d28d9;
      border-color: #ddd6fe;
    }

    .craft-badge.craft-variety {
      background: #fdf2f8;
      color: #be185d;
      border-color: #fbcfe8;
    }

    /* 3-Column Directory Cards Grid */
    .directory-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 24px;
    }

    @media (max-width: 1080px) {
      .directory-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }

    @media (max-width: 680px) {
      .directory-grid {
        grid-template-columns: 1fr;
      }
    }

    .talent-card {
      background: var(--card-porcelain);
      border: 1px solid var(--border-porcelain);
      border-radius: var(--radius-card);
      box-shadow: var(--shadow-card);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
      position: relative;
    }

    .talent-card:hover {
      transform: translateY(-3px);
      box-shadow: var(--shadow-hover);
      border-color: #cbd5e1;
    }

    .talent-card-header {
      padding: 20px 20px 14px;
      display: flex;
      gap: 14px;
      align-items: flex-start;
    }

    .talent-avatar-wrap {
      position: relative;
      width: 64px;
      height: 64px;
      min-width: 64px;
    }

    .talent-avatar {
      width: 64px;
      height: 64px;
      border-radius: 50%;
      object-fit: cover;
      background: var(--sub-panel);
      border: 2px solid #ffffff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }

    .talent-avail-dot {
      position: absolute;
      bottom: 2px;
      right: 2px;
      width: 14px;
      height: 14px;
      border-radius: 50%;
      background: var(--accent-green);
      border: 2px solid #ffffff;
    }

    .talent-avail-dot.busy {
      background: var(--accent-amber);
    }

    .talent-header-meta {
      flex: 1;
      min-width: 0;
    }

    .talent-name-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 6px;
      margin-bottom: 2px;
    }

    .talent-name {
      font-size: 17px;
      font-weight: 800;
      color: var(--text-obsidian);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-decoration: none;
    }

    .talent-name:hover {
      color: var(--accent-amber);
    }

    .talent-role-badge {
      font-family: 'JetBrains Mono', monospace;
      font-size: 9px;
      font-weight: 800;
      text-transform: uppercase;
      padding: 2px 6px;
      border-radius: 4px;
      background: var(--sub-panel);
      color: #475569;
      border: 1px solid var(--border-porcelain);
      flex-shrink: 0;
    }

    .talent-location {
      font-size: 13px;
      color: var(--text-muted);
      display: flex;
      align-items: center;
      gap: 4px;
      margin-bottom: 6px;
    }

    .talent-card-body {
      padding: 0 20px 18px;
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .talent-bio {
      font-size: 13px;
      color: #334155;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .shelf-label {
      font-size: 10px;
      font-weight: 800;
      text-transform: uppercase;
      color: var(--text-muted);
      letter-spacing: 0.5px;
      margin-bottom: 4px;
    }

    .instruments-shelf {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
    }

    .badge-pill-inst {
      background: #fffbeb;
      border: 1px solid #fde68a;
      color: #92400e;
      font-size: 11px;
      font-weight: 700;
      padding: 2px 8px;
      border-radius: 5px;
    }

    .bands-shelf-list {
      font-size: 12px;
      color: #475569;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 6px;
      flex-wrap: wrap;
    }

    .band-affiliation-tag {
      background: var(--sub-panel);
      border: 1px solid var(--border-porcelain);
      color: var(--text-obsidian);
      padding: 2px 7px;
      border-radius: 4px;
      font-size: 11px;
    }

    .talent-card-footer {
      padding: 14px 20px;
      background: #f8fafc;
      border-top: 1px solid var(--border-porcelain);
      display: flex;
      gap: 10px;
    }

    .btn-card-action {
      flex: 1;
      padding: 8px 12px;
      font-size: 12px;
      font-weight: 700;
      border-radius: 8px;
      text-align: center;
      text-decoration: none;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      transition: all 0.15s ease;
    }

    .btn-card-outline {
      background: #ffffff;
      color: var(--text-obsidian);
      border: 1px solid var(--border-porcelain);
    }

    .btn-card-outline:hover {
      background: var(--sub-panel);
      border-color: #cbd5e1;
    }

    .btn-card-primary {
      background: var(--accent-amber);
      color: #ffffff;
      border: 1px solid var(--accent-hover);
    }

    .btn-card-primary:hover {
      background: var(--accent-hover);
    }

    /* Empty state */
    .empty-directory-card {
      grid-column: 1 / -1;
      background: #ffffff;
      border: 1px dashed var(--border-porcelain);
      border-radius: var(--radius-card);
      padding: 56px 24px;
      text-align: center;
      color: var(--text-muted);
    }

    .empty-directory-card h3 {
      font-size: 18px;
      font-weight: 800;
      color: var(--text-obsidian);
      margin-bottom: 6px;
    }

    /* Connect Modal */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background: rgba(15, 23, 42, 0.6);
      backdrop-filter: blur(4px);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      padding: 20px;
    }

    .modal-card {
      background: #ffffff;
      border: 1px solid var(--border-porcelain);
      border-radius: 16px;
      width: 100%;
      max-width: 520px;
      box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
      overflow: hidden;
      animation: modalFadeIn 0.2s ease-out;
    }

    @keyframes modalFadeIn {
      from { opacity: 0; transform: scale(0.96); }
      to { opacity: 1; transform: scale(1); }
    }

    .modal-header {
      padding: 20px 24px;
      border-bottom: 1px solid var(--border-porcelain);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .modal-title {
      font-size: 18px;
      font-weight: 800;
      color: var(--text-obsidian);
    }

    .modal-close-btn {
      background: transparent;
      border: none;
      font-size: 20px;
      font-weight: 700;
      color: var(--text-muted);
      cursor: pointer;
      line-height: 1;
    }

    .modal-body {
      padding: 24px;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .form-group {
      display: flex;
      flex-direction: column;
      gap: 6px;
    }

    .form-label {
      font-size: 12px;
      font-weight: 700;
      color: #334155;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .form-input, .form-textarea, .form-select {
      width: 100%;
      padding: 10px 14px;
      font-size: 14px;
      font-family: inherit;
      border: 1px solid var(--border-porcelain);
      border-radius: 8px;
      background: #ffffff;
      color: var(--text-obsidian);
      outline: none;
    }

    .form-input:focus, .form-textarea:focus, .form-select:focus {
      border-color: var(--accent-amber);
      box-shadow: 0 0 0 2px rgba(217, 119, 6, 0.15);
    }

    .form-textarea {
      resize: vertical;
      min-height: 80px;
    }

    .modal-footer {
      padding: 16px 24px;
      border-top: 1px solid var(--border-porcelain);
      background: #f8fafc;
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }

    .status-alert {
      padding: 12px 16px;
      border-radius: 8px;
      font-size: 13px;
      font-weight: 600;
      display: none;
    }

    .status-alert.success {
      display: block;
      background: #ecfdf5;
      border: 1px solid #a7f3d0;
      color: var(--accent-green);
    }

    .status-alert.error {
      display: block;
      background: #fef2f2;
      border: 1px solid #fecaca;
      color: #b91c1c;
    }
  </style>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "ItemList",
      "name": "Live Rock Bands in New York",
      "description": "Top verified Rock acts performing live in New York",
      "itemListElement": [
        {
          "@type": "ListItem",
          "position": 1,
          "item": {
            "@type": "MusicGroup",
            "name": "AppsAndStuff",
            "genre": "punk rock, nu metal",
            "description": "Atmospheric post-punk and indie rock collective crafting sprawling sonic textures, driving rhythm, and heartfelt lyrical hooks.",
            "url": "https://showaband.com/bands/appsandstuff",
            "image": "https://bandsagent-media-live.s3.us-east-2.amazonaws.com/avatars/1794360321998-d552a62b-fa92-40f8-a9a9-9c7b783f166f-watermarked_img_15120260402744659144.jpg"
          }
        }
      ]
    }
  ]
}
</script>
</head>
<body>

  <!-- Top Porcelain Navigation -->
  <header class="app-topbar" style="position: sticky; top: 0; z-index: 1000; height: 64px; background: #ffffff; border-bottom: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; padding: 0 24px; box-sizing: border-box;">
    <!-- Left: Brand Logo + Active Act Selector / Pill Badge -->
    <div class="topbar-left flex items-center gap-3">
      <a href="/dashboard.html" class="font-extrabold text-base tracking-tight text-slate-900 no-underline select-none">BandsAgent</a>
      <div class="inline-flex items-center gap-1.5 bg-slate-50 border border-slate-200 rounded-full px-3 py-1 text-xs font-semibold text-slate-700">
        <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
        <span>Active Act</span>
      </div>
    </div>

    <!-- Center: Global Search Bar -->
    <div class="topbar-center relative flex items-center justify-center">
      <input type="text" id="global-search" class="bg-slate-50 border border-slate-200 rounded-full px-4 py-2 text-xs w-72 text-slate-800 placeholder-slate-400 focus:outline-none focus:border-amber-500 focus:bg-white transition-all" placeholder="Search talent, instruments, cities..." oninput="typeof filterDirectoryCards === 'function' ? filterDirectoryCards() : null">
    </div>

    <!-- Right: Navigation Links + Avatar Circle -->
    <div class="topbar-right flex items-center gap-4 text-xs font-semibold text-slate-600">
      <!-- Right: Messenger drawer toggle, Cart drawer toggle, Profile dropdown.
           Section navigation (The Stage Wire / Live Stages / Merch Store / Backstage
          Console) lives exclusively in the left rail — never duplicated here. -->
      <button type="button" id="nav-messenger-toggle" class="topbar-drawer-icon-btn" aria-label="Open Messenger" title="Open Messenger" onclick="if (typeof toggleGlobalMessenger === 'function') toggleGlobalMessenger();">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
        </svg>
      </button>
      <button type="button" id="nav-cart-toggle" class="topbar-drawer-icon-btn" aria-label="Open Shopping Cart" title="Open Shopping Cart" onclick="if (typeof toggleGlobalCart === 'function') toggleGlobalCart();">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path>
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <path d="M16 10a4 4 0 0 1-8 0"></path>
        </svg>
      </button>
      <div id="nav-user-dropdown-wrap" class="relative inline-flex items-center">
        <button id="nav-user-avatar-btn" type="button" class="nav-user-avatar-btn inline-flex items-center justify-center w-9 h-9 rounded-full overflow-hidden border border-slate-200 hover:border-slate-400 transition-colors cursor-pointer p-0 bg-slate-800" aria-label="Profile and Account Menu" aria-haspopup="true">
          <img id="topbar-user-avatar" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' fill='%2394a3b8'><rect width='64' height='64' fill='%23f1f5f9'/><circle cx='32' cy='24' r='12'/><path d='M16 54c0-8.8 7.2-16 16-16s16 7.2 16 16z'/></svg>" alt="Avatar" class="w-full h-full object-cover" data-avatar-name="" onerror="applyAvatarFallback(this)">
        </button>
        <span class="nav-caret" aria-hidden="true">&#9662;</span>

        <!-- Clean Porcelain Light User Account Dropdown Menu -->
        <div id="nav-user-dropdown-menu" style="display: none; position: absolute; right: 0; top: calc(100% + 8px); width: 250px; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.05); z-index: 100000; padding: 12px; color: #0f172a; text-align: left; box-sizing: border-box;">
          <div style="border-bottom: 1px solid #e2e8f0; padding-bottom: 10px; margin-bottom: 8px;">
            <div id="dropdown-full-name" style="font-size: 13px; font-weight: 800; color: #0f172a; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">User</div>
            <div id="dropdown-full-email" style="font-size: 11px; color: #64748b; word-break: break-all; margin-top: 2px;"></div>
            <div style="display: flex; gap: 6px; margin-top: 8px; align-items: center; flex-wrap: wrap;">
              <span id="dropdown-role-badge" style="background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; font-size: 9px; font-weight: 800; padding: 2px 6px; border-radius: 4px; text-transform: uppercase;">BAND</span>
              <span id="dropdown-tier-badge" style="background: #fffbeb; color: #b45309; border: 1px solid #fde68a; font-size: 9px; font-weight: 800; padding: 2px 6px; border-radius: 4px; text-transform: uppercase;">PRO</span>
            </div>
          </div>
          <div style="display: flex; flex-direction: column; gap: 4px;">
            <a id="dropdown-edit-profile-link" href="/musician-profile.html?me=true" style="display: flex; align-items: center; justify-content: space-between; padding: 8px 10px; border-radius: 8px; text-decoration: none; color: #0f172a; font-size: 12px; font-weight: 700; background: #fffbeb; border: 1px solid #fde68a; transition: all 0.15s ease;">
              <span style="display: flex; align-items: center; gap: 6px;">
                <span>👤</span>
                <span>My Profile</span>
              </span>
              <span style="color: #d97706; font-size: 14px; font-weight: 800;">&rarr;</span>
            </a>
            <a href="/my-account.html" style="display: flex; align-items: center; justify-content: space-between; padding: 8px 10px; border-radius: 8px; text-decoration: none; color: #475569; font-size: 12px; font-weight: 600; transition: background 0.15s ease;" onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
              <span style="display: flex; align-items: center; gap: 6px;">
                <span>⚙</span>
                <span>Account Settings</span>
              </span>
              <span style="color: #94a3b8; font-size: 12px;">&rarr;</span>
            </a>
          </div>
          <div style="border-top: 1px solid #e2e8f0; margin-top: 8px; padding-top: 8px;">
            <button type="button" onclick="if (typeof executeSecureLogout === 'function') executeSecureLogout();" style="width: 100%; display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-radius: 8px; background: transparent; border: none; text-align: left; color: #dc2626; font-size: 12px; font-weight: 700; cursor: pointer; transition: background 0.15s ease;" onmouseover="this.style.background='#fef2f2'" onmouseout="this.style.background='transparent'">
              <span>🚪 Log Out</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </header>

  <!-- Main Layout Wrapper with Left Navigation Rail -->
  <main class="directory-layout-wrapper">

    <!-- Left Column: Navigation Rail (240px) -->
    <aside class="directory-left-rail">
      <nav class="rail-nav-box" aria-label="Discovery Navigation">
        <!-- Discovery Hub section destinations -->
        <div class="rail-group-label">DISCOVERY HUB</div>

        <!-- Talent Directory (Active) -->
        <a href="/directory.html" class="rail-nav-link active" id="rail-link-directory" onclick="switchDirectoryView('talent', event)">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
            <rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect>
          </svg>
          <span>Talent Directory</span>
        </a>

        <!-- The Stage Wire -->
        <a href="/feed.html" class="rail-nav-link">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <path d="M4 11a9 9 0 0 1 9 9"></path>
            <path d="M4 4a16 16 0 0 1 16 16"></path>
            <circle cx="5" cy="19" r="1"></circle>
          </svg>
          <span>The Stage Wire</span>
        </a>

        <!-- Live Stages -->
        <a href="/showaband.html" class="rail-nav-link">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <rect x="2" y="7" width="20" height="15" rx="2" ry="2"></rect>
            <polyline points="17 2 12 7 7 2"></polyline>
          </svg>
          <span>Live Stages</span>
        </a>

        <!-- Merch Store -->
        <a href="/merch.html" class="rail-nav-link">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path>
            <line x1="3" y1="6" x2="21" y2="6"></line>
            <path d="M16 10a4 4 0 0 1-8 0"></path>
          </svg>
          <span>Merch Store</span>
        </a>

        <div class="rail-divider"></div>
        <div class="rail-group-label">BACKSTAGE</div>

        <!-- Backstage Console -->
        <a href="/dashboard.html" class="rail-nav-link">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <rect x="3" y="3" width="7" height="7"></rect>
            <rect x="14" y="3" width="7" height="7"></rect>
            <rect x="14" y="14" width="7" height="7"></rect>
            <rect x="3" y="14" width="7" height="7"></rect>
          </svg>
          <span>Backstage Console</span>
        </a>
      </nav>
    </aside>

    <!-- Center Stream Content Area -->
    <div class="directory-main-stream" style="min-width: 0;">

      <!-- In-Page View Tabs (Directory vs Classifieds) — page-local controls, not nav -->
      <div class="view-tab-chip-row" role="tablist" aria-label="Directory Views">
        <button type="button" class="view-tab-chip active" id="view-tab-talent" role="tab" aria-selected="true" onclick="setDirectoryViewTab('talent')">Talent Directory</button>
        <button type="button" class="view-tab-chip" id="view-tab-classifieds" role="tab" aria-selected="false" onclick="setDirectoryViewTab('classifieds')">Classifieds &amp; Gear</button>
      </div>

      <!-- Primary Talent Directory View -->
      <div id="directory-talent-section">
        <!-- Hero Banner -->
        <section class="directory-hero">
          <div class="hero-info">
            <div class="hero-eyebrow">
              <span>LIVE MARKETPLACE</span>
              <span>&bull;</span>
              <span>MULTI-BAND ROSTER HUB</span>
            </div>
            <h1 class="hero-title">Universal Talent &amp; Roster Discovery</h1>
            <p class="hero-subtitle">
              Connect directly with verified session musicians, multi-instrumentalists, touring bands, comedians, actors, variety performers, and live production crew. Explore active setlists, audition availability, and hire subs or specialists for upcoming dates.
            </p>
          </div>
          <div class="hero-stats-pill">
            <div class="stat-item">
              <span class="stat-value" id="stats-total-talent">--</span>
              <span class="stat-label">Verified Acts</span>
            </div>
            <div class="stat-item">
              <span class="stat-value" id="stats-available-subs">--</span>
              <span class="stat-label">Available Subs</span>
            </div>
          </div>
        </section>

        <!-- Filter Bar Card -->
        <section class="filter-bar-card">
          <div class="filter-inputs-row">
            <div class="search-input-wrap">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
              <input 
                type="text" 
                id="search-input" 
                class="directory-search-input" 
                placeholder="Search by talent moniker, instrument, band, or city..."
              >
            </div>

            <div class="location-filter-wrap">
              <select id="location-select" class="directory-select">
                <option value="">All Locations</option>
                <option value="Austin">Austin, TX</option>
                <option value="Detroit">Detroit, MI</option>
                <option value="Chicago">Chicago, IL</option>
                <option value="Toronto">Toronto, ON</option>
                <option value="New York">New York, NY</option>
                <option value="Nashville">Nashville, TN</option>
                <option value="Los Angeles">Los Angeles, CA</option>
              </select>
            </div>

            <label class="available-toggle-label" title="Show only talent available for subbing or tour gigs">
              <input type="checkbox" id="available-toggle">
              <span>Available for Hire Only</span>
            </label>
          </div>

          <!-- Role / Instrument Filter Pills -->
          <div class="category-chips-row" id="directory-category-chips-row" aria-label="Talent Domain Filters">
            <button type="button" class="category-chip active" data-cat="ALL">
              <span class="chip-domain-dot" style="background:#d97706;"></span>All Talent
            </button>
            <button type="button" class="category-chip" data-cat="MUSIC">
              <span class="chip-domain-dot" style="background:#0284c7;"></span>Music
            </button>
            <button type="button" class="category-chip" data-cat="COMEDY">
              <span class="chip-domain-dot" style="background:#ca8a04;"></span>Comedy
            </button>
            <button type="button" class="category-chip" data-cat="ACTING">
              <span class="chip-domain-dot" style="background:#7c3aed;"></span>Theater &amp; Acting
            </button>
            <button type="button" class="category-chip" data-cat="VARIETY">
              <span class="chip-domain-dot" style="background:#db2777;"></span>Variety &amp; Stage
            </button>
            <button type="button" class="category-chip" data-cat="CREW">
              <span class="chip-domain-dot" style="background:#1d4ed8;"></span>Production &amp; Crew
            </button>
          </div>
          <div class="filter-pills-row" id="role-pills-container">
            <button type="button" class="filter-pill active" data-role="all" data-inst="">All Talent</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="drums">Drummers</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="bass">Bassists</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="guitar">Guitarists</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="keys">Keys / Synth</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="dj">DJs</button>
            <button type="button" class="filter-pill" data-role="musician" data-inst="sound-tech">Sound Techs</button>
            <button type="button" class="filter-pill" data-role="band" data-inst="">Bands / Acts</button>
            <button type="button" class="filter-pill" data-role="venue" data-inst="">Live Venues</button>
          </div>
        </section>

        <!-- Free-Tier Sponsor Banner Slot: horizontal leaderboard strip rendered by
             /js/ad-banner.js below the talent filter bar (anonymous / free-tier only). -->
        <div id="sponsor-directory-banner" class="sponsor-slot" data-sponsor-slot="leaderboard" data-sponsor-category="Live Sound" style="margin-bottom: 24px;" aria-label="Sponsored music partner placement"></div>

        <!-- Talent Cards Grid -->
        <section class="directory-grid" id="directory-cards-container">
          <!-- Dynamically Rendered -->
        </section>
      </div>

      <!-- Dedicated Classifieds & Gear Marketplace View -->
      <div id="directory-classifieds-section" style="display: none;">
        <!-- Banner Card with Post Action Trigger -->
        <div class="classifieds-header-card" style="background: #ffffff; border: 1px solid var(--border-porcelain); border-radius: 16px; padding: 24px 28px; margin-bottom: 24px; box-shadow: var(--shadow-card); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
          <div>
            <h2 style="font-size: 22px; font-weight: 800; color: #0f172a; margin: 0 0 4px 0; font-family: 'Plus Jakarta Sans', sans-serif;">Classifieds &amp; Gear Marketplace</h2>
            <p style="font-size: 14px; color: var(--text-muted); margin: 0;">Verified community board for musician availability, substitute players, hardware trade, and gig sharing.</p>
          </div>
          <button type="button" id="btn-open-post-classified-dir" class="btn-post-classified" onclick="handleOpenClassifiedModal()" style="background: var(--accent-amber); color: #ffffff; border: none; border-radius: 12px; padding: 11px 22px; font-size: 13px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: background 0.15s ease; box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
            <span>Post Classified</span>
          </button>
        </div>

        <!-- Category Pills Bar -->
        <div class="filter-bar-card" style="margin-bottom: 24px; padding: 16px 20px;">
          <div style="display: flex; gap: 8px; flex-wrap: wrap;" id="classifieds-pills-bar">
            <button type="button" class="classified-pill active" data-cat="ALL" onclick="filterClassifiedCategory('ALL', this)">All Classifieds</button>
            <button type="button" class="classified-pill" data-cat="MUSICIAN AVAILABILITY" onclick="filterClassifiedCategory('MUSICIAN AVAILABILITY', this)">Musician Availability</button>
            <button type="button" class="classified-pill" data-cat="SUB WANTED" onclick="filterClassifiedCategory('SUB WANTED', this)">Sub Wanted</button>
            <button type="button" class="classified-pill" data-cat="GEAR FOR SALE" onclick="filterClassifiedCategory('GEAR FOR SALE', this)">Gear for Sale</button>
            <button type="button" class="classified-pill" data-cat="GIG SHARE" onclick="filterClassifiedCategory('GIG SHARE', this)">Gig Share</button>
          </div>
          <div style="margin-top: 14px; border-top: 1px solid var(--border-porcelain); padding-top: 14px;">
            <div class="search-input-wrap">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
              <input 
                type="text" 
                id="directory-classifieds-search-input" 
                class="directory-search-input" 
                placeholder="Search classifieds by instrument, gear model, city, or keywords..."
                oninput="handleClassifiedSearchDebounced(this.value)"
              >
            </div>
          </div>
        </div>

        <!-- Classifieds Stream Grid -->
        <div id="directory-classifieds-stream" style="display: flex; flex-direction: column; gap: 18px;">
          <!-- Dynamically populated -->
        </div>
      </div>

    </div>
  </main>

  <!-- Connect / In-App Inquiry Modal -->
  <div class="modal-overlay" id="connect-modal-overlay">
    <div class="modal-card">
      <div class="modal-header">
        <h3 class="modal-title" id="connect-modal-title">Connect with Musician</h3>
        <button type="button" class="modal-close-btn" id="connect-close-btn">&times;</button>
      </div>
      <form id="connect-inquiry-form">
        <div class="modal-body">
          <div class="status-alert" id="connect-status-alert"></div>

          <div class="form-group">
            <label class="form-label">Gig Date / Performance Window</label>
            <input type="date" class="form-input" id="connect-date" required>
          </div>

          <div class="form-group">
            <label class="form-label">Role or Inquiry Type</label>
            <select class="form-select" id="connect-type">
              <option value="Tour Sub Musician">Tour Sub Musician</option>
              <option value="Session Recording">Session Recording</option>
              <option value="Band Audition">Band Lineup Audition</option>
              <option value="General Booking Inquiry">General Booking Inquiry</option>
            </select>
          </div>

          <div class="form-group">
            <label class="form-label">Venue / City Location</label>
            <input type="text" class="form-input" id="connect-venue" placeholder="e.g. The Fillmore, Detroit, MI" required>
          </div>

          <div class="form-group">
            <label class="form-label">Offered Compensation ($ USD)</label>
            <input type="number" class="form-input" id="connect-fee" placeholder="300" min="50" step="25" required>
          </div>

          <div class="form-group">
            <label class="form-label">Inquiry Message</label>
            <textarea class="form-textarea" id="connect-message" placeholder="Provide setlist requirements, song details, and rehearsal schedule..." required></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="nav-btn nav-btn-outline" id="connect-cancel-btn">Cancel</button>
          <button type="submit" class="nav-btn nav-btn-primary" id="connect-submit-btn">Send Inquiry</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Classified Gated Access Upgrade Modal (Clean Porcelain Light) -->
  <div id="classified-upgrade-modal" class="modal-overlay" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(6px); z-index: 10000; align-items: center; justify-content: center; padding: 20px;">
    <div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 16px; padding: 32px; box-shadow: 0 20px 40px -15px rgba(0,0,0,0.15); max-width: 480px; width: 100%;">
      <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">
        <div style="display: flex; align-items: center; gap: 10px;">
          <div style="width: 40px; height: 40px; border-radius: 10px; background: #fef3c7; color: #d97706; display: flex; align-items: center; justify-content: center; font-size: 20px;">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>
          </div>
          <div>
            <span style="font-size: 11px; font-weight: 700; color: #d97706; text-transform: uppercase; letter-spacing: 0.5px;">Marketplace Gate</span>
            <h3 style="font-family: 'Plus Jakarta Sans', sans-serif; font-size: 18px; font-weight: 800; color: #0f172a; margin: 2px 0 0 0;">Musician Verification Required</h3>
          </div>
        </div>
        <button type="button" onclick="closeClassifiedUpgradeModal()" style="background: none; border: none; font-size: 24px; color: #94a3b8; cursor: pointer; padding: 0 4px; line-height: 1;">&times;</button>
      </div>
      <p style="font-size: 14px; color: #475569; line-height: 1.6; margin: 0 0 20px 0;">
        Classified postings are reserved for musicians and band members.
      </p>
      <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 14px; margin-bottom: 24px; font-size: 13px; color: #64748b; line-height: 1.5;">
        Verified musicians and band acts can list instrument sales, equipment trades, tour availability, and urgent gig substitutions.
      </div>
      <div style="display: flex; gap: 10px; justify-content: flex-end;">
        <button type="button" onclick="closeClassifiedUpgradeModal()" style="background: #ffffff; border: 1px solid #cbd5e1; color: #334155; padding: 10px 18px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">Dismiss</button>
        <a href="/login.html?returnTo=/directory.html%23classifieds" style="background: #d97706; color: #ffffff; text-decoration: none; padding: 10px 20px; border-radius: 10px; font-size: 13px; font-weight: 700; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);">Sign In or Register</a>
      </div>
    </div>
  </div>

  <!-- Post a Classified Modal (Clean Porcelain Light, 4-Image Drag-and-Drop) -->
  <div id="post-classified-modal" class="modal-overlay" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(6px); z-index: 10000; align-items: center; justify-content: center; padding: 20px;">
    <div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 16px; width: 100%; max-width: 580px; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);">
      <div style="padding: 20px 24px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: #ffffff; z-index: 10;">
        <div>
          <span style="font-size: 11px; font-weight: 700; color: #d97706; text-transform: uppercase; letter-spacing: 0.5px;">Musician Marketplace</span>
          <h3 style="font-size: 18px; font-weight: 800; color: #0f172a; margin: 2px 0 0 0; font-family: 'Plus Jakarta Sans', sans-serif;">Post a Classified</h3>
        </div>
        <button type="button" onclick="closePostClassifiedModal()" style="background: transparent; border: none; font-size: 24px; color: #64748b; cursor: pointer; line-height: 1;">&times;</button>
      </div>

      <form id="post-classified-form" onsubmit="submitClassifiedListing(event)" style="padding: 24px; display: flex; flex-direction: column; gap: 16px;">
        <div id="classified-form-alert" style="display: none; padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 600;"></div>

        <!-- Category Selector -->
        <div>
          <label for="classified-category-input" style="display: block; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; margin-bottom: 6px;">Category</label>
          <select id="classified-category-input" required style="width: 100%; padding: 10px 14px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; color: #0f172a; outline: none; font-family: inherit;">
            <option value="Musician Availability">Musician Availability</option>
            <option value="Sub Wanted">Sub Wanted</option>
            <option value="Gear for Sale">Gear for Sale</option>
            <option value="Gig Share">Gig Share</option>
          </select>
        </div>

        <!-- Title -->
        <div>
          <label for="classified-title-input" style="display: block; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; margin-bottom: 6px;">Title</label>
          <input type="text" id="classified-title-input" placeholder="e.g. Vintage Fender Rhodes Mark I or Touring Drummer Available..." required style="width: 100%; padding: 10px 14px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; color: #0f172a; outline: none; box-sizing: border-box; font-family: inherit;">
        </div>

        <!-- Price & City / Region (Row) -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
          <div>
            <label for="classified-price-input" style="display: block; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; margin-bottom: 6px;">Price (Optional, $)</label>
            <input type="number" id="classified-price-input" min="0" step="any" placeholder="e.g. 450" style="width: 100%; padding: 10px 14px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; color: #0f172a; outline: none; box-sizing: border-box; font-family: inherit;">
          </div>
          <div>
            <label for="classified-city-input" style="display: block; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; margin-bottom: 6px;">City / Region</label>
            <input type="text" id="classified-city-input" placeholder="e.g. Austin, TX or Toronto, ON" style="width: 100%; padding: 10px 14px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; color: #0f172a; outline: none; box-sizing: border-box; font-family: inherit;">
          </div>
        </div>

        <!-- Description -->
        <div>
          <label for="classified-description-input" style="display: block; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; margin-bottom: 6px;">Description</label>
          <textarea id="classified-description-input" rows="4" placeholder="Describe the gear condition, technical specs, tour dates, or audition requirements..." required style="width: 100%; padding: 10px 14px; font-size: 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; color: #0f172a; outline: none; box-sizing: border-box; resize: vertical; font-family: inherit;"></textarea>
        </div>

        <!-- Drag and drop / file selector (up to 4 images, max 5MB each) -->
        <div>
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
            <label style="font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase;">Photos (Max 4 images, 5MB each)</label>
            <span id="classified-images-counter" style="font-size: 12px; color: #64748b; font-weight: 600;">0/4 photos</span>
          </div>
          <div id="classified-dropzone" class="classified-dropzone" style="border: 2px dashed #cbd5e1; border-radius: 12px; padding: 22px; text-align: center; background: #f8fafc; cursor: pointer; transition: all 0.15s ease;" onclick="document.getElementById('classified-file-input').click()">
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#64748b" stroke-width="1.8" style="margin: 0 auto 6px auto; display: block;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
            <div style="font-size: 13px; font-weight: 700; color: #0f172a; margin-bottom: 2px;">Drag and drop photos here, or click to browse</div>
            <div style="font-size: 11px; color: #64748b;">Supports JPG, PNG, WEBP up to 5MB each</div>
          </div>
          <input type="file" id="classified-file-input" multiple accept="image/*" style="display: none;" onchange="handleClassifiedFileSelect(event)">
          <!-- Instant Image Preview Cards -->
          <div id="classified-previews-container" style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-top: 12px;"></div>
        </div>

        <!-- Modal Footer -->
        <div style="display: flex; justify-content: flex-end; gap: 10px; padding-top: 14px; border-top: 1px solid #e2e8f0;">
          <button type="button" onclick="closePostClassifiedModal()" style="background: #ffffff; border: 1px solid #cbd5e1; color: #334155; padding: 10px 18px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">Cancel</button>
          <button type="submit" id="btn-submit-classified" style="background: #d97706; color: #ffffff; border: none; padding: 10px 22px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer; transition: background 0.15s ease; box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);">Publish Listing</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Classified Lightbox Modal -->
  <div class="modal-overlay" id="directory-lightbox-modal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.85); z-index: 99999; align-items: center; justify-content: center; backdrop-filter: blur(4px);" onclick="closeDirectoryLightbox()">
    <div style="position: relative; max-width: 90vw; max-height: 90vh; display: flex; flex-direction: column; align-items: center;" onclick="event.stopPropagation()">
      <button type="button" onclick="closeDirectoryLightbox()" style="position: absolute; top: -45px; right: 0; background: #ffffff; color: #0f172a; border: 1px solid #e2e8f0; border-radius: 9999px; width: 36px; height: 36px; font-weight: bold; font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">&times;</button>
      <img id="directory-lightbox-img" src="" alt="Enlarged Listing Photo" style="max-width: 90vw; max-height: 85vh; object-fit: contain; border-radius: 12px; border: 2px solid #ffffff; box-shadow: 0 20px 40px rgba(0,0,0,0.4);" />
    </div>
  </div>

  <script>
    function escapeHtml(str) {
      if (!str) return '';
      return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    }

    // ─── Universal Avatar Fallback Engine ──────────────────────────────
    // Absent or broken avatar URLs resolve to a clean inline SVG with the
    // user's capitalized two-letter initials on a slate-100 (#f1f5f9)
    // background. Onerror handlers tear down first: zero recursion.
    const DEFAULT_AVATAR_SVG = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' fill='%2394a3b8'><rect width='64' height='64' fill='%23f1f5f9'/><circle cx='32' cy='24' r='12'/><path d='M16 54c0-8.8 7.2-16 16-16s16 7.2 16 16z'/></svg>";

    /**
     * Extracts capitalized user initials (up to 2 letters) from a user or ensemble name.
     */
    function getInitials(name) {
      if (!name || typeof name !== 'string') return '';
      const parts = name.trim().split(/\s+/).filter(Boolean);
      if (parts.length === 0) return '';
      if (parts.length === 1) {
        const letters = parts[0].replace(/[^a-zA-Z0-9]/g, '');
        return (letters.slice(0, 2) || parts[0].slice(0, 2)).toUpperCase();
      }
      const first = parts[0].replace(/[^a-zA-Z0-9]/g, '')[0] || parts[0][0];
      const last = parts[parts.length - 1].replace(/[^a-zA-Z0-9]/g, '')[0] || parts[parts.length - 1][0];
      return (first + last).toUpperCase();
    }

    /**
     * Inline SVG data-URI avatar with the user's capitalized initials on slate-100.
     */
    function getInitialsAvatarSvg(name) {
      const initials = getInitials(name);
      if (!initials) return DEFAULT_AVATAR_SVG;
      return `data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><rect width='64' height='64' fill='%23f1f5f9'/><text x='32' y='36' font-family='Plus Jakarta Sans, -apple-system, sans-serif' font-size='22' font-weight='700' fill='%23475569' text-anchor='middle' dominant-baseline='central'>${initials}</text></svg>`;
    }

    /**
     * Universal Avatar URL Resolver: valid http(s)/relative/data URLs pass
     * through; anything absent/invalid falls back to the user's initials SVG.
     */
    function getAvatarUrl(avatarUrl, name) {
      if (avatarUrl && typeof avatarUrl === 'string') {
        const trimmed = avatarUrl.trim();
        if (
          (trimmed.startsWith('http://') ||
           trimmed.startsWith('https://') ||
           trimmed.startsWith('/') ||
           trimmed.startsWith('data:image/')) &&
          !trimmed.includes('undefined') &&
          !trimmed.includes('null')
        ) {
          return trimmed;
        }
      }
      return getInitialsAvatarSvg((name || '').toString());
    }

    /**
     * Universal onerror fallback: initials SVG, single-fire, zero recursion.
     */
    function applyAvatarFallback(img) {
      if (!img) return;
      img.onerror = null;
      if (img.dataset && !img.dataset.avatarFallbackApplied) {
        img.dataset.avatarFallbackApplied = 'true';
      }
      const name = (img.dataset && img.dataset.avatarName) || (img.alt && img.alt !== 'Avatar' ? img.alt : '');
      img.src = getInitialsAvatarSvg(name || '');
    }
    window.applyAvatarFallback = applyAvatarFallback;
    window.getInitialsAvatarSvg = getInitialsAvatarSvg;
    window.getAvatarUrl = getAvatarUrl;

    const STATE = {
      query: '',
      role: 'all',
      instrument: '',
      category: 'ALL',
      roleTag: '',
      location: '',
      available: false,
      activeTargetSlug: '',
      activeTargetType: 'musician'
    };

    let debounceTimer = null;
    // Defensive taxonomy access: /js/directory.js loads after this inline block,
    // so resolve lazily inside handlers (never at parse time).
    function talentTaxonomy() {
      return (typeof window !== 'undefined' && window.DirectoryTalentTaxonomy) || null;
    }

    async function fetchDirectoryProfiles() {
      const container = document.getElementById('directory-cards-container');
      const params = new URLSearchParams();

      if (STATE.query) params.set('query', STATE.query);
      if (STATE.role && STATE.role !== 'all') params.set('role', STATE.role);
      if (STATE.instrument) params.set('instrument', STATE.instrument);
      if (STATE.category && STATE.category !== 'ALL') params.set('category', STATE.category);
      if (STATE.roleTag) params.set('roleTag', STATE.roleTag);
      if (STATE.location) params.set('location', STATE.location);
      if (STATE.available) params.set('available', 'true');

      try {
        const response = await fetch(`/api/directory?${params.toString()}`);
        const data = await response.json();

        if (!data.success || !Array.isArray(data.profiles)) {
          renderEmptyState('Failed to load talent profiles. Please try again.');
          return;
        }

        renderProfiles(data.profiles);
        updateStats(data.profiles);
      } catch (err) {
        console.error('Directory fetch error:', err);
        renderEmptyState('Network error connecting to discovery directory.');
      }
    }

    function updateStats(profiles) {
      const totalEl = document.getElementById('stats-total-talent');
      const availEl = document.getElementById('stats-available-subs');

      if (totalEl) totalEl.textContent = profiles.length;
      if (availEl) {
        const availCount = profiles.filter(p => p.isAvailableForHire).length;
        availEl.textContent = availCount;
      }
    }

    function renderEmptyState(message = 'No matching talent found.') {
      const container = document.getElementById('directory-cards-container');
      container.innerHTML = `
        <div class="empty-directory-card">
          <h3>No Profiles Found</h3>
          <p>${escapeHtml(message)}</p>
          <button type="button" class="nav-btn nav-btn-outline" style="margin-top: 14px;" onclick="resetFilters()">Reset All Filters</button>
        </div>
      `;
    }

    function renderProfiles(profiles) {
      const container = document.getElementById('directory-cards-container');
      if (!profiles || profiles.length === 0) {
        renderEmptyState('No talent matched your current search filters. Try another talent domain category, sub-role pill, or query.');
        return;
      }

      container.innerHTML = profiles.map(p => {
        const avatar = getAvatarUrl(p.avatarUrl || p.avatar, p.name);
        const tax = talentTaxonomy();
        const typeBadge = tax ? tax.typeBadge(p) : (p.type === 'crew' ? 'Production & Crew' : (p.type === 'musician' ? 'Musician' : (p.type === 'band' ? 'Band / Act' : 'Venue')));
        const craftBadgeText = tax ? tax.craftBadge(p) : (p.primaryCraft || typeBadge);
        const craftClass = (p.talentCategory === 'CREW_PRODUCTION' || p.type === 'crew') ? 'craft-crew'
          : (p.talentCategory === 'COMEDY' ? 'craft-comedy'
          : (p.talentCategory === 'ACTING' ? 'craft-acting'
          : (p.talentCategory === 'VARIETY' ? 'craft-variety' : '')));
        const skillShelfLabel = tax ? tax.shelfLabel(p) : 'Primary Instruments & Skills';
        const instruments = Array.isArray(p.instruments) && p.instruments.length > 0 ? p.instruments : ['Live Talent'];
        const roleTags = Array.isArray(p.roleTags) ? p.roleTags : [];
        const skillTags = roleTags.length > 0 ? roleTags.concat(instruments.filter(i => !roleTags.includes(i))) : instruments;
        const bands = Array.isArray(p.currentBands) && p.currentBands.length > 0 ? p.currentBands : [];
        const isAvail = p.isAvailableForHire !== false;
        const profileUrl = p.profileUrl || (p.type === 'musician' ? `/musician-profile.html?slug=${encodeURIComponent(p.slug)}` : `/band-profile.html?slug=${encodeURIComponent(p.slug)}`);

        return `
          <article class="talent-card">
            <div class="talent-card-header">
              <div class="talent-avatar-wrap">
                <img src="${escapeHtml(avatar)}" alt="${escapeHtml(p.name)}" class="talent-avatar" loading="lazy" data-avatar-name="${escapeHtml(p.name || '')}" onerror="applyAvatarFallback(this)">
                <div class="talent-avail-dot ${isAvail ? '' : 'busy'}" title="${isAvail ? 'Available for Gigs / Subs' : 'Currently Booked'}"></div>
              </div>
              <div class="talent-header-meta">
                <div class="talent-name-row">
                  <a href="${escapeHtml(profileUrl)}" class="talent-name" title="${escapeHtml(p.name)}">${escapeHtml(p.name)}</a>
                  <span class="talent-role-badge">${escapeHtml(typeBadge)}</span>
                </div>
                <div class="talent-location">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                    <circle cx="12" cy="10" r="3"></circle>
                  </svg>
                  <span>${escapeHtml(p.location || 'Touring Circuit')}</span>
                </div>
                ${isAvail ? `<span style="font-size: 11px; font-weight: 700; color: #059669;">Available for Gigs / Subs</span>` : `<span style="font-size: 11px; font-weight: 700; color: #d97706;">Active Touring</span>`}
              </div>
            </div>

            <div class="talent-card-body">
              ${p.bio ? `<p class="talent-bio">${escapeHtml(p.bio)}</p>` : ''}

              <div class="craft-badge-row" style="margin-bottom: 10px; display: flex; gap: 6px; flex-wrap: wrap; align-items: center;">
                <span class="talent-role-badge craft-badge ${craftClass}" title="Primary Craft">${escapeHtml(craftBadgeText)}</span>
                ${(p.reviewCount && p.reviewCount > 0) ? `
                  <span class="reputation-pill" style="font-size: 11px; font-weight: 700; color: #b45309; background: #fffbeb; border: 1px solid #fde68a; padding: 2px 8px; border-radius: 9999px;">
                    ${Number(p.ratingAverage || 5.0).toFixed(1)} rating across ${p.reviewCount} verified show${p.reviewCount === 1 ? '' : 's'}
                  </span>
                ` : ''}
              </div>

              <div>
                <div class="shelf-label">${escapeHtml(skillShelfLabel)}</div>
                <div class="instruments-shelf">
                  ${skillTags.slice(0, 4).map(inst => `<span class="badge-pill-inst">${escapeHtml(cleanBracketTags(inst))}</span>`).join('')}
                  ${skillTags.length > 4 ? `<span class="badge-pill-inst" style="background:#f1f5f9; border-color:#cbd5e1; color:#475569;">+${skillTags.length - 4}</span>` : ''}
                </div>
              </div>

              ${bands.length > 0 ? `
                <div>
                  <div class="shelf-label">Current Bands &amp; Acts</div>
                  <div class="bands-shelf-list">
                    ${bands.slice(0, 3).map(b => `<span class="band-affiliation-tag">${escapeHtml(cleanBracketTags(b))}</span>`).join('')}
                  </div>
                </div>
              ` : ''}
            </div>

            <div class="talent-card-footer" style="display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: wrap;">
              <a href="${escapeHtml(profileUrl)}" class="btn-card-action btn-card-outline" style="flex: 1; text-align: center; min-width: 80px;">Profile</a>
              <button 
                type="button" 
                class="btn-card-action btn-card-primary" 
                onclick="openConnectModal('${escapeHtml(p.slug)}', '${escapeHtml(p.name)}', '${escapeHtml(p.type)}')"
                style="flex: 1; min-width: 120px;"
              >
                Connect / Inquire
              </button>
              <button 
                type="button" 
                class="btn-card-action btn-card-follow" 
                id="dir-follow-btn-${escapeHtml(p.slug || p.id)}"
                data-target-id="${escapeHtml(p.userId || p.id || p.slug)}"
                data-target-type="${p.type === 'band' ? 'BAND' : 'USER'}"
                data-craft-type="${escapeHtml(p.type || 'musician')}"
                data-talent-category="${escapeHtml(p.talentCategory || '')}"
                data-primary-craft="${escapeHtml(p.primaryCraft || '')}"
                onclick="handleDirectoryFollow(this, '${escapeHtml(p.userId || p.id || p.slug)}', '${p.type === 'band' ? 'BAND' : 'USER'}')"
                style="background: #ffffff; border: 1px solid #e2e8f0; color: #0f172a; padding: 8px 14px; border-radius: 8px; font-size: 12px; font-weight: 700; cursor: pointer; transition: all 0.15s ease; white-space: nowrap;"
              >
                Follow
              </button>
            </div>
          </article>
        `;
      }).join('');

      if (typeof window.initDirectoryFollowStates === 'function') {
        window.initDirectoryFollowStates();
      }
    }

    function resetFilters() {
      STATE.query = '';
      STATE.role = 'all';
      STATE.instrument = '';
      STATE.category = 'ALL';
      STATE.roleTag = '';
      STATE.location = '';
      STATE.available = false;

      document.getElementById('search-input').value = '';
      document.getElementById('location-select').value = '';
      document.getElementById('available-toggle').checked = false;

      document.querySelectorAll('.category-chip').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.cat === 'ALL');
      });
      renderSubRolePills('ALL', true);

      fetchDirectoryProfiles();
    }

    /**
     * Renders the sub-role pill rack for the active talent domain category.
     * When autoSelectFirst is true the first pill ("All Roles") is activated immediately.
     */
    function renderSubRolePills(categoryKey, autoSelectFirst = false) {
      const container = document.getElementById('role-pills-container');
      const tax = talentTaxonomy();
      let pills;
      if (tax && typeof tax.rolePillsForCategory === 'function') {
        pills = tax.rolePillsForCategory(categoryKey) || [];
      } else {
        pills = [{ label: 'All Roles', role: 'all', inst: '' }];
      }

      container.innerHTML = pills.map((pill) => `
        <button type="button" class="filter-pill${autoSelectFirst && pill.role === 'all' ? ' active' : ''}" data-role="${pill.role || 'all'}" data-inst="${pill.inst || ''}" data-tag="${pill.tag || ''}">${pill.label}</button>
      `).join('');
    }

    // Modal Interaction
    const modal = document.getElementById('connect-modal-overlay');
    const closeBtn = document.getElementById('connect-close-btn');
    const cancelBtn = document.getElementById('connect-cancel-btn');
    const form = document.getElementById('connect-inquiry-form');
    const alertBox = document.getElementById('connect-status-alert');

    function openConnectModal(slug, name, type) {
      STATE.activeTargetSlug = slug;
      STATE.activeTargetType = type;

      document.getElementById('connect-modal-title').textContent = `Connect with ${name}`;
      alertBox.className = 'status-alert';
      alertBox.style.display = 'none';

      const nextWeek = new Date();
      nextWeek.setDate(nextWeek.getDate() + 7);
      document.getElementById('connect-date').value = nextWeek.toISOString().split('T')[0];

      modal.style.display = 'flex';
    }

    function closeConnectModal() {
      modal.style.display = 'none';
    }

    closeBtn.addEventListener('click', closeConnectModal);
    cancelBtn.addEventListener('click', closeConnectModal);
    modal.addEventListener('click', (e) => {
      if (e.target === modal) closeConnectModal();
    });

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const submitBtn = document.getElementById('connect-submit-btn');
      submitBtn.disabled = true;
      submitBtn.textContent = 'Transmitting...';

      const payload = {
        gigDate: document.getElementById('connect-date').value,
        eventType: document.getElementById('connect-type').value,
        venueName: document.getElementById('connect-venue').value,
        offeredFee: document.getElementById('connect-fee').value,
        message: document.getElementById('connect-message').value,
      };

      try {
        const endpoint = STATE.activeTargetType === 'musician'
          ? `/api/musicians/${encodeURIComponent(STATE.activeTargetSlug)}/inquiry`
          : `/api/bands/${encodeURIComponent(STATE.activeTargetSlug)}/inquiry`;

        const res = await fetch(endpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify(payload)
        });
        const result = await res.json();

        if (res.ok && result.success) {
          alertBox.className = 'status-alert success';
          alertBox.textContent = 'Inquiry transmitted successfully. You will be alerted upon review.';
          alertBox.style.display = 'block';
          form.reset();
          setTimeout(() => {
            closeConnectModal();
            submitBtn.disabled = false;
            submitBtn.textContent = 'Send Inquiry';
          }, 1800);
        } else {
          alertBox.className = 'status-alert error';
          alertBox.textContent = result.error || 'Failed to submit inquiry. Please sign in and try again.';
          alertBox.style.display = 'block';
          submitBtn.disabled = false;
          submitBtn.textContent = 'Send Inquiry';
        }
      } catch (err) {
        alertBox.className = 'status-alert error';
        alertBox.textContent = 'Network error while transmitting inquiry.';
        alertBox.style.display = 'block';
        submitBtn.disabled = false;
        submitBtn.textContent = 'Send Inquiry';
      }
    });

    // Event Listeners for Filters
    document.addEventListener('DOMContentLoaded', () => {
      // Search input
      const searchInput = document.getElementById('search-input');
      searchInput.addEventListener('input', (e) => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
          STATE.query = e.target.value.trim();
          fetchDirectoryProfiles();
        }, 250);
      });

      // Location filter
      const locationSelect = document.getElementById('location-select');
      locationSelect.addEventListener('change', (e) => {
        STATE.location = e.target.value;
        fetchDirectoryProfiles();
      });

      // Available toggle
      const availableToggle = document.getElementById('available-toggle');
      availableToggle.addEventListener('change', (e) => {
        STATE.available = e.target.checked;
        fetchDirectoryProfiles();
      });

      // Talent Domain Category Chips — swap the sub-role pill rack and refetch
      const categoryChips = document.querySelectorAll('.category-chip');
      categoryChips.forEach(chip => {
        chip.addEventListener('click', () => {
          categoryChips.forEach(c => c.classList.remove('active'));
          chip.classList.add('active');

          STATE.category = chip.dataset.cat || 'ALL';
          STATE.roleTag = '';
          STATE.role = 'all';
          STATE.instrument = '';
          renderSubRolePills(STATE.category, true);
          fetchDirectoryProfiles();
        });
      });

      // Sub-Role & Instrument Pills (event delegation: rack re-renders per category)
      const pillsRow = document.getElementById('role-pills-container');
      pillsRow.addEventListener('click', (e) => {
        const pill = e.target.closest('.filter-pill');
        if (!pill) return;
        pillsRow.querySelectorAll('.filter-pill').forEach(p => p.classList.remove('active'));
        pill.classList.add('active');

        STATE.role = pill.dataset.role || 'all';
        STATE.instrument = pill.dataset.inst || '';
        STATE.roleTag = pill.dataset.tag || '';
        fetchDirectoryProfiles();
      });

      // Initial Fetch & Nav Avatar Sync
      fetchDirectoryProfiles();
      syncNavUserAvatar();
      initClassifiedDropzone();

      if (window.location.hash === '#classifieds' || new URLSearchParams(window.location.search).get('view') === 'classifieds') {
        switchDirectoryView('classifieds');
      }
    });

    // ====================================================
    // Classifieds & Gear Marketplace Subsystem
    // ====================================================
    let CURRENT_DIRECTORY_USER = null;
    let activeClassifiedCategory = 'ALL';
    let activeClassifiedSearch = '';
    let classifiedSearchDebounce = null;
    let classifiedSelectedFiles = [];

    function cleanBracketTags(str) {
      if (!str || typeof str !== 'string') return str || '';
      let cleaned = str.replace(/\[DEMO\]\s*(.+)/i, '$1 Demo');
      cleaned = cleaned.replace(/\[(.*?)\]/g, '$1');
      cleaned = cleaned.replace(/[\[\]]/g, '');
      return cleaned.trim();
    }

    function maskContactDetails(text) {
      if (!text || typeof text !== 'string') return text || '';
      const emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
      const phoneRegex = /(?:\+?\d{1,3}[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b|\b\+?\d{1,4}[-.\s]\d{1,4}[-.\s]\d{3,9}\b/g;
      return text.replace(emailRegex, '(email protected)').replace(phoneRegex, '(phone masked)');
    }

    window.switchDirectoryView = function (view, event) {
      if (event) event.preventDefault();
      const talentSection = document.getElementById('directory-talent-section');
      const classifiedsSection = document.getElementById('directory-classifieds-section');
      const railTalent = document.getElementById('rail-link-directory');
      const railClassifieds = document.getElementById('rail-link-classifieds');

      if (view === 'classifieds') {
        if (talentSection) talentSection.style.display = 'none';
        if (classifiedsSection) classifiedsSection.style.display = 'block';
        if (railTalent) railTalent.classList.remove('active');
        if (railClassifieds) railClassifieds.classList.add('active');

        if (window.location.hash !== '#classifieds') {
          history.replaceState(null, '', '#classifieds');
        }
        fetchClassifieds();
      } else {
        if (talentSection) talentSection.style.display = 'block';
        if (classifiedsSection) classifiedsSection.style.display = 'none';
        if (railTalent) railTalent.classList.add('active');
        if (railClassifieds) railClassifieds.classList.remove('active');

        if (window.location.hash === '#classifieds') {
          history.replaceState(null, '', window.location.pathname);
        }
      }
    };

    window.setDirectoryViewTab = function (view) {
      switchDirectoryView(view);
      const talentTab = document.getElementById('view-tab-talent');
      const classifiedsTab = document.getElementById('view-tab-classifieds');
      if (talentTab && classifiedsTab) {
        talentTab.classList.toggle('active', view !== 'classifieds');
        talentTab.setAttribute('aria-selected', view !== 'classifieds' ? 'true' : 'false');
        classifiedsTab.classList.toggle('active', view === 'classifieds');
        classifiedsTab.setAttribute('aria-selected', view === 'classifieds' ? 'true' : 'false');
      }
    };

    window.filterClassifiedCategory = function (category, buttonEl) {
      activeClassifiedCategory = category || 'ALL';
      const pills = document.querySelectorAll('#classifieds-pills-bar .classified-pill');
      pills.forEach(p => p.classList.remove('active'));
      if (buttonEl) buttonEl.classList.add('active');
      fetchClassifieds();
    };

    window.handleClassifiedSearchDebounced = function (val) {
      clearTimeout(classifiedSearchDebounce);
      classifiedSearchDebounce = setTimeout(() => {
        activeClassifiedSearch = (val || '').trim();
        fetchClassifieds();
      }, 300);
    };

    async function fetchClassifieds() {
      const container = document.getElementById('directory-classifieds-stream');
      if (!container) return;
      container.innerHTML = `
        <div style="background: #ffffff; border: 1px solid var(--border-porcelain); border-radius: 16px; padding: 36px 20px; text-align: center; color: var(--text-muted);">
          <div>Loading classified listings...</div>
        </div>`;

      try {
        const params = new URLSearchParams();
        if (activeClassifiedCategory && activeClassifiedCategory !== 'ALL') {
          params.set('category', activeClassifiedCategory);
        }
        if (activeClassifiedSearch) {
          params.set('search', activeClassifiedSearch);
        }

        const res = await fetch(`/api/classifieds?${params.toString()}`, {
          headers: { Accept: 'application/json' },
          credentials: 'include',
        });
        const data = await res.json();

        if (data.success && Array.isArray(data.listings) && data.listings.length > 0) {
          renderClassifiedsListings(data.listings);
        } else {
          renderClassifiedsEmptyState();
        }
      } catch (err) {
        console.error('[Directory Classifieds Error]:', err);
        container.innerHTML = `
          <div style="background: #ffffff; border: 1px solid #fee2e2; border-radius: 16px; padding: 32px 20px; text-align: center; color: #b91c1c;">
            <div>Failed to load classifieds. Please check network connection.</div>
          </div>`;
      }
    }

    function renderClassifiedsEmptyState() {
      const container = document.getElementById('directory-classifieds-stream');
      if (!container) return;
      container.innerHTML = `
        <div class="classifieds-empty-card" style="background: #ffffff; border: 1px dashed #cbd5e1; border-radius: 16px; padding: 48px 24px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.04);">
          <div style="width: 52px; height: 52px; border-radius: 50%; background: #fef3c7; color: #d97706; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px auto;">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path>
              <circle cx="7" cy="7" r="1.5"></circle>
            </svg>
          </div>
          <h3 style="font-size: 16px; font-weight: 800; color: #0f172a; margin: 0 0 8px 0; font-family: 'Plus Jakarta Sans', sans-serif;">No classifieds posted yet. Be the first musician to advertise gear or availability.</h3>
          <p style="font-size: 13px; color: var(--text-muted); margin: 0 0 20px 0; max-width: 480px; margin-left: auto; margin-right: auto; line-height: 1.5;">
            Advertise touring instrument availability, session subbing, vintage hardware for sale, or local rehearsal studio shares.
          </p>
          <button type="button" onclick="handleOpenClassifiedModal()" style="background: var(--accent-amber); color: #ffffff; border: none; border-radius: 12px; padding: 10px 22px; font-size: 13px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; box-shadow: 0 2px 6px rgba(217, 119, 6, 0.25);">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
            <span>Post Classified</span>
          </button>
        </div>`;
    }

    function getCategoryBadgeStyles(cat) {
      const upper = (cat || '').toUpperCase();
      if (upper.includes('SUB')) {
        return { bg: '#fef3c7', text: '#b45309', border: '#fde68a', label: 'Sub Wanted' };
      }
      if (upper.includes('GEAR')) {
        return { bg: '#f1f5f9', text: '#334155', border: '#cbd5e1', label: 'Gear for Sale' };
      }
      if (upper.includes('AVAILABILITY') || upper.includes('MUSICIAN')) {
        return { bg: '#ecfdf5', text: '#047857', border: '#a7f3d0', label: 'Musician Availability' };
      }
      if (upper.includes('GIG')) {
        return { bg: '#eff6ff', text: '#1d4ed8', border: '#bfdbfe', label: 'Gig Share' };
      }
      return { bg: '#f8fafc', text: '#475569', border: '#e2e8f0', label: cat || 'Classified' };
    }

    function formatPriceDisplay(priceCents) {
      if (priceCents === null || priceCents === undefined || priceCents === '') return null;
      const cents = Number(priceCents);
      if (isNaN(cents) || cents < 0) return null;
      const dollars = cents >= 100 ? (cents / 100) : cents;
      return '$' + dollars.toLocaleString('en-US', {
        minimumFractionDigits: (cents % 100 === 0 ? 0 : 2),
        maximumFractionDigits: 2,
      });
    }

    function renderClassifiedGallery(images) {
      if (!images || !Array.isArray(images) || images.length === 0) return '';
      const validImgs = images.filter(Boolean).slice(0, 4);
      if (validImgs.length === 0) return '';

      if (validImgs.length === 1) {
        return `
          <div style="margin: 14px 0; border-radius: 12px; overflow: hidden; background: #f1f5f9; max-height: 320px; cursor: pointer; border: 1px solid var(--border-porcelain);" onclick="openDirectoryLightbox('${escapeHtml(validImgs[0])}')">
            <img src="${escapeHtml(validImgs[0])}" alt="Classified photo" style="width: 100%; height: 100%; max-height: 320px; object-fit: cover; display: block;" loading="lazy">
          </div>`;
      }
      if (validImgs.length === 2) {
        return `
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin: 14px 0;">
            ${validImgs.map(img => `
              <div style="border-radius: 10px; overflow: hidden; background: #f1f5f9; height: 180px; cursor: pointer; border: 1px solid var(--border-porcelain);" onclick="openDirectoryLightbox('${escapeHtml(img)}')">
                <img src="${escapeHtml(img)}" alt="Classified photo" style="width: 100%; height: 100%; object-fit: cover; display: block;" loading="lazy">
              </div>
            `).join('')}
          </div>`;
      }
      if (validImgs.length === 3) {
        return `
          <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin: 14px 0;">
            <div style="border-radius: 10px; overflow: hidden; background: #f1f5f9; height: 190px; cursor: pointer; border: 1px solid var(--border-porcelain);" onclick="openDirectoryLightbox('${escapeHtml(validImgs[0])}')">
              <img src="${escapeHtml(validImgs[0])}" alt="Classified photo" style="width: 100%; height: 100%; object-fit: cover; display: block;" loading="lazy">
            </div>
            <div style="display: flex; flex-direction: column; gap: 8px;">
              ${validImgs.slice(1, 3).map(img => `
                <div style="border-radius: 10px; overflow: hidden; background: #f1f5f9; height: 91px; cursor: pointer; border: 1px solid var(--border-porcelain);" onclick="openDirectoryLightbox('${escapeHtml(img)}')">
                  <img src="${escapeHtml(img)}" alt="Classified photo" style="width: 100%; height: 100%; object-fit: cover; display: block;" loading="lazy">
                </div>
              `).join('')}
            </div>
          </div>`;
      }
      return `
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin: 14px 0;">
          ${validImgs.map(img => `
            <div style="border-radius: 10px; overflow: hidden; background: #f1f5f9; height: 130px; cursor: pointer; border: 1px solid var(--border-porcelain);" onclick="openDirectoryLightbox('${escapeHtml(img)}')">
              <img src="${escapeHtml(img)}" alt="Classified photo" style="width: 100%; height: 100%; object-fit: cover; display: block;" loading="lazy">
            </div>
          `).join('')}
        </div>`;
    }

    function renderClassifiedsListings(listings) {
      const container = document.getElementById('directory-classifieds-stream');
      if (!container) return;

      container.innerHTML = listings.map(l => {
        const author = l.author || {};
        const authorName = cleanBracketTags(author.name || 'Musician');
        const avatarUrl = getAvatarUrl(author.avatarUrl || author.image, authorName);
        const isVerified = Boolean(author.isVerified);
        const badgeCfg = getCategoryBadgeStyles(l.category);
        const formattedPrice = formatPriceDisplay(l.priceCents);
        const locationTag = l.city || l.location || '';
        const galleryHtml = renderClassifiedGallery(l.images);

        return `
          <article class="classified-card" data-listing-id="${escapeHtml(l.id)}">
            <!-- Author & Category Meta Header -->
            <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 12px;">
              <div style="display: flex; align-items: center; gap: 10px; min-width: 0;">
                <img src="${escapeHtml(avatarUrl)}" alt="${escapeHtml(authorName)}" data-avatar-name="${escapeHtml(authorName)}" style="width: 44px; height: 44px; border-radius: 50%; object-fit: cover; border: 1px solid var(--border-porcelain); flex-shrink: 0;" onerror="applyAvatarFallback(this)">
                <div style="min-width: 0;">
                  <div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
                    <span style="font-size: 14px; font-weight: 800; color: #0f172a; font-family: 'Plus Jakarta Sans', sans-serif;">${escapeHtml(authorName)}</span>
                    ${isVerified ? `<span style="display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; border-radius: 50%; background: var(--accent-amber); color: #ffffff; font-size: 10px; font-weight: 800;" title="Verified Artist">&#10003;</span>` : ''}
                    <span style="background: ${badgeCfg.bg}; color: ${badgeCfg.text}; border: 1px solid ${badgeCfg.border}; padding: 2px 8px; border-radius: 9999px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">${escapeHtml(cleanBracketTags(badgeCfg.label))}</span>
                  </div>
                  <div style="font-size: 12px; color: var(--text-muted); margin-top: 2px; display: flex; align-items: center; gap: 8px;">
                    <span>Active Listing</span>
                    ${locationTag ? `<span>&bull;</span><span style="display: inline-flex; align-items: center; gap: 3px;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg>${escapeHtml(cleanBracketTags(locationTag))}</span>` : ''}
                  </div>
                </div>
              </div>

              <!-- Price display badge (formatted in USD/CAD, e.g. $450) -->
              ${formattedPrice ? `
                <div style="background: #f8fafc; border: 1px solid var(--border-porcelain); border-radius: 10px; padding: 6px 12px; font-family: 'Plus Jakarta Sans', sans-serif; font-size: 15px; font-weight: 800; color: #0f172a; white-space: nowrap;">
                  ${escapeHtml(formattedPrice)}
                </div>
              ` : ''}
            </div>

            <!-- Title & Description -->
            <h3 style="font-size: 16px; font-weight: 800; color: #0f172a; margin: 0 0 8px 0; font-family: 'Plus Jakarta Sans', sans-serif;">${escapeHtml(cleanBracketTags(l.title))}</h3>
            <div style="font-size: 14px; color: #334155; line-height: 1.6; margin: 0 0 14px 0; white-space: pre-line;">${escapeHtml(cleanBracketTags(maskContactDetails(l.description)))}</div>

            <!-- Image Gallery Grid (supports up to 4 images with thumbnail lightbox zoom) -->
            ${galleryHtml}

            <!-- Direct Action Bar -->
            <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border-porcelain);">
              <span style="font-size: 12px; color: var(--text-muted); font-weight: 600;">Direct Musician Inquiry</span>
              <button
                type="button"
                class="btn-inquire-classified"
                onclick="handleClassifiedInquire('${escapeHtml(l.id)}', '${escapeHtml(cleanBracketTags(authorName))}', '${escapeHtml(cleanBracketTags(l.title))}', '${escapeHtml(cleanBracketTags(badgeCfg.label))}')"
                style="background: #ffffff; border: 1px solid #cbd5e1; color: #0f172a; padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer; transition: all 0.15s ease; display: inline-flex; align-items: center; gap: 6px;"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
                <span>Contact / Inquire</span>
              </button>
            </div>
          </article>`;
      }).join('');
    }

    window.handleClassifiedInquire = function (listingId, authorName, title, category) {
      const modal = document.getElementById('connect-modal-overlay');
      if (!modal) return;
      document.getElementById('connect-modal-title').textContent = `Inquire: ${authorName}`;
      document.getElementById('connect-type').value = 'Tour Sub Musician';
      document.getElementById('connect-message').value = `Hello ${authorName}, I am contacting you regarding your classified listing "${title}" (${category}). Let's coordinate details!`;
      modal.style.display = 'flex';
    };

    window.openDirectoryLightbox = function (url) {
      const modal = document.getElementById('directory-lightbox-modal');
      const img = document.getElementById('directory-lightbox-img');
      if (modal && img) {
        img.src = url;
        modal.style.display = 'flex';
      }
    };

    window.closeDirectoryLightbox = function () {
      const modal = document.getElementById('directory-lightbox-modal');
      if (modal) modal.style.display = 'none';
    };

    // Gated Access Check for Classified Posting
    function isUserMusicianOrBand(user) {
      if (!user) return false;
      const role = String(user.role || '').toUpperCase();
      const accType = String(user.accountType || '').toUpperCase();
      const isAdmin = role === 'ADMIN' || accType === 'ADMIN';
      const isMusician = Boolean(user.musicianProfile) || role === 'MUSICIAN' || accType === 'MUSICIAN';
      const isBand = (user.bandMembers && user.bandMembers.length > 0) || (user.managedBands && user.managedBands.length > 0) || role === 'BAND' || accType === 'BAND';
      const isIndustry = ['CREW', 'DJ', 'VENUE', 'AGENT', 'PRODUCER', 'ARTIST'].includes(role) || ['CREW', 'DJ', 'VENUE', 'AGENT', 'PRODUCER', 'ARTIST'].includes(accType);
      return isAdmin || isMusician || isBand || isIndustry;
    }

    window.handleOpenClassifiedModal = function () {
      if (!CURRENT_DIRECTORY_USER || !isUserMusicianOrBand(CURRENT_DIRECTORY_USER)) {
        openClassifiedUpgradeModal();
        return;
      }
      openPostClassifiedModal();
    };

    window.openClassifiedUpgradeModal = function () {
      const modal = document.getElementById('classified-upgrade-modal');
      if (modal) modal.style.display = 'flex';
    };

    window.closeClassifiedUpgradeModal = function () {
      const modal = document.getElementById('classified-upgrade-modal');
      if (modal) modal.style.display = 'none';
    };

    window.openPostClassifiedModal = function () {
      const modal = document.getElementById('post-classified-modal');
      if (modal) modal.style.display = 'flex';
      resetClassifiedForm();
    };

    window.closePostClassifiedModal = function () {
      const modal = document.getElementById('post-classified-modal');
      if (modal) modal.style.display = 'none';
    };

    function showClassifiedFormError(msg) {
      const alertBox = document.getElementById('classified-form-alert');
      if (!alertBox) return;
      alertBox.textContent = msg;
      alertBox.style.display = 'block';
      alertBox.style.background = '#fef2f2';
      alertBox.style.border = '1px solid #fecaca';
      alertBox.style.color = '#b91c1c';
    }

    function resetClassifiedForm() {
      classifiedSelectedFiles = [];
      const form = document.getElementById('post-classified-form');
      if (form) form.reset();
      const alertBox = document.getElementById('classified-form-alert');
      if (alertBox) alertBox.style.display = 'none';
      renderClassifiedPreviews();
    }

    window.handleClassifiedFileSelect = function (event) {
      const files = Array.from(event.target.files || []);
      addClassifiedFiles(files);
      event.target.value = '';
    };

    function addClassifiedFiles(files) {
      const alertBox = document.getElementById('classified-form-alert');
      if (alertBox) alertBox.style.display = 'none';

      for (const file of files) {
        if (!file.type || !file.type.startsWith('image/')) {
          showClassifiedFormError('Only image files (JPG, PNG, WEBP) are supported.');
          continue;
        }
        if (file.size > 5 * 1024 * 1024) {
          showClassifiedFormError(`Image "${file.name}" exceeds 5MB size limit.`);
          continue;
        }
        if (classifiedSelectedFiles.length >= 4) {
          showClassifiedFormError('Maximum 4 images allowed per classified listing.');
          break;
        }
        classifiedSelectedFiles.push(file);
      }
      renderClassifiedPreviews();
    }

    function renderClassifiedPreviews() {
      const container = document.getElementById('classified-previews-container');
      const counter = document.getElementById('classified-images-counter');
      if (counter) counter.textContent = `${classifiedSelectedFiles.length}/4 photos`;
      if (!container) return;

      container.innerHTML = '';
      classifiedSelectedFiles.forEach((file, index) => {
        const card = document.createElement('div');
        card.style.cssText = 'position: relative; border-radius: 10px; overflow: hidden; border: 1px solid #cbd5e1; height: 74px; background: #f1f5f9;';

        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);
        img.alt = file.name;
        img.style.cssText = 'width: 100%; height: 100%; object-fit: cover;';

        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.innerHTML = '&times;';
        removeBtn.title = 'Remove photo';
        removeBtn.style.cssText = 'position: absolute; top: 3px; right: 3px; width: 20px; height: 20px; border-radius: 50%; background: rgba(15, 23, 42, 0.75); color: #ffffff; border: none; font-size: 13px; font-weight: 700; cursor: pointer; display: flex; align-items: center; justify-content: center; line-height: 1;';
        removeBtn.onclick = function (e) {
          e.stopPropagation();
          classifiedSelectedFiles.splice(index, 1);
          renderClassifiedPreviews();
        };

        card.appendChild(img);
        card.appendChild(removeBtn);
        container.appendChild(card);
      });
    }

    // Drag and Drop Attachment Initializer
    function initClassifiedDropzone() {
      const dropzone = document.getElementById('classified-dropzone');
      if (!dropzone) return;

      ['dragenter', 'dragover'].forEach(name => {
        dropzone.addEventListener(name, (e) => {
          e.preventDefault();
          e.stopPropagation();
          dropzone.classList.add('drag-active');
        });
      });

      ['dragleave', 'drop'].forEach(name => {
        dropzone.addEventListener(name, (e) => {
          e.preventDefault();
          e.stopPropagation();
          dropzone.classList.remove('drag-active');
        });
      });

      dropzone.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        const files = dt ? Array.from(dt.files) : [];
        addClassifiedFiles(files);
      });
    }

    window.submitClassifiedListing = async function (event) {
      event.preventDefault();
      const submitBtn = document.getElementById('btn-submit-classified');
      const alertBox = document.getElementById('classified-form-alert');
      if (alertBox) alertBox.style.display = 'none';

      const category = document.getElementById('classified-category-input').value;
      const title = document.getElementById('classified-title-input').value.trim();
      const priceVal = document.getElementById('classified-price-input').value.trim();
      const city = document.getElementById('classified-city-input').value.trim();
      const description = document.getElementById('classified-description-input').value.trim();

      if (!title || !description) {
        showClassifiedFormError('Title and description are required.');
        return;
      }

      submitBtn.disabled = true;
      submitBtn.textContent = 'Publishing...';

      try {
        const formData = new FormData();
        formData.append('category', category);
        formData.append('title', title);
        formData.append('description', description);
        if (city) {
          formData.append('city', city);
          formData.append('location', city);
        }
        if (priceVal) {
          const priceCents = Math.round(parseFloat(priceVal) * 100);
          if (!isNaN(priceCents) && priceCents >= 0) {
            formData.append('priceCents', priceCents);
          }
        }

        classifiedSelectedFiles.forEach(file => {
          formData.append('images', file);
        });

        const res = await fetch('/api/classifieds', {
          method: 'POST',
          body: formData,
          credentials: 'include',
        });

        const data = await res.json();
        if (!res.ok || !data.success) {
          if (res.status === 403 || res.status === 401) {
            closePostClassifiedModal();
            openClassifiedUpgradeModal();
            return;
          }
          throw new Error(data.error || 'Failed to create classified listing.');
        }

        closePostClassifiedModal();
        resetClassifiedForm();
        await fetchClassifieds();
      } catch (err) {
        showClassifiedFormError(err.message || 'Error publishing classified listing.');
      } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Publish Listing';
      }
    };

    // Format Eastern Time (America/Toronto)
    function formatEasternTime(dateInput) {
      if (!dateInput) return '';
      return new Intl.DateTimeFormat('en-US', {
        timeZone: 'America/Toronto',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
        timeZoneName: 'short'
      }).format(new Date(dateInput));
    }

    // Dynamic Navigation Avatar Sync (universal initials fallback engine)
    async function syncNavUserAvatar() {
      try {
        const res = await fetch('/api/auth/session', { credentials: 'include' });
        const data = await res.json();
        if (data && data.user) {
          CURRENT_DIRECTORY_USER = data.user;
        }
        const name = (data.user?.name || data.user?.profile?.name || localStorage.getItem('user_name') || '').trim();
        const candidate = (data.user?.avatarUrl || data.user?.profile?.avatarUrl || localStorage.getItem('user_avatar') || '').trim();
        const hasUsableAvatar = Boolean(
          candidate &&
          candidate !== 'undefined' &&
          candidate !== 'null' &&
          /^(https?:\/\/|\/|data:image\/)/.test(candidate)
        );
        const avatarImg = document.getElementById('topbar-user-avatar') || document.querySelector('.topbar-right img');
        const avatarLink = document.getElementById('topbar-avatar-container') || (avatarImg ? avatarImg.closest('a') : null);

        if (avatarImg) {
          avatarImg.dataset.avatarName = name;
          if (name) {
            avatarImg.alt = name;
            if (avatarLink) avatarLink.title = name;
          }
          if (hasUsableAvatar) {
            // Broken live URLs fall back to the initials SVG via onerror (fires once).
            avatarImg.onerror = function () {
              avatarImg.onerror = null;
              avatarImg.src = getInitialsAvatarSvg(avatarImg.dataset.avatarName || '');
            };
            avatarImg.src = candidate;
            localStorage.setItem('user_avatar', candidate);
          } else {
            avatarImg.onerror = null;
            avatarImg.src = getInitialsAvatarSvg(name);
          }
        }
      } catch (e) {
        const cached = (localStorage.getItem('user_avatar') || '').trim();
        const avatarImg = document.getElementById('topbar-user-avatar') || document.querySelector('.topbar-right img');
        if (avatarImg && cached) {
          avatarImg.onerror = function () {
            avatarImg.onerror = null;
            avatarImg.src = getInitialsAvatarSvg(avatarImg.dataset.avatarName || '');
          };
          avatarImg.src = cached;
        }
      }
    }
  </script>
  <!-- Free-Tier Sponsor & Affiliate Banner Engine (Clean Porcelain Light, gates on session tier) -->
  <script src="/js/ad-banner.js?v=20261106"></script>
  <script src="/js/directory.js"></script>
  <script src="/js/nav-header.js"></script>
  <!-- Universal Global Navigation & Bracket Purge Suite + Slide-Over Cart Drawer
       (Global Top Bar contract: global-nav.js MUST load before cart-drawer.js) -->
  <script src="/js/global-nav.js"></script>
  <script src="/js/cart-drawer.js"></script>
  <script src="/js/issue-reporter.js?v=20261108_a2" defer></script>
</body>
</html>
