<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>xlora_measure — Architectural Sizing & Clearance Portal</title>
  
  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Google Font: Inter -->
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
  <!-- Lucide Icons -->
  <script src="https://unpkg.com/lucide@latest"></script>
  
  <!-- KaTeX for Beautiful LaTeX Math Equations -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
  <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>

  <style>
    body {
      font-family: 'Inter', sans-serif;
    }
    /* Blueprint Graph Paper Pattern background - Soft Light Mode Grid */
    .bg-grid-slate-100 {
      background-size: 20px 20px;
      background-image: 
        linear-gradient(to right, rgba(203, 213, 225, 0.45) 1px, transparent 1px),
        linear-gradient(to bottom, rgba(203, 213, 225, 0.45) 1px, transparent 1px);
    }
    /* Custom Scrollbars optimized for Light Mode */
    .custom-scrollbar::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    .custom-scrollbar::-webkit-scrollbar-track {
      background: rgba(241, 245, 249, 0.8);
    }
    .custom-scrollbar::-webkit-scrollbar-thumb {
      background: rgba(217, 119, 6, 0.25);
      border-radius: 9999px;
    }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover {
      background: rgba(217, 119, 6, 0.5);
    }
    
    /* Dynamic deflection flex visual effect */
    .deflection-beam-base {
      transition: transform 0.3s ease-out;
    }

    /* Screen-only print utilities */
    #printable-workshop-sheet {
      display: none;
    }

    /* Printable overrides */
    @media print {
      body * {
        visibility: hidden !important;
      }
      #printable-workshop-sheet, #printable-workshop-sheet * {
        visibility: visible !important;
        display: block !important;
      }
      #printable-workshop-sheet {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        margin: 0;
        padding: 30px;
        box-shadow: none;
        border: none;
        background: white;
        color: black;
      }
      .screen-only, #workshopPrintOverlay, #toast-container, header, #imageViewerModal {
        display: none !important;
        visibility: hidden !important;
      }
    }
  </style>
</head>
<body class="min-h-screen bg-slate-50 text-slate-800 flex flex-col selection:bg-amber-100 selection:text-amber-900 bg-grid-slate-100">

  <!-- ==========================================
        GLOBAL HEADER / BRAND BANNER
        ========================================== -->
  <header class="border-b border-slate-200 bg-white/90 backdrop-blur-md sticky top-0 z-30 px-4 py-4 transition-all screen-only shadow-sm">
    <div class="max-w-7xl mx-auto flex items-center justify-between">
      <div class="flex items-center gap-3">
        <div class="bg-gradient-to-tr from-amber-500 to-amber-600 text-white p-2.5 rounded-xl shadow-md shadow-amber-500/10 flex items-center justify-center">
          <i data-lucide="ruler" class="w-5 h-5 stroke-[2.2]"></i>
        </div>
        <div>
          <div class="flex items-center gap-2">
            <span class="font-extrabold text-lg tracking-tight bg-gradient-to-r from-slate-900 to-slate-750 bg-clip-text text-transparent">
              xlora_measure
            </span>
            <span class="text-[10px] bg-amber-100 text-amber-700 border border-amber-200 px-1.5 py-0.5 rounded-md font-bold tracking-wide uppercase">
              v3.0 Production
            </span>
          </div>
          <p class="text-[11px] text-slate-505 tracking-wide font-mono mt-0.5" id="studio-branding-container">
            Bespoke Atelier: <strong class="text-slate-800 underline decoration-slate-400 underline-offset-4 cursor-pointer hover:decoration-amber-500 transition" onclick="toggleEditStudio(true)" id="studio-name-display">Aether Bespoke Craft</strong>
            <i data-lucide="settings" class="w-2.5 h-2.5 inline text-slate-400 hover:text-amber-600 transition ml-1"></i>
          </p>
          <div id="studio-name-edit-form" class="hidden flex items-center gap-1.5 mt-0.5">
            <input type="text" id="studio-name-input" class="bg-slate-100 text-slate-800 px-3 py-1 rounded-xl border border-slate-300 text-[10px] placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
            <button onclick="saveStudioName()" class="text-amber-600 hover:text-amber-700 font-bold px-1.5 text-[9px] uppercase tracking-wider font-mono">Save</button>
            <button onclick="toggleEditStudio(false)" class="text-slate-400 hover:text-slate-500 px-1.5 text-[9px] uppercase tracking-wider font-mono">Cancel</button>
          </div>
        </div>
      </div>

      <div class="flex items-center gap-3">
        <div id="portal-navigation-wrapper" class="flex items-center gap-2">
          <button id="back-to-atelier-btn" onclick="switchView('designer')" class="hidden flex items-center gap-2 bg-white hover:bg-slate-100 text-slate-700 text-xs px-3.5 py-2 rounded-xl border border-slate-250 transition-all font-semibold shadow-sm">
            <i data-lucide="arrow-left" class="w-3.5 h-3.5 text-amber-650"></i>
            Atelier Workspace
          </button>
        </div>
        
        <!-- Live Auth Profile Widget -->
        <div id="user-auth-wrapper" class="flex items-center gap-2">
          <button id="auth-trigger-btn" onclick="openModal('authModal')" class="flex items-center gap-2 bg-white hover:bg-slate-50 text-slate-700 text-xs px-3.5 py-2 rounded-xl border border-slate-200 transition font-semibold shadow-sm">
            <i data-lucide="log-in" class="w-3.5 h-3.5 text-amber-600"></i>
            <span>Sign In</span>
          </button>
          <div id="user-profile-badge" class="hidden flex items-center gap-2 bg-white border border-slate-200 px-3 py-1.5 rounded-xl shadow-sm">
            <div class="w-5 h-5 rounded-full bg-gradient-to-tr from-amber-500 to-amber-600 text-white flex items-center justify-center font-bold text-[10px]" id="user-avatar-initials">U</div>
            <span id="user-email-display" class="text-xs text-slate-600 font-mono hidden sm:inline max-w-[120px] truncate">User</span>
            <button onclick="handleSignOut()" class="text-slate-400 hover:text-rose-600 p-0.5 transition" title="Sign Out">
              <i data-lucide="log-out" class="w-3.5 h-3.5"></i>
            </button>
          </div>
        </div>

        <div class="flex items-center gap-2" id="sync-status-indicator">
          <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[11px] font-mono border border-emerald-200">
            <span class="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-ping"></span>
            <span id="sync-status-text">Connecting spec registry...</span>
          </span>
        </div>
      </div>
    </div>
  </header>

  <!-- TOAST NOTIFICATION CONTAINER -->
  <div id="toast-container" class="fixed top-24 right-4 z-50 flex flex-col gap-2 pointer-events-none"></div>

  <!-- ==========================================
        MAIN AREA: DESIGNER DASHBOARD
        ========================================== -->
  <main id="designer-view" class="flex-1 max-w-7xl w-full mx-auto p-4 lg:p-6 grid grid-cols-1 lg:grid-cols-12 gap-6 screen-only">
    
    <!-- LEFT SIDEBAR: CLIENT FILES & TOOLS -->
    <section class="lg:col-span-4 flex flex-col gap-5 border-r border-slate-200/80 lg:pr-6">
      
      <!-- Studio Overview Dashboard -->
      <div class="bg-white border border-slate-200 rounded-2xl p-4 shadow-sm relative overflow-hidden">
        <div class="absolute -top-6 -right-6 opacity-[0.04] pointer-events-none text-slate-900">
          <i data-lucide="folder-open" class="w-32 h-32"></i>
        </div>
        <h2 class="font-bold text-[10px] tracking-wider uppercase text-amber-655 mb-1 font-mono">Workshop Ledger</h2>
        <p class="text-xs text-slate-500 mb-4 leading-relaxed">Map physical space clearance records & visual blueprint specs into clean digital workspaces.</p>
        
        <div class="grid grid-cols-2 gap-2 mb-4">
          <div class="bg-slate-50 rounded-xl p-3 border border-slate-100">
            <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wide block font-mono">Active Folders</span>
            <span id="stat-active-folders" class="text-2xl font-black text-slate-800 font-mono">0</span>
          </div>
          <div class="bg-slate-50 rounded-xl p-3 border border-slate-100">
            <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wide block font-mono">Logged Specs</span>
            <span id="stat-logged-specs" class="text-2xl font-black text-slate-800 font-mono">0</span>
          </div>
        </div>

        <button onclick="openModal('addClientModal')" class="w-full bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-705 text-white text-xs font-bold py-2.5 px-4 rounded-xl shadow-md shadow-amber-500/10 flex items-center justify-center gap-2 transition active:scale-[0.98]">
          <i data-lucide="plus" class="w-4 h-4 stroke-[2.5]"></i>
          Initiate Custom Project
        </button>
      </div>

      <!-- Advanced Woodcraft Deflection & Mechanics Simulator -->
      <div class="bg-white border border-slate-200 rounded-2xl p-4 flex flex-col gap-3 shadow-sm">
        <div class="flex items-center justify-between pb-1.5 border-b border-slate-100">
          <div class="flex items-center gap-2">
            <i data-lucide="calculator" class="w-3.5 h-3.5 text-amber-600"></i>
            <h3 class="text-xs font-bold text-slate-700 uppercase tracking-wider font-mono">Sizing & Deflection Lab</h3>
          </div>
          <span class="text-[9px] font-mono text-slate-400">Beam Deflection Formula</span>
        </div>
        
        <div class="space-y-3">
          <div>
            <label class="block text-[8px] text-slate-405 uppercase font-black mb-1 font-mono">Wood Species</label>
            <select id="simulator-species" onchange="runSimulatorCalculation()" class="w-full bg-slate-50 border border-slate-200 text-slate-800 rounded-xl p-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/30 transition-all font-mono">
              <option value="Walnut">Black Walnut (E: 1.68M psi)</option>
              <option value="Oak">White Oak (E: 1.82M psi)</option>
              <option value="Maple">Hard Maple (E: 1.83M psi)</option>
              <option value="Cherry">Black Cherry (E: 1.49M psi)</option>
              <option value="Pine">Yellow Pine (E: 1.63M psi)</option>
            </select>
          </div>

          <div class="grid grid-cols-3 gap-2">
            <div>
              <label class="block text-[8px] text-slate-405 uppercase font-black mb-1 font-mono">Length</label>
              <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/30 transition-all">
                <input type="number" id="simulator-length" value="60" oninput="runSimulatorCalculation()" class="w-full bg-transparent p-1.5 text-xs font-mono text-center text-slate-800 focus:outline-none">
                <span class="flex items-center justify-center bg-slate-100 px-2 text-[9px] text-slate-500 font-bold border-l border-slate-200 font-mono">in</span>
              </div>
            </div>
            <div>
              <label class="block text-[8px] text-slate-405 uppercase font-black mb-1 font-mono">Width</label>
              <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/30 transition-all">
                <input type="number" id="simulator-width" value="12" oninput="runSimulatorCalculation()" class="w-full bg-transparent p-1.5 text-xs font-mono text-center text-slate-800 focus:outline-none">
                <span class="flex items-center justify-center bg-slate-100 px-2 text-[9px] text-slate-500 font-bold border-l border-slate-200 font-mono">in</span>
              </div>
            </div>
            <div>
              <label class="block text-[8px] text-slate-405 uppercase font-black mb-1 font-mono">Thick</label>
              <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/30 transition-all">
                <input type="number" id="simulator-thickness" value="1.5" step="0.25" oninput="runSimulatorCalculation()" class="w-full bg-transparent p-1.5 text-xs font-mono text-center text-slate-800 focus:outline-none">
                <span class="flex items-center justify-center bg-slate-100 px-2 text-[9px] text-slate-500 font-bold border-l border-slate-200 font-mono">in</span>
              </div>
            </div>
          </div>

          <!-- Graphical Dynamic Sag Visualization -->
          <div class="bg-slate-50 p-2 rounded-xl border border-slate-100 flex flex-col gap-1 relative overflow-hidden">
            <span class="text-[8px] font-mono text-slate-400 block">Span Deflection Curve Load Model (Center Weight: 150 lbs)</span>
            <svg id="simulator-svg" viewBox="0 0 200 40" class="w-full h-8 bg-white rounded border border-slate-200">
              <line x1="10" y1="20" x2="190" y2="20" stroke="rgba(15, 23, 42, 0.08)" stroke-dasharray="2,2"/>
              <path id="simulator-beam-path" d="M 10 20 Q 100 20 190 20" fill="none" stroke="#d97706" stroke-width="2.5" class="deflection-beam-base"/>
              <circle cx="100" id="simulator-weight-marker" cy="20" r="3" fill="#ef4444" />
            </svg>
            <div class="flex justify-between items-center text-[9px] font-mono mt-1">
              <span class="text-slate-500">Moment of Inertia (I): <strong id="sim-i-val" class="text-slate-700">0.00</strong> in⁴</span>
              <span class="text-slate-500">Theoretical Sag: <strong id="sim-sag-val" class="text-amber-600">0.000"</strong> <span class="text-[8.5px] text-slate-400 font-bold font-mono">in</span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- Live Search & Filter Bar -->
      <div class="flex flex-col gap-2">
        <div class="relative">
          <i data-lucide="search" class="absolute left-3 top-3 h-4 w-4 text-slate-400"></i>
          <input type="text" id="client-search" placeholder="Find project folders, logs..." oninput="triggerSearch(this.value)" class="w-full bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl pl-9 pr-9 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all shadow-sm">
        </div>

        <!-- Filtering Presets -->
        <div class="flex flex-wrap gap-1 py-1" id="category-filters-container">
          <!-- Populated dynamically via JS -->
        </div>
      </div>

      <!-- Client Lists Directory Container -->
      <div class="flex-1 overflow-y-auto max-h-[300px] lg:max-h-[400px] space-y-2 pr-1 custom-scrollbar">
        <h3 class="font-bold text-[10px] tracking-wider uppercase text-slate-400 px-1 py-1 font-mono">Folders Ledger</h3>
        <div id="client-ledger-list" class="space-y-2">
          <!-- Populated dynamically -->
        </div>
      </div>
    </section>

    <!-- RIGHT VIEWPORT: WORKSPACE VIEW & LOG DETAILS -->
    <section class="lg:col-span-8 flex flex-col gap-6" id="workspace-viewport">
      
      <!-- Empty Workspace state -->
      <div id="empty-workspace-state" class="flex-1 bg-white border border-dashed border-slate-300 rounded-3xl p-16 flex flex-col items-center justify-center text-center shadow-sm">
        <div class="bg-slate-50 p-4 rounded-full border border-slate-200 text-slate-400 mb-4 animate-pulse">
          <i data-lucide="ruler" class="w-10 h-10 stroke-[1.5]"></i>
        </div>
        <h2 class="text-slate-800 font-black text-base">Select custom specifications profile</h2>
        <p class="text-xs text-slate-500 mt-2 max-w-sm leading-relaxed">
          Choose an existing client specification ledger from the left archives or click to initialize a brand new tailored design workspace.
        </p>
        <button onclick="openModal('addClientModal')" class="mt-6 bg-amber-500 hover:bg-amber-600 text-slate-950 font-bold text-xs px-4.5 py-2.5 rounded-xl transition shadow-md shadow-amber-500/5">
          Initiate Custom Workspace
        </button>
      </div>

      <div id="active-workspace-state" class="hidden flex flex-col gap-6">
        <!-- Branded Workspace Header -->
        <div class="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm relative">
          <div class="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 pb-4 mb-4">
            <div>
              <span id="active-client-category-badge" class="text-[10px] bg-amber-50 text-amber-700 border border-amber-200 px-2.5 py-0.5 rounded-full font-bold uppercase tracking-wider font-mono">
                Furniture Specifications Folder
              </span>
              <h1 id="active-client-title" class="text-xl font-black text-slate-800 mt-1">Genevieve Carter</h1>
            </div>
            
            <div class="flex flex-wrap gap-2">
              <button onclick="openEditClientModal()" class="bg-slate-50 hover:bg-slate-100 text-slate-700 border border-slate-200 px-3 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5 transition shadow-sm">
                <i data-lucide="edit-3" class="w-3.5 h-3.5 text-amber-650"></i>
                Edit Folder
              </button>

              <button onclick="shareActiveClient()" class="bg-amber-500 hover:bg-amber-600 text-slate-950 font-extrabold text-xs px-3.5 py-2 rounded-xl flex items-center gap-1.5 transition shadow-md shadow-amber-500/10">
                <i data-lucide="share-2" class="w-3.5 h-3.5"></i>
                Compile Client Access Link
              </button>
              
              <button id="delete-client-btn" class="bg-slate-50 hover:bg-rose-50 text-slate-405 hover:text-rose-600 p-2.5 rounded-xl transition border border-slate-200 shadow-sm" title="Delete Portfolio Folder">
                <i data-lucide="trash-2" class="w-4 h-4"></i>
              </button>
            </div>
          </div>

          <!-- Info Specs Grid -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
            <div>
              <span class="text-slate-400 uppercase text-[9px] font-extrabold tracking-wider block mb-1 font-mono">Communication Channels</span>
              <p id="active-client-email" class="text-slate-655 flex items-center gap-1.5 mb-1.5 font-mono truncate"></p>
              <p id="active-client-phone" class="text-slate-655 flex items-center gap-1.5 font-mono"></p>
            </div>
            <div>
              <span class="text-slate-400 uppercase text-[9px] font-extrabold tracking-wider block mb-1 font-mono">Design Objectives</span>
              <p id="active-client-objectives" class="text-slate-655 italic line-clamp-3 leading-relaxed"></p>
            </div>
            <div>
              <span class="text-slate-400 uppercase text-[9px] font-extrabold tracking-wider block mb-1.5 font-mono">Fabrication Pipeline Level</span>
              <div class="flex flex-wrap gap-1" id="pipeline-status-controls">
                <!-- Status buttons populated via JS -->
              </div>
            </div>
          </div>
        </div>

        <!-- Tab Controls Navigation Bar -->
        <div class="border-b border-slate-200 flex items-center justify-between">
          <div class="flex gap-4">
            <button onclick="setActiveTab('workpieces')" id="tab-workpieces-btn" class="pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-605 font-black transition">
              <i data-lucide="layers" class="w-4 h-4"></i>
              Workpiece Specs (<span id="tab-workpieces-count" class="font-mono">0</span>)
            </button>
            <button onclick="setActiveTab('site-measures')" id="tab-site-btn" class="pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-805 transition">
              <i data-lucide="home" class="w-4 h-4"></i>
              Site Clearance Logs (<span id="tab-site-count" class="font-mono font-bold">0</span>)
            </button>
          </div>

          <div class="flex gap-2">
            <button onclick="openPrintPreview()" class="bg-white hover:bg-slate-50 text-slate-705 border border-slate-205 rounded-xl px-3.5 py-2 text-xs font-semibold flex items-center gap-1.5 transition shadow-sm" title="Workshop printable specifications">
              <i data-lucide="printer" class="w-3.5 h-3.5 text-amber-600"></i>
              Workshop Sheet
            </button>
            <button id="tab-action-btn" onclick="toggleFormVisibility()" class="bg-slate-800 hover:bg-slate-900 text-white rounded-xl px-3.5 py-2 text-xs font-bold flex items-center gap-1.5 transition-all shadow-sm">
              <i data-lucide="plus" class="w-3.5 h-3.5 text-amber-500"></i>
              <span id="tab-action-text">Log Workpiece</span>
            </button>
          </div>
        </div>

        <!-- Spec content wrapper -->
        <div id="tab-content-container">
          <!-- SPEC LISTINGS AND BLUEPRINT GRID -->
        </div>

        <!-- Interactive Verification loop comments feed -->
        <div class="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm">
          <div class="flex items-center gap-2 mb-3">
            <i data-lucide="message-square" class="w-4 h-4 text-amber-600"></i>
            <h3 class="font-extrabold text-xs uppercase tracking-wider text-slate-700 font-mono">Client Review & Verification Feed</h3>
          </div>
          <div id="client-feedback-feed-stream" class="space-y-2 max-h-48 overflow-y-auto pr-1 custom-scrollbar">
            <!-- Feed stream items injected dynamically -->
          </div>
        </div>
      </div>
    </section>
  </main>

  <!-- ==========================================
        SHARED CLIENT SPECIFICATION PORTAL VIEW
        ========================================== -->
  <main id="client-portal-view" class="hidden flex-1 max-w-5xl w-full mx-auto p-4 lg:p-8 animate-fade-in screen-only">
    <div class="flex flex-col gap-6">
      
      <!-- Client Portal Banner -->
      <div class="bg-white border border-slate-200 rounded-3xl p-6 lg:p-8 relative overflow-hidden shadow-sm">
        <div class="absolute top-0 right-0 p-8 opacity-[0.03] pointer-events-none text-slate-900">
          <i data-lucide="check-circle" class="w-48 h-48"></i>
        </div>

        <div class="flex flex-wrap items-center justify-between gap-4 border-b border-slate-100 pb-6 mb-6">
          <div>
            <span class="text-[10px] font-bold tracking-widest text-amber-700 uppercase bg-amber-50 px-3 py-1 rounded-full border border-amber-200 font-mono">
              Architectural Sizing Portal
            </span>
            <h1 class="text-2xl lg:text-3xl font-black text-slate-805 mt-2">
              Hello, <span id="client-portal-name">Client Name</span>
            </h1>
            <p class="text-xs text-slate-500 mt-1.5 max-w-xl leading-relaxed">
              Your custom layouts compiled with workshop-grade precision by <strong id="client-portal-studio-title">Aether Bespoke Craft</strong>. Review dimensions, clearances, and blueprints below to lock in the final cut sheet.
            </p>
          </div>

          <div class="flex items-center gap-2">
            <span class="text-xs text-slate-400 font-mono">State:</span>
            <span id="client-portal-status-badge" class="text-xs px-3 py-1 rounded-full font-bold uppercase tracking-wider border"></span>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs leading-relaxed text-slate-500">
          <div>
            <strong class="text-slate-750 block mb-1 font-mono">Directives Brief</strong>
            <span id="client-portal-brief-text" class="italic"></span>
          </div>
          <div class="flex flex-col gap-2 md:items-end justify-center" id="client-portal-signoff-action-container">
            <!-- Injected via JS based on state -->
          </div>
        </div>
      </div>

      <!-- PORTAL TABS -->
      <div class="flex gap-4 border-b border-slate-200">
        <button onclick="setPortalTab('workpieces')" id="portal-tab-workpieces" class="pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-600 transition">
          <i data-lucide="layers" class="w-4 h-4"></i>
          Proposed Designs (<span id="portal-workpieces-count" class="font-mono">0</span>)
        </button>
        <button onclick="setPortalTab('site-measures')" id="portal-tab-site" class="pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-805 transition">
          <i data-lucide="home" class="w-4 h-4"></i>
          Physical Site Assessment (<span id="portal-site-count" class="font-mono font-bold">0</span>)
        </button>
      </div>

      <!-- PORTAL SPEC LISTINGS CONTENT -->
      <div id="portal-tab-content-container"></div>

      <!-- Portal Revision Note Transmit Panel -->
      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 mt-6">
        <div class="lg:col-span-7 bg-white border border-slate-200 rounded-3xl p-6 flex flex-col gap-4 shadow-sm">
          <div>
            <h3 class="font-extrabold text-xs uppercase tracking-widest text-slate-700 flex items-center gap-2 font-mono">
              <i data-lucide="message-square" class="w-4 h-4 text-amber-655"></i>
              Request Modifications / Feedback
            </h3>
            <p class="text-xs text-slate-500 mt-1.5 leading-relaxed">
              Questions regarding material selections or need to alter a logged dimension? Log it below to notify the studio instantly.
            </p>
          </div>

          <form onsubmit="submitPortalComment(event)" class="flex flex-col gap-3">
            <textarea id="portal-comment-textarea" rows="3" required placeholder="e.g. Can we expand the dining table length to 102 inches? We measured the alcove clearance once more..." class="w-full bg-slate-50 border border-slate-200 rounded-2xl p-4 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition resize-none font-sans"></textarea>
            <button type="submit" class="self-end bg-amber-500 hover:bg-amber-600 text-slate-955 text-xs font-black px-5 py-2.5 rounded-xl transition flex items-center gap-1.5 shadow-sm uppercase tracking-wider font-mono">
              Transmit Revision Note
            </button>
          </form>
        </div>

        <div class="lg:col-span-5 bg-white border border-slate-200 rounded-3xl p-6 flex flex-col gap-4 shadow-sm">
          <h3 class="font-extrabold text-xs uppercase tracking-widest text-slate-700 font-mono">Shared Activity stream</h3>
          <div id="portal-activity-stream-container" class="space-y-3 overflow-y-auto max-h-56 pr-1 custom-scrollbar flex-1">
            <!-- feedback loops are populated here -->
          </div>
        </div>
      </div>

    </div>
  </main>

  <!-- ==========================================
        MODALS & DIALOGS
        ========================================== -->

  <!-- Authentication Modal (Login / Register) -->
  <div id="authModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden animate-fade-in">
    <div class="bg-white border border-slate-200 w-full max-w-md rounded-2xl overflow-hidden shadow-xl relative">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 id="auth-modal-title" class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="shield-check" class="w-4 h-4 text-amber-600"></i>
          Atelier Authentication
        </h3>
        <button onclick="closeModal('authModal')" class="text-slate-400 hover:text-slate-605">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>

      <!-- Switch Authentication Mode Tabs -->
      <div class="flex border-b border-slate-100 bg-slate-50">
        <button id="auth-tab-login" onclick="toggleAuthMode('login')" class="flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-amber-500 text-amber-600">
          Sign In
        </button>
        <button id="auth-tab-register" onclick="toggleAuthMode('register')" class="flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-transparent text-slate-400 hover:text-slate-750">
          Register
        </button>
      </div>

      <form id="auth-form" onsubmit="handleAuthSubmit(event)" class="p-5 space-y-4 text-xs">
        <div>
          <label class="block text-[10px] text-slate-400 uppercase font-black mb-1 font-mono">Email Address *</label>
          <input type="email" id="auth-email" required placeholder="craftsman@aether.studio" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
        </div>
        <div>
          <label class="block text-[10px] text-slate-400 uppercase font-black mb-1 font-mono">Password *</label>
          <input type="password" id="auth-password" required placeholder="••••••••" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
        </div>
        
        <div id="auth-error-box" class="hidden bg-rose-50 border border-rose-200 text-rose-700 p-3 rounded-xl font-mono text-[10px] leading-relaxed">
          Authentication failed. Check your inputs.
        </div>

        <div class="flex items-center justify-end gap-2 border-t border-slate-100 pt-3">
          <button type="button" onclick="closeModal('authModal')" class="bg-transparent hover:bg-slate-50 text-slate-550 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button id="auth-submit-btn" type="submit" class="bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-black px-5 py-2.5 rounded-xl transition flex items-center justify-center gap-1.5 shadow-sm uppercase tracking-wider font-mono">
            Deploy Session
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Add Client Portfolio Modal -->
  <div id="addClientModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
    <div class="bg-white border border-slate-200 w-full max-w-md rounded-2xl overflow-hidden shadow-xl relative">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="folder-open" class="w-4 h-4 text-amber-600"></i>
          Initialize Client Ledger
        </h3>
        <button onclick="closeModal('addClientModal')" class="text-slate-400 hover:text-slate-600">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>

      <form id="add-client-form" onsubmit="handleAddClientSubmit(event)" class="p-4 space-y-4">
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Client Full Name *</label>
          <input type="text" id="new-client-name" required placeholder="e.g. Richard Hendricks" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
        </div>
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Email Address</label>
            <input type="email" id="new-client-email" placeholder="richard@hooli.xyz" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition font-mono">
          </div>
          <div>
            <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Phone Number</label>
            <input type="text" id="new-client-phone" placeholder="+1 (555) 000-0000" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition font-mono">
          </div>
        </div>
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Craft Project Category</label>
          <select id="new-client-category" class="w-full bg-slate-50 border border-slate-200 text-slate-800 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
            <option value="Furniture">Furniture & Fine Woodwork</option>
            <option value="Commercial Fit">Commercial Fittings & Structures</option>
            <option value="Apparel">Custom Sewing & Leathercraft</option>
            <option value="Art">Visual Framing & Art Installation</option>
            <option value="Custom">Custom Component Fab</option>
          </select>
        </div>
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Scope Brief / Project Summary</label>
          <textarea id="new-client-notes" rows="3" placeholder="Summarize raw timber preferences, stylistic directions, structural goals..." class="w-full bg-slate-50 border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl p-3 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition resize-none font-sans"></textarea>
        </div>
        <div class="flex items-center justify-end gap-2 border-t border-slate-100 pt-3">
          <button type="button" onclick="closeModal('addClientModal')" class="bg-transparent hover:bg-slate-50 text-slate-500 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button type="submit" class="bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-bold px-4 py-2 rounded-xl transition font-mono">Initiate Folder</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Edit Client Ledger Portfolio Modal -->
  <div id="editClientModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
    <div class="bg-white border border-slate-200 w-full max-w-md rounded-2xl overflow-hidden shadow-xl relative">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="edit-3" class="w-4 h-4 text-amber-600"></i>
          Edit Client Spec Portfolio
        </h3>
        <button onclick="closeModal('editClientModal')" class="text-slate-400 hover:text-slate-600">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>

      <form id="edit-client-form" onsubmit="handleEditClientSubmit(event)" class="p-4 space-y-4">
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Client Full Name *</label>
          <input type="text" id="edit-client-name" required class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
        </div>
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Email Address</label>
            <input type="email" id="edit-client-email" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition font-mono">
          </div>
          <div>
            <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Phone Number</label>
            <input type="text" id="edit-client-phone" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition font-mono">
          </div>
        </div>
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Craft Project Category</label>
          <select id="edit-client-category" class="w-full bg-slate-50 border border-slate-200 text-slate-800 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
            <option value="Furniture">Furniture & Fine Woodwork</option>
            <option value="Commercial Fit">Commercial Fittings & Structures</option>
            <option value="Apparel">Custom Sewing & Leathercraft</option>
            <option value="Art">Visual Framing & Art Installation</option>
            <option value="Custom">Custom Component Fab</option>
          </select>
        </div>
        <div>
          <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Scope Brief / Project Summary</label>
          <textarea id="edit-client-notes" rows="3" class="w-full bg-slate-50 border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl p-3 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition resize-none font-sans"></textarea>
        </div>
        <div class="flex items-center justify-end gap-2 border-t border-slate-100 pt-3">
          <button type="button" onclick="closeModal('editClientModal')" class="bg-transparent hover:bg-slate-50 text-slate-500 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button type="submit" class="bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-bold px-4 py-2 rounded-xl transition font-mono">Save Modifications</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Add Workpiece Spec Modal (Craft Sizing / Blueprint Configuration) -->
  <div id="addWorkpieceModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden animate-fade-in">
    <div class="bg-white border border-slate-200 w-full max-w-xl rounded-2xl overflow-hidden shadow-xl">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 id="workpiece-modal-heading" class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="layers" class="w-4 h-4 text-amber-600"></i>
          Configure Workpiece Dimensions
        </h3>
        <button onclick="closeWorkpieceModal()" class="text-slate-400 hover:text-slate-600">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>

      <form id="add-workpiece-form" onsubmit="handleAddWorkpieceSubmit(event)" class="p-5 space-y-4 text-xs">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="flex flex-col gap-3">
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black tracking-wide mb-1 font-mono">Workpiece Designation *</label>
              <input type="text" id="workpiece-title" required placeholder="e.g. Dining Bench Plank" class="w-full bg-slate-50 border border-slate-200 text-slate-800 placeholder:text-slate-405 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
            </div>

            <!-- Measured / Verified Person Dropdown Picker -->
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black tracking-wide mb-1 font-mono">Measured / Verified By</label>
              <select id="workpiece-measured-by" class="w-full bg-slate-50 border border-slate-200 text-slate-800 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
                <option value="Lead Designer">Lead Designer</option>
                <option value="Senior Craftsman">Senior Craftsman</option>
                <option value="Site Surveyor">Site Surveyor</option>
                <option value="Apprentice Woodworker">Apprentice Woodworker</option>
                <option value="Client (Self-Measured)">Client (Self-Measured)</option>
              </select>
            </div>
            
            <!-- Dimension Parameters with Individual Unit Dropdowns -->
            <div>
              <span class="block text-[10px] text-slate-405 uppercase font-black tracking-wide mb-1.5 font-mono">Dimensions Config</span>
              <div class="grid grid-cols-2 gap-3">
                <!-- Length -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Length</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="workpiece-length" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="workpiece-length-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'workpiece-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'workpiece-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'workpiece-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Width -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Width</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="workpiece-width" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="workpiece-width-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'workpiece-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'workpiece-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'workpiece-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Height -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Height</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="workpiece-height" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="workpiece-height-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'workpiece-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'workpiece-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'workpiece-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Thickness (depth) -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Thickness</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="workpiece-depth" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="workpiece-depth-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'workpiece-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'workpiece-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'workpiece-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="flex flex-col gap-3">
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Materials Selection & Assembly Notes</label>
              <textarea id="workpiece-notes" rows="4" placeholder="Detail any joint structures, raw lumber, profiles or finishes..." class="w-full bg-slate-50 border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl p-3 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 resize-none font-sans"></textarea>
            </div>

            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black mb-1.5 font-mono font-bold">Reference Images</label>
              <div class="flex flex-wrap gap-2 items-center">
                <label class="w-16 h-16 rounded-xl border border-dashed border-slate-300 hover:border-amber-500 hover:bg-slate-50 flex flex-col items-center justify-center cursor-pointer transition text-slate-400 hover:text-slate-500">
                  <input type="file" accept="image/*" multiple onchange="handleImageUpload(event, 'workpiece')" class="hidden">
                  <i data-lucide="image" class="w-4 h-4"></i>
                  <span class="text-[8px] mt-1 text-center leading-none font-mono">Add Media</span>
                </label>
                <div id="workpiece-images-preview" class="flex flex-wrap gap-2"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="flex items-center justify-end gap-2 border-t border-slate-100 pt-3.5">
          <button type="button" onclick="closeWorkpieceModal()" class="bg-transparent hover:bg-slate-50 text-slate-500 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button id="workpiece-modal-submit-btn" type="submit" class="bg-amber-500 hover:bg-amber-600 text-slate-955 text-xs font-bold px-4 py-2 rounded-xl transition font-mono">Deploy Workpiece Specs</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Add Site Clearance Log Modal -->
  <div id="addSiteMeasureModal" class="fixed inset-0 bg-slate-905/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden animate-fade-in">
    <div class="bg-white border border-slate-200 w-full max-w-xl rounded-2xl overflow-hidden shadow-xl">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 id="site-modal-heading" class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="home" class="w-4 h-4 text-amber-600"></i>
          Log Site Clearance Profile
        </h3>
        <button onclick="closeSiteModal()" class="text-slate-400 hover:text-slate-600">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>

      <form id="add-site-form" onsubmit="handleAddSiteSubmit(event)" class="p-5 space-y-4 text-xs">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="flex flex-col gap-3">
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black tracking-wide mb-1 font-mono">Site / Location Target *</label>
              <input type="text" id="site-label" required placeholder="e.g. Penthouse South Wall Alcove" class="w-full bg-slate-50 border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
            </div>

            <!-- Measured / Verified Person Dropdown Picker for Site -->
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black tracking-wide mb-1 font-mono">Measured / Verified By</label>
              <select id="site-measured-by" class="w-full bg-slate-50 border border-slate-200 text-slate-800 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 transition-all">
                <option value="Lead Designer">Lead Designer</option>
                <option value="Senior Craftsman">Senior Craftsman</option>
                <option value="Site Surveyor">Site Surveyor</option>
                <option value="Apprentice Woodworker">Apprentice Woodworker</option>
                <option value="Client (Self-Measured)">Client (Self-Measured)</option>
              </select>
            </div>

            <div>
              <span class="block text-[10px] text-slate-450 uppercase font-black tracking-wide mb-1.5 font-mono">Measured Clearances</span>
              <div class="grid grid-cols-2 gap-3">
                <!-- Site Length -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Length</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="site-length" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="site-length-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'site-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'site-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'site-length')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Site Width -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Width</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="site-width" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="site-width-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'site-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'site-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'site-width')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Site Height -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Height</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="site-height" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="site-height-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'site-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'site-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'site-height')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>

                <!-- Site Gap Offset (depth) -->
                <div>
                  <span class="text-[8px] text-slate-500 block mb-1 font-bold uppercase font-mono">Gap Offset</span>
                  <div class="flex rounded-xl overflow-hidden border border-slate-200 bg-slate-50 focus-within:border-amber-500 focus-within:ring-1 focus-within:ring-amber-500/35 transition-all">
                    <input type="text" id="site-depth" placeholder="Value" class="w-full bg-transparent px-2.5 py-2 text-xs text-center text-slate-800 focus:outline-none font-mono font-bold">
                    <select id="site-depth-unit" class="bg-slate-100 px-1 py-1 text-[9px] text-amber-700 font-bold border-l border-slate-200 font-mono outline-none">
                      <option value="inches" selected>in</option>
                      <option value="cm">cm</option>
                      <option value="mm">mm</option>
                      <option value="feet">ft</option>
                    </select>
                  </div>
                  <div class="flex gap-1 mt-1 justify-center">
                    <button type="button" onclick="appendFractionValue('1/8', 'site-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/8</button>
                    <button type="button" onclick="appendFractionValue('1/4', 'site-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/4</button>
                    <button type="button" onclick="appendFractionValue('1/2', 'site-depth')" class="bg-slate-50 hover:bg-slate-100 hover:text-amber-700 border border-slate-200 rounded-lg px-1.5 py-0.5 text-[8px] transition-all font-mono">+1/2</button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="flex flex-col gap-3">
            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black mb-1 font-mono">Obstacles & Physical Constraints</label>
              <textarea id="site-notes" rows="4" placeholder="Identify outlets, baseboards, floor vents, trim mold, plumbing profiles..." class="w-full bg-slate-55 border border-slate-200 text-slate-800 placeholder:text-slate-400 rounded-xl p-3 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-500/35 resize-none font-sans"></textarea>
            </div>

            <div>
              <label class="block text-[10px] text-slate-405 uppercase font-black mb-1.5 font-mono font-bold">Reference Images</label>
              <div class="flex flex-wrap gap-2 items-center">
                <label class="w-16 h-16 rounded-xl border border-dashed border-slate-300 hover:border-amber-500 hover:bg-slate-50 flex flex-col items-center justify-center cursor-pointer transition text-slate-400 hover:text-slate-500">
                  <input type="file" accept="image/*" multiple onchange="handleImageUpload(event, 'site')" class="hidden">
                  <i data-lucide="camera" class="w-4 h-4"></i>
                  <span class="text-[8px] mt-1 text-center leading-none font-mono">Add Visual</span>
                </label>
                <div id="site-images-preview" class="flex flex-wrap gap-2"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="flex items-center justify-end gap-2 border-t border-slate-100 pt-3.5">
          <button type="button" onclick="closeSiteModal()" class="bg-transparent hover:bg-slate-50 text-slate-550 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button id="site-modal-submit-btn" type="submit" class="bg-amber-500 hover:bg-amber-600 text-slate-955 text-xs font-bold px-4 py-2 rounded-xl transition font-mono">Deploy Clearance Specs</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Share Spec Folder Modal -->
  <div id="shareSpecModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden animate-fade-in">
    <div class="bg-white border border-slate-200 w-full max-w-lg rounded-2xl overflow-hidden shadow-xl relative">
      <div class="flex items-center justify-between p-4 border-b border-slate-100">
        <h3 class="font-extrabold text-xs uppercase tracking-wider text-slate-700 flex items-center gap-2 font-mono">
          <i data-lucide="share-2" class="w-4 h-4 text-amber-600"></i>
          Share Sizing Workspace Access
        </h3>
        <button onclick="closeModal('shareSpecModal')" class="text-slate-400 hover:text-slate-600">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>
      <div class="p-5 space-y-4 text-xs">
        <p class="text-slate-500 leading-relaxed">
          Grant your client access to view proposed workpiece dimensions, verify physical site assessments, and sign off directly from their phone or browser.
        </p>
        <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-3">
          <div class="flex items-center justify-between">
            <span class="text-[10px] text-slate-400 uppercase font-black font-mono">Secure Share Link for <strong id="share-modal-client-name" class="text-amber-700">Client Name</strong></span>
          </div>
          <div class="bg-white border border-slate-200 px-3 py-2.5 rounded-lg font-mono text-[11px] text-slate-750 break-all select-all flex justify-between items-center gap-2">
            <span id="share-modal-link-preview" class="select-all">Loading...</span>
          </div>
        </div>
        <div class="grid grid-cols-3 gap-2 pt-2">
          <button onclick="copyShareLinkToClipboard()" class="bg-white hover:bg-slate-50 text-slate-707 border border-slate-200 rounded-xl py-2.5 font-bold flex items-center justify-center gap-1.5 transition shadow-sm">
            <i data-lucide="copy" class="w-3.5 h-3.5 text-amber-600"></i> Copy Link
          </button>
          <button onclick="shareToWhatsAppDirectly()" class="bg-white hover:bg-slate-50 text-slate-707 border border-slate-200 rounded-xl py-2.5 font-bold flex items-center justify-center gap-1.5 transition shadow-sm">
            <i data-lucide="message-circle" class="w-3.5 h-3.5 text-emerald-600"></i> WhatsApp
          </button>
          <button onclick="openPortalLinkDirectly()" class="bg-amber-500 hover:bg-amber-600 text-slate-950 rounded-xl py-2.5 font-extrabold flex items-center justify-center gap-1.5 transition shadow-md shadow-amber-500/10">
            <i data-lucide="external-link" class="w-3.5 h-3.5"></i> Launch Portal
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Confirm Dialog Modal -->
  <div id="confirmDialogModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-[100] flex items-center justify-center p-4 hidden">
    <div class="bg-white border border-slate-200 w-full max-w-md rounded-2xl overflow-hidden shadow-xl relative">
      <div class="p-5 space-y-4">
        <div class="flex items-center gap-3">
          <div class="bg-amber-50 p-2.5 rounded-xl border border-amber-200 text-amber-605 flex items-center justify-center">
            <i data-lucide="alert-triangle" class="w-5 h-5"></i>
          </div>
          <h3 id="confirm-dialog-title" class="font-extrabold text-sm uppercase tracking-wide text-slate-755 font-mono">Are you sure?</h3>
        </div>
        <p id="confirm-dialog-message" class="text-xs text-slate-400 leading-relaxed"></p>
        <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
          <button id="confirm-dialog-cancel-btn" type="button" class="bg-transparent hover:bg-slate-50 text-slate-500 text-xs px-4 py-2 rounded-xl transition font-mono">Cancel</button>
          <button id="confirm-dialog-submit-btn" type="button" class="bg-amber-500 hover:bg-amber-600 text-slate-955 text-xs font-bold px-4 py-2 rounded-xl transition font-mono">Confirm</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Workshop Print Sheet Modal Overlay -->
  <div id="workshopPrintOverlay" class="fixed inset-0 bg-slate-905/95 backdrop-blur-md z-[60] overflow-y-auto p-4 md:p-8 hidden screen-only">
    <div class="max-w-4xl mx-auto bg-white text-zinc-900 border border-zinc-200 rounded-2xl shadow-xl p-6 md:p-10 space-y-6 relative animate-fade-in">
      <!-- Controls -->
      <div class="flex items-center justify-between border-b border-zinc-100 pb-4 mb-4">
        <div class="flex items-center gap-2">
          <span class="bg-amber-500 text-slate-955 p-1.5 rounded-lg flex items-center justify-center"><i data-lucide="printer" class="w-4 h-4"></i></span>
          <h3 class="font-bold text-zinc-900 text-sm font-mono">Print Workshop Cut Sheets & Specs</h3>
        </div>
        <div class="flex gap-2">
          <button onclick="window.print()" class="bg-amber-500 hover:bg-amber-400 text-slate-955 font-bold text-xs px-4 py-2 rounded-xl transition flex items-center gap-1.5 shadow">
            <i data-lucide="printer" class="w-3.5 h-3.5"></i> Trigger System Print
          </button>
          <button onclick="closeModal('workshopPrintOverlay')" class="bg-zinc-100 hover:bg-zinc-200 text-zinc-700 font-bold text-xs px-4 py-2 rounded-xl transition font-mono">
            Dismiss Sheet
          </button>
        </div>
      </div>
      
      <!-- Styled sheet displayed on screen inside the modal -->
      <div id="printable-preview-content" class="space-y-6">
        <!-- Dynamic print content -->
      </div>
    </div>
  </div>

  <!-- Image Viewer Modal (Lightbox Container) -->
  <div id="imageViewerModal" onclick="closeModal('imageViewerModal')" class="fixed inset-0 bg-slate-955/95 backdrop-blur-md z-[110] flex flex-col items-center justify-center p-4 hidden animate-fade-in screen-only cursor-zoom-out">
    <div class="absolute top-4 right-4 flex items-center gap-2" onclick="event.stopPropagation()">
      <button onclick="closeModal('imageViewerModal')" class="bg-white hover:bg-slate-50 text-slate-800 p-2.5 rounded-full border border-slate-200 transition flex items-center justify-center shadow-lg">
        <i data-lucide="x" class="w-5 h-5"></i>
      </button>
    </div>
    <div class="max-w-4xl w-full flex flex-col gap-3" onclick="event.stopPropagation()">
      <img id="lightbox-image" src="" alt="Blueprint Detail View" class="max-h-[80vh] w-auto mx-auto rounded-2xl object-contain border border-slate-200 shadow-xl bg-slate-100" />
      <div class="text-center">
        <h4 id="lightbox-caption" class="text-xs font-mono font-black text-amber-700 tracking-wider uppercase drop-shadow"></h4>
      </div>
    </div>
  </div>

  <!-- ROOT PRINT CONTAINER FOR PHYSICAL MEDIA PRINTING -->
  <div id="printable-workshop-sheet"></div>


  <!-- ==========================================
        MAIN JAVASCRIPT APPLICATION ARCHITECTURE
        ========================================== -->
  <script type="module">
    // Modern Firebase SDK imports conforming strictly to recommended guidelines
    import { initializeApp } from 'https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js';
    import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from 'https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js';
    import { getFirestore, doc, getDoc, collection, onSnapshot, addDoc, updateDoc, deleteDoc } from 'https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js';

    // Global state registry
    const appState = {
      currentView: 'designer', // 'designer' | 'client-portal'
      activeClient: null,
      clients: [],
      activeTab: 'workpieces', // 'workpieces' | 'site-measures'
      portalTab: 'workpieces', // 'workpieces' | 'site-measures'
      selectedWood: 'Walnut',
      categoryFilter: 'All',
      searchTerm: '',
      studioName: localStorage.getItem('cs_studio_name') || 'Aether Bespoke Craft',
      isOffline: true,
      currentUser: null,
      authMode: 'login', // 'login' | 'register'
      editingItemId: null,
      editingSiteId: null,
      tempItemImages: [],
      tempSiteImages: [],
      portalOwnerId: null // Stores shared designer's ID when acting as a guest in client view
    };

    // Firebase configurations
    let app, auth, db, appId = 'xlora-measure-default', firebaseInitialized = false;

    // Default static fallback mocks to seed storage and preview simulation
    const seedMockClients = [
      {
        id: 'client-1',
        name: 'Genevieve Carter',
        email: 'genevieve@carterdesign.io',
        phone: '+1 (555) 382-9921',
        category: 'Furniture',
        notes: 'Premium Walnut Dining Table set for the main penthouse space with custom angular metal bevel joints.',
        createdAt: Date.now() - 86400000 * 5,
        updatedAt: Date.now() - 86400000 * 5,
        status: 'In Production',
        items: [
          {
            id: 'item-101',
            title: 'Walnut Slab Dining Table',
            dimensions: { 
              length: '96', lengthUnit: 'inches', 
              width: '42', widthUnit: 'inches', 
              height: '30', heightUnit: 'inches', 
              depth: '2', depthUnit: 'inches' 
            },
            woodType: 'Walnut',
            measuredBy: 'Lead Designer',
            notes: 'Hand-picked organic black walnut live-edge slab. Double trapezoid steel legs in refined sandblasted matte black.',
            images: ['https://images.unsplash.com/photo-1577140917170-285929fb55b7?auto=format&fit=crop&w=800&q=80']
          },
          {
            id: 'item-102',
            title: 'Matching Oak Bench Frame',
            dimensions: { 
              length: '200', lengthUnit: 'cm', 
              width: '40', widthUnit: 'cm', 
              height: '45', heightUnit: 'cm', 
              depth: '4', depthUnit: 'cm' 
            },
            woodType: 'Oak',
            measuredBy: 'Senior Craftsman',
            notes: 'To match main walnut slab edge structure. Must slide entirely beneath table envelope cleanly.',
            images: []
          }
        ],
        siteMeasures: [
          {
            id: 'site-101',
            label: 'Penthouse Dining Room Alcove',
            dimensions: { 
              length: '160', lengthUnit: 'inches', 
              width: '120', widthUnit: 'inches', 
              height: '110', heightUnit: 'inches', 
              depth: '12', depthUnit: 'cm' 
            },
            measuredBy: 'Site Surveyor',
            notes: 'AC floor vents require a strict safety margin clearance on the west side corner.',
            images: ['https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=800&q=80']
          }
        ],
        feedback: [
          { sender: 'Client', text: 'The dining table dimensions look absolutely spot on! Cant wait to see the raw cut planks.', timestamp: Date.now() - 86400000 * 2 }
        ]
      }
    ];

    // Conversion helper for mechanical and projection standards
    const convertToInches = (valStr, unit) => {
      const val = parseFloat(valStr) || 0;
      if (val <= 0) return 0;
      switch (unit) {
        case 'inches':
        case 'in': return val;
        case 'cm': return val / 2.54;
        case 'mm': return val / 25.4;
        case 'feet':
        case 'ft': return val * 12;
        default: return val;
      }
    };

    // Helper to retrieve current active user path segregating data per account
    const getActiveUserId = () => {
      return auth?.currentUser?.uid || 'default-guest';
    };

    // Attempt Firebase Bootstrap with strict Auth rule checks
    const initializeFirebase = async () => {
      try {
        let config = null;
        if (typeof __firebase_config !== 'undefined' && __firebase_config) {
          config = JSON.parse(__firebase_config);
          appId = typeof __app_id !== 'undefined' ? __app_id : 'xlora-measure';
        } else {
          // Fallback configuration parameters containing valid project credentials
          config = {
            apiKey: "AIzaSyCeCZEuLYC4RpXniKaakNZRf3CIq-idbhU",
            authDomain: "xlora-measure.firebaseapp.com",
            projectId: "xlora-measure",
            storageBucket: "xlora-measure.firebasestorage.app",
            messagingSenderId: "307017521562",
            appId: "1:307017521562:web:0bab7e7046599406c80223",
            measurementId: "G-3D7X4YTMG5"
          };
          appId = 'xlora-measure';
        }
        app = initializeApp(config);
        auth = getAuth(app);
        db = getFirestore(app);
        firebaseInitialized = true;
        appState.isOffline = false;

        // AUTHENTICATE FIRST (Rule 3 mandate)
        await initAuth();
      } catch (e) {
        console.warn("Using offline sandbox environment context:", e);
        loadOfflineSandbox();
      }
    };

    // Rule 3 Priority Authenticator Logic with persistent onAuthStateChanged listener
    const initAuth = async () => {
      try {
        if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {
          const cred = await signInWithCustomToken(auth, __initial_auth_token);
          appState.currentUser = cred.user;
        }
      } catch (err) {
        console.error("Auth custom token initialization failed:", err);
      }

      // Automatically recover login state or authenticate anonymously to prevent path errors
      onAuthStateChanged(auth, async (usr) => {
        if (usr) {
          appState.currentUser = usr;
          appState.isOffline = false;
          updateAuthUI(usr);
          setupFirestoreSubscription(usr.uid);
        } else {
          try {
            // Keep guest/anon sessions unique to prevent collisions in public views (Rule 1 & Rule 3)
            const cred = await signInAnonymously(auth);
            appState.currentUser = cred.user;
            appState.isOffline = false;
            updateAuthUI(cred.user);
            setupFirestoreSubscription(cred.user.uid);
          } catch (anonErr) {
            console.error("Anonymous auth observer fallback failed:", anonErr);
            loadOfflineSandbox();
          }
        }
      });
    };

    const loadOfflineSandbox = () => {
      appState.isOffline = true;
      const syncText = document.getElementById('sync-status-text');
      const syncInd = document.getElementById('sync-status-indicator');
      if (syncText) syncText.textContent = "Offline Sandbox Active";
      if (syncInd && syncInd.firstElementChild) {
        syncInd.firstElementChild.className = "inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 text-amber-700 text-[11px] font-mono border border-amber-200";
        if (syncInd.firstElementChild.firstElementChild) {
          syncInd.firstElementChild.firstElementChild.className = "w-1.5 h-1.5 bg-amber-500 rounded-full";
        }
      }
      
      const localData = localStorage.getItem('cs_mock_clients_v2');
      if (localData) {
        appState.clients = JSON.parse(localData);
      } else {
        appState.clients = seedMockClients;
        localStorage.setItem('cs_mock_clients_v2', JSON.stringify(seedMockClients));
      }
      renderClientLedger();
      parseUrlDeepLink();
    };

    // Subscribes strictly to current account subcollection route
    const setupFirestoreSubscription = (userId) => {
      if (!userId) return; // Auth Guard

      document.getElementById('sync-status-text').textContent = "Cloud Sync Active";
      
      // Strict user-specific path (Rule 1 mandate & user data segregation)
      const clientsRef = collection(db, 'artifacts', appId, 'users', userId, 'clients');
      
      // Remove previous listener on change to prevent duplicate streams
      if (window.activeClientsUnsubscribe) {
        window.activeClientsUnsubscribe();
      }

      window.activeClientsUnsubscribe = onSnapshot(clientsRef, (snapshot) => {
        const clientsList = [];
        snapshot.forEach((doc) => {
          clientsList.push({ id: doc.id, ...doc.data() });
        });
        clientsList.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
        appState.clients = clientsList;
        renderClientLedger();
        
        if (appState.activeClient) {
          const refreshedClient = appState.clients.find(c => c.id === appState.activeClient.id);
          if (refreshedClient) {
            appState.activeClient = refreshedClient;
            renderWorkspaceDetails();
          }
        }
        parseUrlDeepLink();
      }, (error) => {
        console.error("Firestore database clients sub collection failed:", error);
      });
    };

    // Subscribes directly to shared document in target designer's private path (Rule 1 & Rule 2)
    const setupClientPortalSubscription = (ownerId, clientId) => {
      if (!ownerId || !clientId) return;

      const clientDocRef = doc(db, 'artifacts', appId, 'users', ownerId, 'clients', clientId);

      if (window.activePortalUnsubscribe) {
        window.activePortalUnsubscribe();
      }

      window.activePortalUnsubscribe = onSnapshot(clientDocRef, (docSnap) => {
        if (docSnap.exists()) {
          appState.activeClient = { id: docSnap.id, ...docSnap.data() };
          appState.portalOwnerId = ownerId; // Save path ID to route feedback correctly
          switchView('client-portal');
        } else {
          triggerToast("Shared layout specifications not found.", "error");
        }
      }, (error) => {
        console.error("Portal share subscriber fetch failed:", error);
        triggerToast("Unable to load shared workspace specs.", "error");
      });
    };

    // Authentication Handlers (Login / Register / Signout)
    window.toggleAuthMode = (mode) => {
      appState.authMode = mode;
      const tabLogin = document.getElementById('auth-tab-login');
      const tabRegister = document.getElementById('auth-tab-register');
      const submitBtn = document.getElementById('auth-submit-btn');
      const errorBox = document.getElementById('auth-error-box');

      errorBox.classList.add('hidden');

      if (mode === 'login') {
        tabLogin.className = "flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-amber-500 text-amber-600";
        tabRegister.className = "flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-transparent text-slate-400 hover:text-slate-750";
        submitBtn.textContent = "Deploy Session";
      } else {
        tabLogin.className = "flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-transparent text-slate-400 hover:text-slate-750";
        tabRegister.className = "flex-1 py-3 text-center text-xs font-bold uppercase font-mono border-b-2 border-amber-500 text-amber-600";
        submitBtn.textContent = "Create Account";
      }
    };

    window.handleAuthSubmit = async (e) => {
      e.preventDefault();
      const email = document.getElementById('auth-email').value.trim();
      const password = document.getElementById('auth-password').value;
      const errorBox = document.getElementById('auth-error-box');
      const submitBtn = document.getElementById('auth-submit-btn');

      if (appState.isOffline || !auth) {
        triggerToast("Authentication offline. Active sandbox mode.", "warning");
        return;
      }

      submitBtn.disabled = true;
      submitBtn.innerHTML = `<span class="w-3.5 h-3.5 border-2 border-slate-950 border-t-transparent rounded-full animate-spin"></span> Processing...`;
      errorBox.classList.add('hidden');

      try {
        if (appState.authMode === 'login') {
          await signInWithEmailAndPassword(auth, email, password);
          triggerToast("Session successfully deployed!");
        } else {
          await createUserWithEmailAndPassword(auth, email, password);
          triggerToast("Account successfully registered & initialized!");
        }
        closeModal('authModal');
        document.getElementById('auth-form').reset();
      } catch (error) {
        console.error("Auth transaction failed:", error);
        errorBox.textContent = error.message || "Credential configuration incorrect. Verify inputs.";
        errorBox.classList.remove('hidden');
      } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = appState.authMode === 'login' ? "Deploy Session" : "Create Account";
      }
    };

    window.handleSignOut = async () => {
      if (!auth) return;
      requestConfirm(
        "Deploy Safe Sign Out?",
        "Do you wish to log out of your craftsperson account? This will gracefully shift you back to a guest profile.",
        async () => {
          try {
            await signOut(auth);
            appState.activeClient = null;
            triggerToast("Account session cleared successfully.");
          } catch (err) {
            triggerToast("Failed to sign out cleanly.", "error");
          }
        },
        "default",
        "Sign Out"
      );
    };

    const updateAuthUI = (user) => {
      const authTriggerBtn = document.getElementById('auth-trigger-btn');
      const userProfileBadge = document.getElementById('user-profile-badge');
      const avatarInitials = document.getElementById('user-avatar-initials');
      const emailDisplay = document.getElementById('user-email-display');

      if (user && !user.isAnonymous) {
        authTriggerBtn.classList.add('hidden');
        userProfileBadge.classList.remove('hidden');
        
        emailDisplay.textContent = user.email;
        const initial = user.email ? user.email.charAt(0).toUpperCase() : 'U';
        avatarInitials.textContent = initial;
      } else {
        authTriggerBtn.classList.remove('hidden');
        userProfileBadge.classList.add('hidden');
      }
    };

    // Trigger toast notification (replaces window.alert)
    window.triggerToast = (message, type = 'success') => {
      const container = document.getElementById('toast-container');
      const toast = document.createElement('div');
      toast.className = `flex items-center gap-3 px-4 py-3 rounded-xl shadow-lg border transition-all duration-300 transform translate-x-4 opacity-0 animate-fade-in pointer-events-auto ${
        type === 'error' ? 'bg-rose-50 text-rose-700 border-rose-300' :
        type === 'warning' ? 'bg-amber-50 text-amber-800 border-amber-300' :
        'bg-white text-slate-850 border-amber-500/40 shadow-slate-200/50'
      }`;
      
      const icon = type === 'error' ? 'alert-circle' : 'check-circle';
      toast.innerHTML = `
        <i data-lucide="${icon}" class="w-4 h-4 ${type === 'error' ? 'text-rose-600' : 'text-amber-600'}"></i>
        <span class="text-xs font-semibold">${message}</span>
      `;
      container.appendChild(toast);
      lucide.createIcons();
      
      setTimeout(() => {
        toast.classList.remove('translate-x-4', 'opacity-0');
      }, 50);

      setTimeout(() => {
        toast.classList.add('translate-x-4', 'opacity-0');
        setTimeout(() => toast.remove(), 350);
      }, 4000);
    };

    // Custom confirm dialog logic
    window.requestConfirm = (title, message, onConfirm, type = 'default', confirmText = 'Confirm') => {
      const modal = document.getElementById('confirmDialogModal');
      document.getElementById('confirm-dialog-title').textContent = title;
      document.getElementById('confirm-dialog-message').textContent = message;
      
      const submitBtn = document.getElementById('confirm-dialog-submit-btn');
      submitBtn.textContent = confirmText;
      submitBtn.className = `text-xs font-bold px-4 py-2 rounded-xl transition shadow-md ${
        type === 'danger' ? 'bg-rose-600 hover:bg-rose-500 text-white' : 'bg-amber-500 hover:bg-amber-600 text-slate-955'
      }`;

      const cleanSubmit = submitBtn.cloneNode(true);
      submitBtn.parentNode.replaceChild(cleanSubmit, submitBtn);
      
      cleanSubmit.addEventListener('click', () => {
        onConfirm();
        closeModal('confirmDialogModal');
      });

      document.getElementById('confirm-dialog-cancel-btn').onclick = () => closeModal('confirmDialogModal');
      openModal('confirmDialogModal');
    };

    // Lightbox image viewer controllers
    window.openImageViewer = (src, caption) => {
      const lightboxImg = document.getElementById('lightbox-image');
      const lightboxCaption = document.getElementById('lightbox-caption');
      if (lightboxImg && lightboxCaption) {
        lightboxImg.src = src;
        lightboxCaption.textContent = caption || 'Blueprint Visual Spec Detail';
        openModal('imageViewerModal');
        lucide.createIcons();
      }
    };

    // Real-Time Mechanical Deflection / Sag Estimator (Sagulator Algorithm)
    window.calculateDeflection = (dimensions, woodType) => {
      const L = parseFloat(dimensions?.length) || 0;
      const W = parseFloat(dimensions?.width) || 0;
      const T = parseFloat(dimensions?.depth) || 0;
      
      const lUnit = dimensions?.lengthUnit || 'inches';
      const wUnit = dimensions?.widthUnit || 'inches';
      const tUnit = dimensions?.depthUnit || 'inches';

      if (L <= 0 || W <= 0 || T <= 0) return null;

      // Elasticity modulus values in PSI (lb/in²)
      const modulusTable = {
        Walnut: 1680000,
        Oak: 1820000,
        Maple: 1830000,
        Cherry: 1490000,
        Pine: 1630000
      };

      const E = modulusTable[woodType] || 1500000;
      
      // Approximate densities in lb/in³
      const densities = {
        Walnut: 0.023,
        Oak: 0.027,
        Maple: 0.025,
        Cherry: 0.021,
        Pine: 0.016
      };
      
      const density = densities[woodType] || 0.022;

      // Normalize all dimensions to inches for structural mechanics calculations
      const lengthIn = convertToInches(L, lUnit);
      const widthIn = convertToInches(W, wUnit);
      const thickIn = convertToInches(T, tUnit);

      const volume = lengthIn * widthIn * thickIn;
      const weight = volume * density; // Total board weight in lbs

      // Moment of Inertia (Solid Plank): I = (W * T^3) / 12
      const I = (widthIn * Math.pow(thickIn, 3)) / 12;

      // Estimate center-load deflection under standard weight load (150 lbs load)
      const load = 150; 
      const deflectionVal = (load * Math.pow(lengthIn, 3)) / (48 * E * I);
      
      // Calculate self-weight deflection (Distributed load sag)
      const selfDef = (5 * weight * Math.pow(lengthIn, 3)) / (384 * E * I);
      const totalDef = deflectionVal + selfDef;

      return {
        weight: weight.toFixed(1),
        inertia: I.toFixed(2),
        deflection: totalDef.toFixed(3),
        rating: totalDef < 0.03 ? 'Stable (Excellent)' : totalDef < 0.09 ? 'Acceptable Flex' : 'Risk of High Sag!'
      };
    };

    // Sizing & Deflection Lab Simulator Calculator (Standalone Desktop Sandbox Model)
    window.runSimulatorCalculation = () => {
      const wood = document.getElementById('simulator-species').value;
      const length = parseFloat(document.getElementById('simulator-length').value) || 0;
      const width = parseFloat(document.getElementById('simulator-width').value) || 0;
      const thickness = parseFloat(document.getElementById('simulator-thickness').value) || 0;

      const sagData = calculateDeflection({ 
        length, lengthUnit: 'inches', 
        width, widthUnit: 'inches', 
        depth: thickness, depthUnit: 'inches' 
      }, wood);

      if (sagData) {
        document.getElementById('sim-i-val').textContent = sagData.inertia;
        document.getElementById('sim-sag-val').textContent = `${sagData.deflection}"`;

        // Update beam bending path based on calculated deflection ratio
        const normalizedDeflection = Math.min(parseFloat(sagData.deflection) * 150, 16);
        const curvePath = `M 10 20 Q 100 ${20 + normalizedDeflection} 190 20`;
        document.getElementById('simulator-beam-path').setAttribute('d', curvePath);
        document.getElementById('simulator-weight-marker').setAttribute('cy', 20 + normalizedDeflection);
      }
    };

    // Isometric SVG Blueprints Render generator (Optimized for Light Theme background)
    window.renderSVGBlueprint = (dimensions, woodType) => {
      const lRaw = parseFloat(dimensions?.length) || 48;
      const wRaw = parseFloat(dimensions?.width) || 24;
      const hRaw = parseFloat(dimensions?.height) || 30;

      const lUnit = dimensions?.lengthUnit || 'inches';
      const wUnit = dimensions?.widthUnit || 'inches';
      const hUnit = dimensions?.heightUnit || 'inches';

      // Standardize coordinates inside the isometric display grid by converting metrics to inches
      const l = convertToInches(lRaw, lUnit);
      const w = convertToInches(wRaw, wUnit);
      const h = convertToInches(hRaw, hUnit);

      const mapping = { inches: 'in', cm: 'cm', mm: 'mm', feet: 'ft' };
      const displayLUnit = mapping[lUnit] || lUnit;
      const displayWUnit = mapping[wUnit] || wUnit;
      const displayHUnit = mapping[hUnit] || hUnit;

      const woodColors = {
        Walnut: { primary: '#5c3a21', line: '#b45309', bg: 'rgba(92, 58, 33, 0.12)' },
        Oak: { primary: '#a18262', line: '#78350f', bg: 'rgba(161, 130, 98, 0.12)' },
        Maple: { primary: '#dfc495', line: '#b45309', bg: 'rgba(223, 196, 149, 0.12)' },
        Cherry: { primary: '#7c2d12', line: '#c2410c', bg: 'rgba(124, 45, 18, 0.12)' },
        Pine: { primary: '#d97706', line: '#b45309', bg: 'rgba(217, 119, 6, 0.12)' }
      };

      const activeWood = woodColors[woodType] || woodColors.Walnut;
      
      const cos30 = 0.866;
      const sin30 = 0.5;
      const vertices = [
        { x: 0, y: 0, z: 0 }, { x: l, y: 0, z: 0 }, { x: 0, y: w, z: 0 }, { x: l, y: w, z: 0 },
        { x: 0, y: 0, z: h }, { x: l, y: 0, z: h }, { x: 0, y: w, z: h }, { x: l, y: w, z: h }
      ];

      const projected = vertices.map(v => ({
        u: v.x * cos30 - v.y * cos30,
        v: v.x * sin30 + v.y * sin30 - v.z
      }));

      const uCoords = projected.map(p => p.u);
      const vCoords = projected.map(p => p.v);
      const minU = Math.min(...uCoords);
      const maxU = Math.max(...uCoords);
      const minV = Math.min(...vCoords);
      const maxV = Math.max(...vCoords);

      const spanU = maxU - minU || 1;
      const spanV = maxV - minV || 1;
      const finalScale = Math.min(220 / spanU, 120 / spanV);

      const finalPoints = projected.map(p => ({
        x: 150 + (p.u - (minU + maxU) / 2) * finalScale,
        y: 100 + (p.v - (minV + maxV) / 2) * finalScale
      }));

      const edges = [
        [0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]
      ];

      let edgesSVG = '';
      edges.forEach(([p1, p2], idx) => {
        const strokeColor = idx >= 4 && idx < 8 ? activeWood.line : 'rgba(15, 23, 42, 0.18)';
        const strokeWidth = idx >= 4 && idx < 8 ? '2' : '1';
        const strokeDash = (p1 === 0 || p2 === 0 || p1 === 2 || p2 === 2) ? '3,3' : '0';
        edgesSVG += `<line x1="${finalPoints[p1].x}" y1="${finalPoints[p1].y}" x2="${finalPoints[p2].x}" y2="${finalPoints[p2].y}" stroke="${strokeColor}" stroke-width="${strokeWidth}" stroke-dasharray="${strokeDash}" />`;
      });

      return `
        <svg viewBox="0 0 300 200" class="w-full h-44 drop-shadow-sm">
          <defs>
            <rect id="grid" width="15" height="15" fill="none" stroke="rgba(15, 23, 42, 0.02)" stroke-width="0.5"/>
            <pattern id="grid-pattern" width="15" height="15" patternUnits="userSpaceOnUse">
              <path d="M 15 0 L 0 0 0 15" fill="none" stroke="rgba(15, 23, 42, 0.02)" stroke-width="0.5"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#grid-pattern)" />
          <polygon points="${finalPoints[4].x},${finalPoints[4].y} ${finalPoints[5].x},${finalPoints[5].y} ${finalPoints[7].x},${finalPoints[7].y} ${finalPoints[6].x},${finalPoints[6].y}" fill="${activeWood.bg}" stroke="transparent" />
          <polygon points="${finalPoints[0].x},${finalPoints[0].y} ${finalPoints[1].x},${finalPoints[1].y} ${finalPoints[5].x},${finalPoints[5].y} ${finalPoints[4].x},${finalPoints[4].y}" fill="rgba(15, 23, 42, 0.01)" stroke="transparent" />
          <polygon points="${finalPoints[1].x},${finalPoints[1].y} ${finalPoints[3].x},${finalPoints[3].y} ${finalPoints[7].x},${finalPoints[7].y} ${finalPoints[5].x},${finalPoints[5].y}" fill="rgba(0,0,0,0.04)" stroke="transparent" />
          ${edgesSVG}
          <circle cx="${finalPoints[0].x}" cy="${finalPoints[0].y}" r="2.5" fill="#d97706" />
          <circle cx="${finalPoints[1].x}" cy="${finalPoints[1].y}" r="2.5" fill="#d97706" />
          <circle cx="${finalPoints[5].x}" cy="${finalPoints[5].y}" r="2.5" fill="#d97706" />
          <text x="${finalPoints[5].x + 10}" y="${finalPoints[5].y - 10}" fill="#b45309" font-size="8" font-family="monospace" font-weight="bold">${hRaw} ${displayHUnit} (H)</text>
          <text x="${(finalPoints[4].x + finalPoints[5].x)/2}" y="${(finalPoints[4].y + finalPoints[5].y)/2 - 8}" fill="#64748b" font-size="8" font-family="monospace" text-anchor="middle">L: ${lRaw} ${displayLUnit}</text>
          <text x="${(finalPoints[5].x + finalPoints[7].x)/2 + 10}" y="${(finalPoints[5].y + finalPoints[7].y)/2 + 4}" fill="#64748b" font-size="8" font-family="monospace">W: ${wRaw} ${displayWUnit}</text>
        </svg>
      `;
    };

    const renderClientLedger = () => {
      const activeFoldersContainer = document.getElementById('stat-active-folders');
      const loggedSpecsContainer = document.getElementById('stat-logged-specs');
      
      const activeFolderCount = appState.clients.length;
      const loggedSpecsCount = appState.clients.reduce((acc, c) => acc + (c.items?.length || 0), 0);
      
      if (activeFoldersContainer) activeFoldersContainer.textContent = activeFolderCount;
      if (loggedSpecsContainer) loggedSpecsContainer.textContent = loggedSpecsCount;

      const ledgerContainer = document.getElementById('client-ledger-list');
      if (!ledgerContainer) return;

      const filtered = appState.clients.filter(c => {
        const matchesSearch = c.name.toLowerCase().includes(appState.searchTerm.toLowerCase()) || 
                              (c.email && c.email.toLowerCase().includes(appState.searchTerm.toLowerCase())) ||
                              (c.notes && c.notes.toLowerCase().includes(appState.searchTerm.toLowerCase()));
        const matchesCategory = appState.categoryFilter === 'All' || c.category === appState.categoryFilter;
        return matchesSearch && matchesCategory;
      });

      if (filtered.length === 0) {
        ledgerContainer.innerHTML = `
          <div class="bg-white border border-slate-200 rounded-2xl py-12 px-4 text-center shadow-sm">
            <i data-lucide="compass" class="w-8 h-8 text-slate-400 mx-auto mb-2"></i>
            <p class="text-xs font-semibold text-slate-500 font-mono">Ledger index empty</p>
          </div>
        `;
        lucide.createIcons();
        return;
      }

      ledgerContainer.innerHTML = filtered.map(client => {
        const isCurrent = appState.activeClient?.id === client.id;
        const itemLength = client.items?.length || 0;
        const siteLength = client.siteMeasures?.length || 0;

        return `
          <div onclick="selectClient('${client.id}')" class="group w-full text-left p-3.5 rounded-xl border transition cursor-pointer relative overflow-hidden flex items-start gap-3 ${
            isCurrent ? 'bg-white border-amber-500 shadow-md' : 'bg-white border-slate-200 hover:bg-slate-50/60'
          }">
            ${isCurrent ? '<div class="absolute top-0 bottom-0 left-0 w-1 bg-amber-500"></div>' : ''}
            <div class="bg-slate-50 p-2.5 rounded-lg text-slate-500 group-hover:text-amber-600 transition flex items-center justify-center border border-slate-100">
              <i data-lucide="user" class="w-4 h-4"></i>
            </div>
            <div class="flex-1 min-w-0">
              <div class="flex items-center justify-between gap-1 mb-1">
                <h4 class="font-bold text-xs text-slate-800 truncate">${client.name}</h4>
                <span class="text-[9px] px-1.5 py-0.5 rounded font-mono font-semibold ${
                  client.status === 'Approved' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' :
                  client.status === 'In Production' ? 'bg-amber-50 text-amber-705 border border-amber-200' : 'bg-slate-100 text-slate-500 border border-slate-200'
                }">${client.status || 'Design'}</span>
              </div>
              <p class="text-[11px] text-slate-500 truncate mb-2">${client.notes || 'No project description brief registered.'}</p>
              <div class="flex items-center justify-between text-[10px] text-slate-400 border-t border-slate-100 pt-2 mt-1">
                <span class="flex items-center gap-1.5 font-mono text-slate-500">
                  <i data-lucide="layers" class="w-3 h-3 text-slate-400"></i><span>${itemLength} items</span>
                  <span class="text-slate-305">•</span>
                  <i data-lucide="home" class="w-3 h-3 text-slate-400"></i><span>${siteLength} sites</span>
                </span>
                <button onclick="shareClientManual(event, '${client.id}')" class="text-slate-500 hover:text-amber-600 flex items-center gap-1 transition">
                  <i data-lucide="share-2" class="w-3 h-3"></i> Share
                </button>
              </div>
            </div>
          </div>
        `;
      }).join('');

      lucide.createIcons();
    };

    const renderCategoryFilters = () => {
      const container = document.getElementById('category-filters-container');
      const categories = ['All', 'Furniture', 'Commercial Fit', 'Apparel', 'Art', 'Custom'];
      
      container.innerHTML = categories.map(cat => {
        const active = appState.categoryFilter === cat;
        return `
          <button onclick="selectCategoryFilter('${cat}')" class="text-[10px] font-bold px-2.5 py-1 rounded-lg border transition ${
            active ? 'bg-amber-500 text-slate-950 border-amber-500 shadow-sm' : 'bg-white text-slate-500 border-slate-205 hover:bg-slate-50'
          }">${cat}</button>
        `;
      }).join('');
    };

    const renderWorkspaceDetails = () => {
      const activeClient = appState.activeClient;
      if (!activeClient) {
        document.getElementById('empty-workspace-state')?.classList.remove('hidden');
        document.getElementById('active-workspace-state')?.classList.add('hidden');
        return;
      } else {
        document.getElementById('empty-workspace-state')?.classList.add('hidden');
        document.getElementById('active-workspace-state')?.classList.remove('hidden');
      }

      document.getElementById('active-client-category-badge').textContent = `${activeClient.category} Specifications Folder`;
      document.getElementById('active-client-title').textContent = activeClient.name;
      document.getElementById('active-client-objectives').textContent = activeClient.notes || 'No initial custom brief registered.';
      
      const emailField = document.getElementById('active-client-email');
      const phoneField = document.getElementById('active-client-phone');
      if (activeClient.email) {
        emailField.innerHTML = `<i data-lucide="mail" class="w-3.5 h-3.5 text-slate-400 flex items-center justify-center"></i> ${activeClient.email}`;
        emailField.classList.remove('hidden');
      } else {
        emailField.classList.add('hidden');
      }
      if (activeClient.phone) {
        phoneField.innerHTML = `<i data-lucide="phone" class="w-3.5 h-3.5 text-slate-400 flex items-center justify-center"></i> ${activeClient.phone}`;
        phoneField.classList.remove('hidden');
      } else {
        phoneField.classList.add('hidden');
      }

      const statusContainer = document.getElementById('pipeline-status-controls');
      const statuses = ['Design Phase', 'In Production', 'Approved'];
      statusContainer.innerHTML = statuses.map(status => {
        const isActive = activeClient.status === status;
        return `
          <button onclick="updatePipelineStatus('${status}')" class="text-[9px] font-bold px-2 py-1 rounded border transition ${
            isActive ? 'bg-amber-500 border-amber-500 text-slate-955 font-black' : 'bg-slate-50 text-slate-500 border-slate-200 hover:bg-slate-100'
          }">
            ${status}
          </button>
        `;
      }).join('');

      const workpiecesCount = activeClient.items?.length || 0;
      const siteCount = (activeClient.siteMeasures || []).length;
      document.getElementById('tab-workpieces-count').textContent = workpiecesCount;
      document.getElementById('tab-site-count').textContent = siteCount;

      renderTabContent();
      renderFeedbackStream();
    };

    const renderTabContent = () => {
      const container = document.getElementById('tab-content-container');
      const client = appState.activeClient;
      if (!client) return;

      const mapping = { inches: 'in', cm: 'cm', mm: 'mm', feet: 'ft' };

      if (appState.activeTab === 'workpieces') {
        document.getElementById('tab-workpieces-btn').className = "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-605 font-black transition";
        document.getElementById('tab-site-btn').className = "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-800 transition";
        document.getElementById('tab-action-text').textContent = "Log Workpiece";

        if (!client.items || client.items.length === 0) {
          container.innerHTML = `
            <div class="bg-white border border-slate-205 rounded-2xl p-12 text-center shadow-sm">
              <i data-lucide="ruler" class="w-10 h-10 text-slate-300 mx-auto mb-2.5"></i>
              <h3 class="text-slate-500 font-bold text-sm font-mono">Specification registry currently empty</h3>
              <p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto leading-relaxed">Click "Log Workpiece" to register architectural specifications.</p>
            </div>
          `;
          lucide.createIcons();
          return;
        }

        container.innerHTML = `
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 animate-fade-in">
            ${client.items.map(item => {
              const dims = item.dimensions || {};
              const l = parseFloat(dims.length) || 0;
              const w = parseFloat(dims.width) || 0;
              const h = parseFloat(dims.height) || 0;
              const d = parseFloat(dims.depth) || 0;

              const lUnit = dims.lengthUnit || 'inches';
              const wUnit = dims.widthUnit || 'inches';
              const hUnit = dims.heightUnit || 'inches';
              const dUnit = dims.depthUnit || 'inches';

              const displayLUnit = mapping[lUnit] || lUnit;
              const displayWUnit = mapping[wUnit] || wUnit;
              const displayHUnit = mapping[hUnit] || hUnit;
              const displayDUnit = mapping[dUnit] || dUnit;

              const currentWood = item.woodType || 'Walnut';
              
              // Normalize to inches for accurate Board Feet (BF) estimations
              const lIn = convertToInches(l, lUnit);
              const wIn = convertToInches(w, wUnit);
              const dIn = convertToInches(d, dUnit);
              const boardFeet = ((lIn * wIn * dIn) / 144);
              const formattedBF = boardFeet.toFixed(2);

              const rates = { Walnut: 14.50, Oak: 9.25, Maple: 8.50, Cherry: 11.20, Pine: 4.80 };
              const rate = rates[currentWood] || 12.00;
              const estimatedCost = (boardFeet * rate).toFixed(2);

              // Calculate deflection sag parameters
              const sagData = calculateDeflection(item.dimensions, currentWood);

              return `
                <div id="workpiece-card-${item.id}" class="bg-white border border-slate-200 rounded-2xl overflow-hidden flex flex-col hover:border-slate-300 transition group shadow-sm relative animate-fade-in">
                  <div class="p-3 bg-slate-50 border-b border-slate-100">
                    ${renderSVGBlueprint(item.dimensions, currentWood)}
                  </div>
                  ${item.images && item.images.length > 0 ? `
                    <div onclick="openImageViewer('${item.images[0]}', '${item.title}')" class="h-32 bg-slate-100 overflow-hidden relative flex items-center justify-center border-b border-slate-200 cursor-zoom-in">
                      <img src="${item.images[0]}" alt="${item.title}" class="w-full h-full object-cover group-hover:scale-[1.03] transition duration-500" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?auto=format&fit=crop&w=400&q=80'" />
                      <div class="absolute inset-0 bg-slate-900/10 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
                        <span class="bg-white border border-slate-200 p-2 rounded-xl text-slate-700 text-[9px] font-mono flex items-center gap-1.5 shadow-md">
                          <i data-lucide="zoom-in" class="w-3.5 h-3.5 text-amber-600"></i> Zoom Image Specs
                        </span>
                      </div>
                    </div>
                  ` : ''}
                  <div class="p-4 flex-1 flex flex-col gap-3">
                    <div class="flex items-start justify-between">
                      <div class="flex-1 min-w-0 pr-2">
                        <h4 class="font-extrabold text-xs text-slate-805 group-hover:text-amber-700 transition-colors truncate">${item.title}</h4>
                        ${item.notes ? `<p class="text-[11px] text-slate-500 mt-1.5 line-clamp-2 leading-relaxed italic">"${item.notes}"</p>` : ''}
                      </div>
                      <div class="flex items-center gap-1 flex-shrink-0">
                        <button onclick="openEditWorkpieceModal('${item.id}')" class="text-slate-400 hover:text-amber-605 p-1 rounded-lg transition-all border border-transparent" title="Edit workpiece spec">
                          <i data-lucide="edit" class="w-3.5 h-3.5"></i>
                        </button>
                        <button onclick="deleteItemSpec('${item.id}')" class="text-slate-400 hover:text-rose-600 p-1 rounded-lg transition-all border border-transparent" title="Discard Blueprints">
                          <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                        </button>
                      </div>
                    </div>

                    <!-- Material Selector -->
                    <div class="bg-slate-50 border border-slate-100 p-2.5 rounded-xl text-[10px] space-y-1.5">
                      <div class="flex items-center justify-between text-slate-400">
                        <span class="font-semibold uppercase tracking-wider font-mono text-[9px] flex items-center gap-1 text-slate-650">
                          <i data-lucide="sliders" class="w-3 h-3 text-amber-600"></i> Material Choice
                        </span>
                        <select onchange="updateItemWoodMaterial('${item.id}', this.value)" class="bg-white border border-slate-205 text-amber-700 rounded px-1.5 py-0.5 text-[9px] font-mono focus:outline-none font-bold">
                          <option value="Walnut" ${currentWood === 'Walnut' ? 'selected' : ''}>Walnut Slab</option>
                          <option value="Oak" ${currentWood === 'Oak' ? 'selected' : ''}>White Oak</option>
                          <option value="Maple" ${currentWood === 'Maple' ? 'selected' : ''}>Hard Maple</option>
                          <option value="Cherry" ${currentWood === 'Cherry' ? 'selected' : ''}>Black Cherry</option>
                          <option value="Pine" ${currentWood === 'Pine' ? 'selected' : ''}>Yellow Pine</option>
                        </select>
                      </div>
                      <div class="grid grid-cols-2 gap-2 text-center border-t border-slate-200/50 pt-1.5">
                        <div class="bg-white p-1.5 rounded font-mono border border-slate-100">
                          <span class="text-[7.5px] text-slate-400 block leading-none">EST. VOLUME</span>
                          <span class="text-slate-700 font-bold block mt-0.5 text-[10.5px]">${formattedBF} <span class="text-[8px] text-slate-400 font-bold">BF</span></span>
                        </div>
                        <div class="bg-white p-1.5 rounded font-mono border border-slate-100">
                          <span class="text-[7.5px] text-slate-400 block leading-none">EST. WOOD COST</span>
                          <span class="text-emerald-600 font-bold block mt-0.5 text-[10.5px]">$${estimatedCost}</span>
                        </div>
                      </div>
                    </div>

                    <!-- Material Physics (Live Calculation Module) -->
                    ${sagData ? `
                    <div class="bg-slate-50 border border-slate-100 p-2.5 rounded-xl text-[10px] font-mono space-y-1">
                      <div class="flex justify-between items-center text-[8px] text-slate-400 font-bold uppercase tracking-wider">
                        <span>Material Physics (Sagulator)</span>
                        <span class="text-amber-700 font-extrabold">${sagData.rating}</span>
                      </div>
                      <div class="grid grid-cols-2 gap-1.5 pt-1.5 border-t border-slate-200/50">
                        <div class="flex justify-between">
                          <span class="text-slate-400">Net Weight:</span>
                          <span class="text-slate-700 font-bold">${sagData.weight} lbs</span>
                        </div>
                        <div class="flex justify-between">
                          <span class="text-slate-400">Max Sag:</span>
                          <span class="text-slate-700 font-bold">${sagData.deflection} in</span>
                        </div>
                      </div>
                    </div>
                    ` : ''}

                    <!-- Custom Craftsman Measured By Display -->
                    <div class="flex justify-between items-center text-[10px] text-slate-500 font-mono bg-slate-50 p-2 rounded-lg border border-slate-100">
                      <span>Measured By:</span>
                      <span class="font-bold text-amber-800">${item.measuredBy || 'Lead Designer'}</span>
                    </div>

                    <!-- Sizes -->
                    <div class="bg-slate-50 rounded-xl p-2.5 border border-slate-100 mt-auto font-mono">
                      <span class="text-[9px] uppercase font-bold text-slate-400 tracking-wider block mb-1">Architectural Sizing</span>
                      <div class="grid grid-cols-4 gap-1 text-center text-[10px]">
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">LENGTH</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${l || '-'} <span class="text-[8.5px] text-slate-400 font-bold lowercase">${displayLUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">WIDTH</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${w || '-'} <span class="text-[8.5px] text-slate-400 font-bold lowercase">${displayWUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">HEIGHT</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${h || '-'} <span class="text-[8.5px] text-slate-400 font-bold lowercase">${displayHUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">THICKNESS</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${d || '-'} <span class="text-[8.5px] text-slate-400 font-bold lowercase">${displayDUnit}</span></span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              `;
            }).join('')}
          </div>
        `;
      } else {
        document.getElementById('tab-workpieces-btn').className = "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-800 transition";
        document.getElementById('tab-site-btn').className = "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-605 font-black transition";
        document.getElementById('tab-action-text').textContent = "Add Site Dimensions";

        if (!client.siteMeasures || client.siteMeasures.length === 0) {
          container.innerHTML = `
            <div class="bg-white border border-slate-205 rounded-2xl p-12 text-center shadow-sm">
              <i data-lucide="home" class="w-10 h-10 text-slate-300 mx-auto mb-2.5"></i>
              <h3 class="text-slate-500 font-bold text-sm font-mono">Location clearance logs empty</h3>
              <p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto leading-relaxed">Record physical clearances to ensure flawless assemblies.</p>
            </div>
          `;
          lucide.createIcons();
          return;
        }

        container.innerHTML = `
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 animate-fade-in">
            ${client.siteMeasures.map(site => {
              const dims = site.dimensions || {};
              const l = parseFloat(dims.length) || 0;
              const w = parseFloat(dims.width) || 0;
              const h = parseFloat(dims.height) || 0;
              const d = parseFloat(dims.depth) || 0;

              const lUnit = dims.lengthUnit || 'inches';
              const wUnit = dims.widthUnit || 'inches';
              const hUnit = dims.heightUnit || 'inches';
              const dUnit = dims.depthUnit || 'inches';

              const displayLUnit = mapping[lUnit] || lUnit;
              const displayWUnit = mapping[wUnit] || wUnit;
              const displayHUnit = mapping[hUnit] || hUnit;
              const displayDUnit = mapping[dUnit] || dUnit;

              return `
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden flex flex-col hover:border-slate-300 transition group shadow-sm relative animate-fade-in">
                  <div class="h-44 bg-slate-50 relative overflow-hidden flex items-center justify-center border-b border-slate-100">
                    ${site.images && site.images.length > 0 ? `
                      <img src="${site.images[0]}" alt="${site.label}" onclick="openImageViewer('${site.images[0]}', '${site.label}')" class="w-full h-full object-cover cursor-zoom-in" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1504307651254-35680f356dfd?auto=format&fit=crop&w=400&q=80'" />
                      <div onclick="openImageViewer('${site.images[0]}', '${site.label}')" class="absolute inset-0 bg-slate-900/10 opacity-0 group-hover:opacity-100 transition flex items-center justify-center cursor-zoom-in">
                        <span class="bg-white border border-slate-200 p-2 rounded-xl text-slate-700 text-[9px] font-mono flex items-center gap-1.5 shadow-md">
                          <i data-lucide="zoom-in" class="w-3.5 h-3.5 text-amber-600"></i> Zoom Clearance Media
                        </span>
                      </div>
                    ` : `
                      <div class="flex flex-col items-center gap-1.5 text-slate-350">
                        <i data-lucide="camera" class="w-6 h-6 stroke-[1.5]"></i>
                        <span class="text-[9px] tracking-widest uppercase font-black font-mono font-bold">No photos registered</span>
                      </div>
                    `}
                    <div class="absolute top-2.5 right-2.5 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all z-10">
                      <button onclick="openEditSiteMeasureModal('${site.id}')" class="bg-white/90 hover:bg-white text-slate-505 hover:text-amber-600 p-1.5 rounded-lg border border-slate-200 shadow animate-fade-in" title="Edit site spec">
                        <i data-lucide="edit" class="w-3.5 h-3.5 flex items-center justify-center"></i>
                      </button>
                      <button onclick="deleteSiteSpec('${site.id}')" class="bg-white/90 hover:bg-rose-50 text-slate-505 hover:text-rose-600 p-1.5 rounded-lg border border-slate-200 shadow animate-fade-in" title="Purge site blueprints">
                        <i data-lucide="trash-2" class="w-3.5 h-3.5 flex items-center justify-center"></i>
                      </button>
                    </div>
                  </div>
                  <div class="p-4 flex-1 flex flex-col gap-3">
                    <div>
                      <div class="flex items-center gap-1.5 mb-1">
                        <i data-lucide="map-pin" class="w-3.5 h-3.5 text-amber-600"></i>
                        <h4 class="font-extrabold text-xs text-slate-800 group-hover:text-amber-700 transition-colors truncate">${site.label}</h4>
                      </div>
                      ${site.notes ? `<p class="text-[11px] text-slate-500 mt-1.5 line-clamp-2 leading-relaxed italic">"${site.notes}"</p>` : ''}
                    </div>

                    <!-- Custom Surveyor Name Display -->
                    <div class="flex justify-between items-center text-[10px] text-slate-500 font-mono bg-slate-50 p-2 rounded-lg border border-slate-100">
                      <span>Verified By:</span>
                      <span class="font-bold text-amber-850">${site.measuredBy || 'Lead Designer'}</span>
                    </div>

                    <div class="bg-slate-50 rounded-xl p-2.5 border border-slate-100 mt-auto font-mono">
                      <span class="text-[9px] uppercase font-bold text-slate-400 tracking-wider block mb-1">Physical Clearance Perimeter</span>
                      <div class="grid grid-cols-4 gap-1 text-center text-[10px]">
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">LENGTH</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${l || '-'} <span class="text-[8.5px] text-slate-450 font-bold lowercase">${displayLUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">WIDTH</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${w || '-'} <span class="text-[8.5px] text-slate-450 font-bold lowercase">${displayWUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">HEIGHT</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${h || '-'} <span class="text-[8.5px] text-slate-450 font-bold lowercase">${displayHUnit}</span></span>
                        </div>
                        <div class="bg-white py-1.5 rounded-lg border border-slate-150">
                          <span class="text-[7.5px] text-slate-400 block leading-none">GAP BUFFER</span>
                          <span class="text-slate-700 font-extrabold block mt-0.5">${d || '-'} <span class="text-[8.5px] text-slate-450 font-bold lowercase">${displayDUnit}</span></span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              `;
            }).join('')}
          </div>
        `;
      }
      lucide.createIcons();
    };

    const renderFeedbackStream = () => {
      const activeClient = appState.activeClient;
      const streamContainer = document.getElementById('client-feedback-feed-stream');
      if (!streamContainer) return;

      if (!activeClient.feedback || activeClient.feedback.length === 0) {
        streamContainer.innerHTML = `<p class="text-xs text-slate-400 italic font-medium font-mono">No live reviews logged. Share access portal with your client to initiate verification loops.</p>`;
        return;
      }

      streamContainer.innerHTML = activeClient.feedback.map(f => {
        const senderColor = f.sender === 'Client' ? 'text-amber-700' : f.sender === 'System' ? 'text-emerald-600 font-extrabold' : 'text-slate-500';
        return `
          <div class="bg-slate-50 p-3 rounded-xl border border-slate-100 text-[11px] leading-relaxed animate-fade-in">
            <div class="flex items-center justify-between mb-1.5">
              <span class="font-extrabold text-[9px] uppercase tracking-wider ${senderColor} font-mono">${f.sender}</span>
              <span class="text-[9px] text-slate-400 font-mono">${new Date(f.timestamp).toLocaleDateString()}</span>
            </div>
            <p class="text-slate-655">${f.text}</p>
          </div>
        `;
      }).join('');
    };

    // Client directory interactions
    window.selectClient = (id) => {
      const client = appState.clients.find(c => c.id === id);
      if (client) {
        appState.activeClient = client;
        document.getElementById('empty-workspace-state').classList.add('hidden');
        document.getElementById('active-workspace-state').classList.remove('hidden');
        renderClientLedger();
        renderWorkspaceDetails();

        document.getElementById('delete-client-btn').onclick = () => handleDeleteClient(client.id);
      }
    };

    window.selectCategoryFilter = (cat) => {
      appState.categoryFilter = cat;
      renderCategoryFilters();
      renderClientLedger();
    };

    window.triggerSearch = (val) => {
      appState.searchTerm = val;
      renderClientLedger();
    };

    window.setActiveTab = (tab) => {
      appState.activeTab = tab;
      renderTabContent();
    };

    window.updateItemWoodMaterial = async (itemId, wood) => {
      const client = appState.activeClient;
      if (!client) return;

      const updatedItems = client.items.map(item => {
        if (item.id === itemId) {
          return { ...item, woodType: wood };
        }
        return item;
      });

      await updateClientData(client.id, { items: updatedItems });
      triggerToast(`Material changed to ${wood}`);
    };

    // Initiate new Client spec workspace folder
    window.handleAddClientSubmit = async (e) => {
      e.preventDefault();
      const name = document.getElementById('new-client-name').value;
      const email = document.getElementById('new-client-email').value;
      const phone = document.getElementById('new-client-phone').value;
      const category = document.getElementById('new-client-category').value;
      const notes = document.getElementById('new-client-notes').value;

      const payload = {
        name, email, phone, category, notes,
        status: 'Design Phase',
        items: [],
        siteMeasures: [],
        feedback: [],
        createdAt: Date.now(),
        updatedAt: Date.now()
      };

      if (!appState.isOffline && db) {
        try {
          const colRef = collection(db, 'artifacts', appId, 'users', getActiveUserId(), 'clients');
          const docRef = await addDoc(colRef, payload);
          triggerToast(`Specs folder for ${name} initialized!`);
        } catch (err) {
          triggerToast("Cloud offline, saved locally.", "warning");
          commitLocalMock([{ id: 'local-' + Date.now(), ...payload }, ...appState.clients]);
        }
      } else {
        commitLocalMock([{ id: 'local-' + Date.now(), ...payload }, ...appState.clients]);
        triggerToast(`Local ledger created for ${name}`);
      }

      document.getElementById('add-client-form').reset();
      closeModal('addClientModal');
    };

    const commitLocalMock = (updatedList) => {
      appState.clients = updatedList;
      localStorage.setItem('cs_mock_clients_v2', JSON.stringify(updatedList));
      renderClientLedger();
    };

    // Complete portfolio folder discard routines
    const handleDeleteClient = (clientId) => {
      requestConfirm(
        "Scrub Client Portfolio?",
        "Warning: This will permanently delete this craftsman spec folder and all registered site measurement data. This action is irreversible.",
        async () => {
          if (!appState.isOffline && db) {
            try {
              const docRef = doc(db, 'artifacts', appId, 'users', getActiveUserId(), 'clients', clientId);
              await deleteDoc(docRef);
              appState.activeClient = null;
              triggerToast("Spec database records wiped.");
              renderClientLedger();
              document.getElementById('active-workspace-state').classList.add('hidden');
              document.getElementById('empty-workspace-state').classList.remove('hidden');
            } catch (err) {
              triggerToast("Cloud sync offline, wiped local cache copy.", "warning");
              const listCopy = appState.clients.filter(c => c.id !== clientId);
              commitLocalMock(listCopy);
              appState.activeClient = null;
              renderClientLedger();
            }
          } else {
            const listCopy = appState.clients.filter(c => c.id !== clientId);
            commitLocalMock(listCopy);
            appState.activeClient = null;
            renderClientLedger();
            triggerToast("Wiped spec registry from local cache.");
          }
        },
        "danger",
        "Wipe Spec Folder"
      );
    };

    // Client portal sharing setups containing owner UID parameters
    window.shareActiveClient = () => {
      const active = appState.activeClient;
      if (!active) return;
      shareClientManual(null, active.id);
    };

    window.shareClientManual = (e, id) => {
      if (e) e.stopPropagation();
      const target = appState.clients.find(c => c.id === id);
      if (!target) return;

      document.getElementById('share-modal-client-name').textContent = target.name;
      
      const origin = window.location.origin + window.location.pathname;
      const shareLink = `${origin}?client=${target.id}&owner=${getActiveUserId()}`;
      document.getElementById('share-modal-link-preview').textContent = shareLink;

      openModal('shareSpecModal');
    };

    window.copyShareLinkToClipboard = () => {
      const text = document.getElementById('share-modal-link-preview').textContent;
      const fillTextArea = document.createElement("textarea");
      fillTextArea.value = text;
      fillTextArea.style.top = "0";
      fillTextArea.style.left = "0";
      fillTextArea.style.position = "fixed";
      document.body.appendChild(fillTextArea);
      fillTextArea.focus();
      fillTextArea.select();
      
      try {
        document.execCommand('copy');
        triggerToast("Workspace credentials compiled and copied!");
      } catch (err) {
        triggerToast("Clipboard transfer blocked.", "error");
      } finally {
        document.body.removeChild(fillTextArea);
      }
    };

    window.openPortalLinkDirectly = () => {
      const link = document.getElementById('share-modal-link-preview').textContent;
      window.open(link, '_blank');
    };

    window.shareToWhatsAppDirectly = () => {
      const link = document.getElementById('share-modal-link-preview').textContent;
      const targetName = document.getElementById('share-modal-client-name').textContent;
      const text = `Hi ${targetName}, here are the layout specifications and dimensions for your custom workspace project: ${link}`;
      window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, '_blank');
    };

    // Dialog trigger controls
    window.openModal = (id) => {
      document.getElementById(id)?.classList.remove('hidden');
    };

    window.closeModal = (id) => {
      document.getElementById(id)?.classList.add('hidden');
    };

    window.toggleEditStudio = (edit) => {
      if (edit) {
        document.getElementById('studio-branding-container').classList.add('hidden');
        document.getElementById('studio-name-edit-form').classList.remove('hidden');
        document.getElementById('studio-name-input').value = appState.studioName;
      } else {
        document.getElementById('studio-branding-container').classList.remove('hidden');
        document.getElementById('studio-name-edit-form').classList.add('hidden');
      }
    };

    window.saveStudioName = () => {
      const name = document.getElementById('studio-name-input').value;
      appState.studioName = name;
      localStorage.setItem('cs_studio_name', name);
      document.getElementById('studio-name-display').textContent = name;
      toggleEditStudio(false);
      triggerToast("Studio branding configurations saved!");
    };

    window.toggleFormVisibility = () => {
      if (appState.activeTab === 'workpieces') {
        openModal('addWorkpieceModal');
      } else {
        openModal('addSiteMeasureModal');
      }
    };

    const updateClientData = async (clientId, updatedFields) => {
      const clientIndex = appState.clients.findIndex(c => c.id === clientId);
      if (clientIndex === -1) return;

      const updatedClient = {
        ...appState.clients[clientIndex],
        ...updatedFields,
        updatedAt: Date.now()
      };

      if (!appState.isOffline && db) {
        try {
          const docRef = doc(db, 'artifacts', appId, 'users', getActiveUserId(), 'clients', clientId);
          await updateDoc(docRef, {
            ...updatedFields,
            updatedAt: Date.now()
          });
        } catch (err) {
          console.error("Firestore update failed, falling back to local:", err);
          commitLocalMock(appState.clients.map(c => c.id === clientId ? updatedClient : c));
        }
      } else {
        commitLocalMock(appState.clients.map(c => c.id === clientId ? updatedClient : c));
      }
      
      appState.activeClient = updatedClient;
      renderWorkspaceDetails();
      renderClientLedger();
    };

    // Edit Workpiece Modal populate trigger
    window.openEditWorkpieceModal = (itemId) => {
      const client = appState.activeClient;
      if (!client) return;
      const item = client.items.find(it => it.id === itemId);
      if (!item) return;

      appState.editingItemId = itemId;
      document.getElementById('workpiece-modal-heading').innerHTML = `<i data-lucide="edit" class="w-4 h-4 text-amber-600"></i> Edit Workpiece Dimensions`;
      document.getElementById('workpiece-modal-submit-btn').textContent = 'Save Specifications';

      document.getElementById('workpiece-title').value = item.title || '';
      document.getElementById('workpiece-measured-by').value = item.measuredBy || 'Lead Designer';
      document.getElementById('workpiece-length').value = item.dimensions?.length || '';
      document.getElementById('workpiece-length-unit').value = item.dimensions?.lengthUnit || 'inches';
      document.getElementById('workpiece-width').value = item.dimensions?.width || '';
      document.getElementById('workpiece-width-unit').value = item.dimensions?.widthUnit || 'inches';
      document.getElementById('workpiece-height').value = item.dimensions?.height || '';
      document.getElementById('workpiece-height-unit').value = item.dimensions?.heightUnit || 'inches';
      document.getElementById('workpiece-depth').value = item.dimensions?.depth || '';
      document.getElementById('workpiece-depth-unit').value = item.dimensions?.depthUnit || 'inches';
      document.getElementById('workpiece-notes').value = item.notes || '';
      
      appState.tempItemImages = item.images || [];
      const previewContainer = document.getElementById('workpiece-images-preview');
      previewContainer.innerHTML = appState.tempItemImages.map(img => `
        <div class="w-16 h-16 rounded-xl overflow-hidden border border-slate-200 relative group bg-white shadow-sm animate-fade-in">
          <img src="${img}" alt="Preview" class="w-full h-full object-cover cursor-pointer" onclick="openImageViewer('${img}', 'Workpiece Detail Inspect')" />
          <button type="button" onclick="removeTempImage('${img}', 'workpiece', this)" class="absolute inset-x-0 bottom-0 bg-rose-500/90 text-white py-1 text-[8.5px] text-center opacity-0 group-hover:opacity-100 transition duration-200 font-bold font-mono">Remove</button>
        </div>
      `).join('');

      openModal('addWorkpieceModal');
      lucide.createIcons();
    };

    // Edit Site Clearance Modal populate trigger
    window.openEditSiteMeasureModal = (siteId) => {
      const client = appState.activeClient;
      if (!client) return;
      const site = client.siteMeasures.find(s => s.id === siteId);
      if (!site) return;

      appState.editingSiteId = siteId;
      document.getElementById('site-modal-heading').innerHTML = `<i data-lucide="edit" class="w-4 h-4 text-amber-600"></i> Edit Site Clearance Profile`;
      document.getElementById('site-modal-submit-btn').textContent = 'Save Clearance Specs';

      document.getElementById('site-label').value = site.label || '';
      document.getElementById('site-measured-by').value = site.measuredBy || 'Lead Designer';
      document.getElementById('site-length').value = site.dimensions?.length || '';
      document.getElementById('site-length-unit').value = site.dimensions?.lengthUnit || 'inches';
      document.getElementById('site-width').value = site.dimensions?.width || '';
      document.getElementById('site-width-unit').value = site.dimensions?.widthUnit || 'inches';
      document.getElementById('site-height').value = site.dimensions?.height || '';
      document.getElementById('site-height-unit').value = site.dimensions?.heightUnit || 'inches';
      document.getElementById('site-depth').value = site.dimensions?.depth || '';
      document.getElementById('site-depth-unit').value = site.dimensions?.depthUnit || 'inches';
      document.getElementById('site-notes').value = site.notes || '';
      
      appState.tempSiteImages = site.images || [];
      const previewContainer = document.getElementById('site-images-preview');
      previewContainer.innerHTML = appState.tempSiteImages.map(img => `
        <div class="w-16 h-16 rounded-xl overflow-hidden border border-slate-200 relative group bg-white shadow-sm animate-fade-in">
          <img src="${img}" alt="Preview" class="w-full h-full object-cover cursor-pointer" onclick="openImageViewer('${img}', 'Clearance Detail Inspect')" />
          <button type="button" onclick="removeTempImage('${img}', 'site', this)" class="absolute inset-x-0 bottom-0 bg-rose-500/90 text-white py-1 text-[8.5px] text-center opacity-0 group-hover:opacity-100 transition duration-200 font-bold font-mono">Remove</button>
        </div>
      `).join('');

      openModal('addSiteMeasureModal');
      lucide.createIcons();
    };

    // Remove active image asset from view previews
    window.removeTempImage = (imgSrc, type, buttonEl) => {
      const targetArray = type === 'workpiece' ? 'tempItemImages' : 'tempSiteImages';
      appState[targetArray] = appState[targetArray].filter(x => x !== imgSrc);
      buttonEl.parentElement.remove();
    };

    // Close and reset active workpiece modal configurations
    window.closeWorkpieceModal = () => {
      appState.editingItemId = null;
      document.getElementById('add-workpiece-form').reset();
      document.getElementById('workpiece-images-preview').innerHTML = '';
      appState.tempItemImages = [];
      document.getElementById('workpiece-modal-heading').innerHTML = `<i data-lucide="layers" class="w-4 h-4 text-amber-600"></i> Configure Workpiece Dimensions`;
      document.getElementById('workpiece-modal-submit-btn').textContent = 'Deploy Workpiece Specs';
      closeModal('addWorkpieceModal');
      lucide.createIcons();
    };

    // Close and reset active site clearance modal configurations
    window.closeSiteModal = () => {
      appState.editingSiteId = null;
      document.getElementById('add-site-form').reset();
      document.getElementById('site-images-preview').innerHTML = '';
      appState.tempSiteImages = [];
      document.getElementById('site-modal-heading').innerHTML = `<i data-lucide="home" class="w-4 h-4 text-amber-600"></i> Log Site Clearance Profile`;
      document.getElementById('site-modal-submit-btn').textContent = 'Deploy Clearance Specs';
      closeModal('addSiteMeasureModal');
      lucide.createIcons();
    };

    // Specifications deploy controllers
    window.handleAddWorkpieceSubmit = async (e) => {
      e.preventDefault();
      const client = appState.activeClient;
      if (!client) return;

      const title = document.getElementById('workpiece-title').value;
      const measuredBy = document.getElementById('workpiece-measured-by').value;
      const length = document.getElementById('workpiece-length').value;
      const lengthUnit = document.getElementById('workpiece-length-unit').value;
      const width = document.getElementById('workpiece-width').value;
      const widthUnit = document.getElementById('workpiece-width-unit').value;
      const height = document.getElementById('workpiece-height').value;
      const heightUnit = document.getElementById('workpiece-height-unit').value;
      const depth = document.getElementById('workpiece-depth').value;
      const depthUnit = document.getElementById('workpiece-depth-unit').value;
      const notes = document.getElementById('workpiece-notes').value;

      let updatedItems;
      if (appState.editingItemId) {
        updatedItems = client.items.map(item => {
          if (item.id === appState.editingItemId) {
            return {
              ...item,
              title,
              measuredBy,
              dimensions: { length, lengthUnit, width, widthUnit, height, heightUnit, depth, depthUnit },
              notes,
              images: appState.tempItemImages || []
            };
          }
          return item;
        });
        triggerToast(`Workpiece spec "${title}" modified successfully!`);
      } else {
        const newItem = {
          id: 'item-' + Date.now(),
          title,
          measuredBy,
          dimensions: { length, lengthUnit, width, widthUnit, height, heightUnit, depth, depthUnit },
          woodType: 'Walnut',
          notes,
          images: appState.tempItemImages || []
        };
        updatedItems = [...(client.items || []), newItem];
        triggerToast(`Workpiece "${title}" added successfully!`);
      }

      await updateClientData(client.id, { items: updatedItems });
      closeWorkpieceModal();
    };

    window.handleAddSiteSubmit = async (e) => {
      e.preventDefault();
      const client = appState.activeClient;
      if (!client) return;

      const label = document.getElementById('site-label').value;
      const measuredBy = document.getElementById('site-measured-by').value;
      const length = document.getElementById('site-length').value;
      const lengthUnit = document.getElementById('site-length-unit').value;
      const width = document.getElementById('site-width').value;
      const widthUnit = document.getElementById('site-width-unit').value;
      const height = document.getElementById('site-height').value;
      const heightUnit = document.getElementById('site-height-unit').value;
      const depth = document.getElementById('site-depth').value;
      const depthUnit = document.getElementById('site-depth-unit').value;
      const notes = document.getElementById('site-notes').value;

      let updatedSites;
      if (appState.editingSiteId) {
        updatedSites = client.siteMeasures.map(site => {
          if (site.id === appState.editingSiteId) {
            return {
              ...site,
              label,
              measuredBy,
              dimensions: { length, lengthUnit, width, widthUnit, height, heightUnit, depth, depthUnit },
              notes,
              images: appState.tempSiteImages || []
            };
          }
          return site;
        });
        triggerToast(`Clearance log "${label}" modified successfully!`);
      } else {
        const newSite = {
          id: 'site-' + Date.now(),
          label,
          measuredBy,
          dimensions: { length, lengthUnit, width, widthUnit, height, heightUnit, depth, depthUnit },
          notes,
          images: appState.tempSiteImages || []
        };
        updatedSites = [...(client.siteMeasures || []), newSite];
        triggerToast(`Site clearance log "${label}" added successfully!`);
      }

      await updateClientData(client.id, { siteMeasures: updatedSites });
      closeSiteModal();
    };

    window.deleteItemSpec = (itemId) => {
      const client = appState.activeClient;
      if (!client) return;

      requestConfirm(
        "Discard Workpiece Specifications?",
        "Are you sure you want to delete this custom blueprint profile?",
        async () => {
          const updatedItems = client.items.filter(item => item.id !== itemId);
          await updateClientData(client.id, { items: updatedItems });
          triggerToast("Specifications discarded.");
        },
        "danger",
        "Delete Spec Profile"
      );
    };

    window.deleteSiteSpec = (siteId) => {
      const client = appState.activeClient;
      if (!client) return;

      requestConfirm(
        "Discard Site Measure Record?",
        "Verify you wish to purge this physical site assessment dimension record and related environment photos.",
        async () => {
          const updatedSites = client.siteMeasures.filter(site => site.id !== siteId);
          await updateClientData(client.id, { siteMeasures: updatedSites });
          triggerToast("Location assessment metrics purged.");
        },
        "danger",
        "Purge Site Log"
      );
    };

    // Responsive Fractional coordinates injector helper
    window.appendFractionValue = (fraction, targetId) => {
      const input = document.getElementById(targetId);
      if (!input) return;

      const currentVal = parseFloat(input.value || '0');
      const cleanWhole = Math.floor(currentVal);
      
      let fractionDec = 0;
      if (fraction === '1/16') fractionDec = 0.0625;
      else if (fraction === '1/8') fractionDec = 0.125;
      else if (fraction === '1/4') fractionDec = 0.25;
      else if (fraction === '3/8') fractionDec = 0.375;
      else if (fraction === '1/2') fractionDec = 0.5;
      else if (fraction === '5/8') fractionDec = 0.625;
      else if (fraction === '3/4') fractionDec = 0.75;
      else if (fraction === '7/8') fractionDec = 0.875;

      const finalVal = cleanWhole + fractionDec;
      input.value = finalVal.toString();
    };

    // Photo uploads media processors
    window.handleImageUpload = async (event, type) => {
      const files = Array.from(event.target.files);
      if (files.length === 0) return;

      const previewContainer = document.getElementById(type === 'workpiece' ? 'workpiece-images-preview' : 'site-images-preview');
      const targetArray = type === 'workpiece' ? 'tempItemImages' : 'tempSiteImages';
      
      if (!appState[targetArray]) appState[targetArray] = [];

      for (let file of files) {
        try {
          const base64 = await compressImage(file);
          appState[targetArray].push(base64);

          const imgDiv = document.createElement('div');
          imgDiv.className = 'w-16 h-16 rounded-xl overflow-hidden border border-slate-200 relative group bg-white shadow-sm animate-fade-in';
          imgDiv.innerHTML = `
            <img src="${base64}" alt="Preview" class="w-full h-full object-cover cursor-pointer" onclick="openImageViewer('${base64}', 'Uploaded dynamic thumbnail')" />
            <button type="button" class="absolute inset-x-0 bottom-0 bg-rose-500/90 text-white py-0.5 text-[8px] text-center opacity-0 group-hover:opacity-100 transition duration-200 font-bold font-mono">Remove</button>
          `;
          imgDiv.querySelector('button').onclick = () => {
            appState[targetArray] = appState[targetArray].filter(x => x !== base64);
            imgDiv.remove();
          };
          previewContainer.appendChild(imgDiv);
        } catch (err) {
          console.error(err);
          triggerToast("Error processing media asset", "error");
        }
      }
    };

    const compressImage = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const MAX_WIDTH = 550;
            const MAX_HEIGHT = 550;
            let width = img.width;
            let height = img.height;

            if (width > height) {
              if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
              }
            } else {
              if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
              }
            }
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);
            resolve(canvas.toDataURL('image/jpeg', 0.7));
          };
          img.onerror = reject;
        };
        reader.onerror = reject;
      });
    };

    window.openEditClientModal = () => {
      const client = appState.activeClient;
      if (!client) return;
      document.getElementById('edit-client-name').value = client.name || '';
      document.getElementById('edit-client-email').value = client.email || '';
      document.getElementById('edit-client-phone').value = client.phone || '';
      document.getElementById('edit-client-category').value = client.category || 'Furniture';
      document.getElementById('edit-client-notes').value = client.notes || '';
      openModal('editClientModal');
    };

    window.handleEditClientSubmit = async (e) => {
      e.preventDefault();
      const client = appState.activeClient;
      if (!client) return;

      const name = document.getElementById('edit-client-name').value;
      const email = document.getElementById('edit-client-email').value;
      const phone = document.getElementById('edit-client-phone').value;
      const category = document.getElementById('edit-client-category').value;
      const notes = document.getElementById('edit-client-notes').value;

      await updateClientData(client.id, { name, email, phone, category, notes });
      closeModal('editClientModal');
      triggerToast("Client spec folder modified successfully!");
    };

    window.updatePipelineStatus = async (status) => {
      const client = appState.activeClient;
      if (!client) return;

      const payload = {
        ...client,
        status,
        updatedAt: Date.now()
      };

      if (!appState.isOffline && db) {
        try {
          const docRef = doc(db, 'artifacts', appId, 'users', getActiveUserId(), 'clients', client.id);
          await updateDoc(docRef, { status, updatedAt: Date.now() });
          triggerToast(`Fabrication level set: ${status}`);
        } catch (err) {
          commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
        }
      } else {
        commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
        triggerToast(`Logged local progress state: ${status}`);
      }
    };

    // Formal buyer layout signoff approval loop
    window.approveClientPortalSpecs = () => {
      const client = appState.activeClient;
      if (!client) return;

      requestConfirm(
        "Approve Studio Workpiece Specifications?",
        "By confirming, you formally verify and sign off on all dimensions, spatial clearings, structural designs, and raw visual elements displayed above.",
        async () => {
          const approvalFeedback = {
            sender: 'System',
            text: '✅ Formal Signoff: This custom specification catalog was APPROVED for production by the client.',
            timestamp: Date.now()
          };

          const payload = {
            ...client,
            status: 'Approved',
            feedback: [...(client.feedback || []), approvalFeedback],
            updatedAt: Date.now()
          };

          const ownerId = appState.portalOwnerId || getActiveUserId();

          if (!appState.isOffline && db) {
            try {
              const docRef = doc(db, 'artifacts', appId, 'users', ownerId, 'clients', client.id);
              await updateDoc(docRef, {
                status: 'Approved',
                feedback: payload.feedback,
                updatedAt: Date.now()
              });
              triggerToast("Signed & approved! Design locks updated.", "success");
            } catch (err) {
              commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
            }
          } else {
            commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
            triggerToast("Local Signoff Logged: Project status locked.");
          }
          renderPortalUI();
        },
        "default",
        "Approve & Signoff"
      );
    };

    const parseUrlDeepLink = () => {
      const urlParams = new URLSearchParams(window.location.search);
      const targetClientId = urlParams.get('client');
      const ownerId = urlParams.get('owner');

      if (targetClientId) {
        if (ownerId && !appState.isOffline) {
          setupClientPortalSubscription(ownerId, targetClientId);
        } else {
          const client = appState.clients.find(c => c.id === targetClientId);
          if (client) {
            appState.activeClient = client;
            switchView('client-portal');
          }
        }
      }
    };

    window.switchView = (view) => {
      appState.currentView = view;
      if (view === 'designer') {
        document.getElementById('designer-view').classList.remove('hidden');
        document.getElementById('client-portal-view').classList.add('hidden');
        document.getElementById('back-to-atelier-btn').classList.add('hidden');
        renderClientLedger();
      } else {
        document.getElementById('designer-view').classList.add('hidden');
        document.getElementById('client-portal-view').classList.remove('hidden');
        document.getElementById('back-to-atelier-btn').classList.remove('hidden');
        renderPortalUI();
      }
    };

    const renderPortalUI = () => {
      const client = appState.activeClient;
      if (!client) return;

      document.getElementById('client-portal-name').textContent = client.name;
      document.getElementById('client-portal-studio-title').textContent = appState.studioName;
      document.getElementById('client-portal-brief-text').textContent = `"${client.notes || 'No project description added yet.'}"`;
      
      const badge = document.getElementById('client-portal-status-badge');
      badge.textContent = client.status || 'Design Phase';
      badge.className = `text-xs px-3 py-1 rounded-full font-bold uppercase tracking-wider border ${
        client.status === 'Approved' ? 'bg-emerald-50 text-emerald-700 border-emerald-200' :
        client.status === 'In Production' ? 'bg-amber-50 text-amber-705 border border-amber-200' :
        'bg-slate-50 text-slate-600 border-slate-200'
      }`;

      const actionContainer = document.getElementById('client-portal-signoff-action-container');
      if (client.status !== 'Approved') {
        actionContainer.innerHTML = `
          <button onclick="approveClientPortalSpecs()" class="bg-amber-500 hover:bg-amber-600 text-slate-955 font-black px-5 py-3 rounded-xl shadow-md shadow-amber-500/10 transition active:scale-95 flex items-center gap-1.5 text-xs uppercase tracking-wider">
            <i data-lucide="check-circle" class="w-4 h-4 stroke-[2.5]"></i> Signoff & Lock Specs
          </button>
        `;
      } else {
        actionContainer.innerHTML = `<span class="text-emerald-600 font-mono text-xs flex items-center gap-1 font-bold"><i data-lucide="check-circle" class="w-4 h-4"></i> Layout signoff recorded</span>`;
      }

      document.getElementById('portal-workpieces-count').textContent = client.items?.length || 0;
      document.getElementById('portal-site-count').textContent = (client.siteMeasures || []).length;

      renderPortalTabContent();
      lucide.createIcons();
    };

    window.setPortalTab = (tab) => {
      appState.portalTab = tab;
      
      document.getElementById('portal-tab-workpieces').className = tab === 'workpieces' 
        ? "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-600 transition"
        : "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-805 transition";

      document.getElementById('portal-tab-site').className = tab === 'site-measures' 
        ? "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-amber-500 text-amber-605 transition"
        : "pb-3 text-xs font-black uppercase tracking-widest flex items-center gap-2 border-b-2 border-transparent text-slate-500 hover:text-slate-805 transition";

      renderPortalTabContent();
    };

    const renderPortalTabContent = () => {
      const container = document.getElementById('portal-tab-content-container');
      const client = appState.activeClient;
      if (!client) return;

      const mapping = { inches: 'in', cm: 'cm', mm: 'mm', feet: 'ft' };

      if (appState.portalTab === 'workpieces') {
        if (!client.items || client.items.length === 0) {
          container.innerHTML = `<div class="bg-white border border-slate-205 rounded-3xl p-12 text-center text-slate-500 shadow-sm font-mono">Workspace designs are currently being compiled. Check back soon.</div>`;
          return;
        }

        container.innerHTML = `
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 animate-fade-in">
            ${client.items.map(item => {
              const dims = item.dimensions || {};
              const currentWood = item.woodType || 'Walnut';
              const sagData = calculateDeflection(item.dimensions, currentWood);

              const l = parseFloat(dims.length) || 0;
              const w = parseFloat(dims.width) || 0;
              const h = parseFloat(dims.height) || 0;
              const d = parseFloat(dims.depth) || 0;

              const lUnit = dims.lengthUnit || 'inches';
              const wUnit = dims.widthUnit || 'inches';
              const hUnit = dims.heightUnit || 'inches';
              const dUnit = dims.depthUnit || 'inches';

              const displayLUnit = mapping[lUnit] || lUnit;
              const displayWUnit = mapping[wUnit] || wUnit;
              const displayHUnit = mapping[hUnit] || hUnit;
              const displayDUnit = mapping[dUnit] || dUnit;

              return `
                <div class="bg-white border border-slate-200 rounded-3xl overflow-hidden hover:border-slate-300 transition duration-300 flex flex-col group shadow-sm">
                  <div class="p-3 bg-slate-50 border-b border-slate-100">
                    ${renderSVGBlueprint(item.dimensions, currentWood)}
                  </div>
                  ${item.images && item.images.length > 0 ? `
                    <div onclick="openImageViewer('${item.images[0]}', '${item.title}')" class="h-40 overflow-hidden relative border-b border-slate-200 bg-slate-50 cursor-zoom-in">
                      <img src="${item.images[0]}" alt="${item.title}" class="w-full h-full object-cover group-hover:scale-105 transition duration-500" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?auto=format&fit=crop&w=400&q=80'" />
                      <div class="absolute inset-0 bg-slate-900/10 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
                        <span class="bg-white border border-slate-200 p-2 rounded-xl text-slate-705 text-[10px] font-mono flex items-center gap-1.5 shadow-md">
                          <i data-lucide="zoom-in" class="w-3.5 h-3.5 text-amber-600"></i> Click to Zoom Spec Image
                        </span>
                      </div>
                    </div>
                  ` : ''}
                  <div class="p-5 flex-1 flex flex-col gap-4">
                    <div>
                      <h3 class="text-sm font-black text-slate-805">${item.title}</h3>
                      ${item.notes ? `<p class="text-xs text-slate-500 mt-2.5 italic leading-relaxed">"${item.notes}"</p>` : ''}
                    </div>

                    <!-- Material Physics Indicator for Client -->
                    ${sagData ? `
                    <div class="bg-slate-50 border border-slate-100 p-3 rounded-2xl text-[10.5px] font-mono space-y-1">
                      <div class="flex justify-between items-center text-[8px] text-slate-400 font-bold uppercase tracking-wider">
                        <span>Physical Properties (${currentWood})</span>
                        <span class="text-amber-700 font-bold">${sagData.rating}</span>
                      </div>
                      <div class="grid grid-cols-2 gap-1.5 pt-1.5 border-t border-slate-200/50">
                        <div class="flex justify-between">
                          <span class="text-slate-400">Weight:</span>
                          <span class="text-slate-750 font-bold">${sagData.weight} lbs</span>
                        </div>
                        <div class="flex justify-between">
                          <span class="text-slate-400">Max Sag:</span>
                          <span class="text-slate-750 font-bold">${sagData.deflection} in</span>
                        </div>
                      </div>
                    </div>
                    ` : ''}

                    <div class="flex justify-between items-center text-[10px] text-slate-500 font-mono bg-slate-50 p-2 rounded-lg border border-slate-100">
                      <span>Measured By:</span>
                      <span class="font-bold text-amber-850">${item.measuredBy || 'Lead Designer'}</span>
                    </div>

                    <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100 mt-auto font-mono">
                      <span class="text-[10px] uppercase font-bold text-slate-400 tracking-wider block mb-2">Registered Dimensions</span>
                      <div class="grid grid-cols-4 gap-2 text-center">
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Length</span>
                          <span class="text-slate-700 font-extrabold text-xs">${l || 'TBD'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayLUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Width</span>
                          <span class="text-slate-700 font-extrabold text-xs">${w || 'TBD'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayWUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Height</span>
                          <span class="text-slate-700 font-extrabold text-xs">${h || 'TBD'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayHUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Thickness</span>
                          <span class="text-slate-700 font-extrabold text-xs">${d || 'TBD'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayDUnit}</span></span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              `;
            }).join('')}
          </div>
        `;
      } else {
        if (!client.siteMeasures || client.siteMeasures.length === 0) {
          container.innerHTML = `<div class="bg-white border border-slate-205 rounded-3xl p-12 text-center text-slate-500 shadow-sm font-mono">No environment clearance measurements are registered to your file.</div>`;
          return;
        }

        container.innerHTML = `
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 animate-fade-in">
            ${client.siteMeasures.map(site => {
              const dims = site.dimensions || {};
              const l = parseFloat(dims.length) || 0;
              const w = parseFloat(dims.width) || 0;
              const h = parseFloat(dims.height) || 0;
              const d = parseFloat(dims.depth) || 0;

              const lUnit = dims.lengthUnit || 'inches';
              const wUnit = dims.widthUnit || 'inches';
              const hUnit = dims.heightUnit || 'inches';
              const dUnit = dims.depthUnit || 'inches';

              const displayLUnit = mapping[lUnit] || lUnit;
              const displayWUnit = mapping[wUnit] || wUnit;
              const displayHUnit = mapping[hUnit] || hUnit;
              const displayDUnit = mapping[dUnit] || dUnit;

              return `
                <div class="bg-white border border-slate-200 rounded-3xl overflow-hidden hover:border-slate-300 transition duration-305 flex flex-col group shadow-sm">
                  <div class="h-56 bg-slate-50 relative overflow-hidden flex items-center justify-center">
                    ${site.images && site.images.length > 0 ? `
                      <img src="${site.images[0]}" alt="${site.label}" onclick="openImageViewer('${site.images[0]}', '${site.label}')" class="w-full h-full object-cover cursor-zoom-in" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1504307651254-35680f356dfd?auto=format&fit=crop&w=400&q=80'" />
                      <div onclick="openImageViewer('${site.images[0]}', '${site.label}')" class="absolute inset-0 bg-slate-900/10 opacity-0 group-hover:opacity-100 transition flex items-center justify-center cursor-zoom-in">
                        <span class="bg-white border border-slate-200 p-2 rounded-xl text-slate-200 text-[10px] font-mono flex items-center gap-1.5 shadow-md">
                          <i data-lucide="zoom-in" class="w-3.5 h-3.5 text-amber-500"></i> Click to Zoom Clearance Image
                        </span>
                      </div>
                    ` : `
                      <div class="text-center text-slate-400 flex flex-col items-center gap-1.5">
                        <i data-lucide="camera" class="w-8 h-8 stroke-[1.2] mb-1"></i>
                        <span class="text-xs uppercase font-black font-mono font-bold">No photo uploaded</span>
                      </div>
                    `}
                  </div>
                  <div class="p-5 flex-1 flex flex-col gap-4">
                    <div>
                      <div class="flex items-center gap-2 text-slate-805 mb-1">
                        <i data-lucide="map-pin" class="w-4 h-4 text-amber-600"></i>
                        <h3 class="text-sm font-black">${site.label}</h3>
                      </div>
                      ${site.notes ? `<p class="text-xs text-slate-500 mt-2.5 italic leading-relaxed">"${site.notes}"</p>` : ''}
                    </div>

                    <div class="flex justify-between items-center text-[10px] text-slate-500 font-mono bg-slate-50 p-2 rounded-lg border border-slate-100">
                      <span>Measured By:</span>
                      <span class="font-bold text-amber-805">${site.measuredBy || 'Lead Designer'}</span>
                    </div>

                    <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100 mt-auto font-mono">
                      <span class="text-[10px] uppercase font-bold text-slate-450 tracking-wider block mb-2">Location Clearances Registered</span>
                      <div class="grid grid-cols-4 gap-2 text-center">
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Length</span>
                          <span class="text-slate-700 font-extrabold text-xs">${l || '-'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayLUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Width</span>
                          <span class="text-slate-700 font-extrabold text-xs">${w || '-'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayWUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Height</span>
                          <span class="text-slate-700 font-extrabold text-xs">${h || '-'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayHUnit}</span></span>
                        </div>
                        <div class="bg-white py-2 rounded-xl border border-slate-150">
                          <span class="text-[8px] text-slate-400 block uppercase tracking-wider mb-0.5">Gap</span>
                          <span class="text-slate-700 font-extrabold text-xs">${d || '-'} <span class="text-[9px] text-slate-400 font-semibold lowercase">${displayDUnit}</span></span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              `;
            }).join('')}
          </div>
        `;
      }

      const activityStream = document.getElementById('portal-activity-stream-container');
      if (!client.feedback || client.feedback.length === 0) {
        activityStream.innerHTML = `<p class="text-xs text-slate-400 italic mt-4 text-center font-mono">No revision history compiled.</p>`;
      } else {
        activityStream.innerHTML = client.feedback.map(f => `
          <div class="bg-slate-50 p-3 rounded-2xl border border-slate-100 text-[11px] leading-relaxed">
            <div class="flex items-center justify-between mb-1.5">
              <span class="font-extrabold text-[8px] uppercase tracking-wider ${
                f.sender === 'Client' ? 'text-amber-705' : f.sender === 'System' ? 'text-emerald-600 font-extrabold' : 'text-slate-500'
              } font-mono">${f.sender}</span>
              <span class="text-[9px] text-slate-400 font-mono">${new Date(f.timestamp).toLocaleDateString()}</span>
            </div>
            <p class="text-slate-655">${f.text}</p>
          </div>
        `).join('');
      }
      lucide.createIcons();
    };

    window.submitPortalComment = async (e) => {
      e.preventDefault();
      const textarea = document.getElementById('portal-comment-textarea');
      const val = textarea.value;
      if (!val.trim()) return;

      const client = appState.activeClient;
      if (!client) return;

      const updatedFeedback = [...(client.feedback || []), {
        sender: 'Client',
        text: val,
        timestamp: Date.now()
      }];

      const payload = {
        ...client,
        feedback: updatedFeedback,
        updatedAt: Date.now()
      };

      const ownerId = appState.portalOwnerId || getActiveUserId();

      if (!appState.isOffline && db) {
        try {
          const docRef = doc(db, 'artifacts', appId, 'users', ownerId, 'clients', client.id);
          await updateDoc(docRef, {
            feedback: updatedFeedback,
            updatedAt: Date.now()
          });
          triggerToast("Revision specifications updated to workshop logs!", "success");
        } catch (err) {
          commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
        }
      } else {
        commitLocalMock(appState.clients.map(c => c.id === client.id ? payload : c));
        triggerToast("Progress notes updated inside sandbox files.");
      }

      textarea.value = '';
      renderPortalUI();
    };

    // Full layout printable sheet compilation
    window.openPrintPreview = () => {
      const client = appState.activeClient;
      if (!client) return;

      const previewContainer = document.getElementById('printable-preview-content');
      const physicalContainer = document.getElementById('printable-workshop-sheet');
      const mapping = { inches: 'in', cm: 'cm', mm: 'mm', feet: 'ft' };
      
      const workpiecesHTML = (!client.items || client.items.length === 0) 
        ? `<p class="text-xs text-zinc-550 italic font-mono">No pieces cataloged for fabrication.</p>`
        : client.items.map((item, idx) => {
            const dims = item.dimensions || {};
            const displayLUnit = mapping[dims.lengthUnit] || dims.lengthUnit || 'in';
            const displayWUnit = mapping[dims.widthUnit] || dims.widthUnit || 'in';
            const displayHUnit = mapping[dims.heightUnit] || dims.heightUnit || 'in';
            const displayDUnit = mapping[dims.depthUnit] || dims.depthUnit || 'in';
            return `
              <div class="border border-zinc-300 p-4 rounded-xl space-y-3 bg-zinc-50">
                <div class="flex justify-between items-center border-b border-zinc-200 pb-1.5">
                  <h4 class="font-black text-sm text-zinc-900">${idx + 1}. ${item.title} (${item.woodType || 'Walnut'})</h4>
                  <span class="text-xs text-zinc-500 font-mono">Measured by: ${item.measuredBy || 'Lead Designer'}</span>
                </div>
                <div class="grid grid-cols-4 gap-2 text-center font-mono text-xs text-zinc-900">
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Length</span>
                    <span class="text-sm font-extrabold">${dims.length || 'TBD'} ${displayLUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Width</span>
                    <span class="text-sm font-extrabold">${dims.width || 'TBD'} ${displayWUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Height</span>
                    <span class="text-sm font-extrabold">${dims.height || 'TBD'} ${displayHUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Thickness</span>
                    <span class="text-sm font-extrabold">${dims.depth || 'TBD'} ${displayDUnit}</span>
                  </div>
                </div>
                ${item.notes ? `
                  <div class="text-xs pt-1">
                    <strong class="uppercase font-bold text-[9px] text-zinc-600 block mb-1 font-mono">Execution / Cutting Notes:</strong>
                    <p class="text-zinc-855 italic leading-relaxed">"${item.notes}"</p>
                  </div>
                ` : ''}
              </div>
            `;
          }).join('');

      const siteHTML = (!client.siteMeasures || client.siteMeasures.length === 0)
        ? `<p class="text-xs text-zinc-550 italic font-mono">No site clearance files registered.</p>`
        : client.siteMeasures.map((site, idx) => {
            const dims = site.dimensions || {};
            const displayLUnit = mapping[dims.lengthUnit] || dims.lengthUnit || 'in';
            const displayWUnit = mapping[dims.widthUnit] || dims.widthUnit || 'in';
            const displayHUnit = mapping[dims.heightUnit] || dims.heightUnit || 'in';
            const displayDUnit = mapping[dims.depthUnit] || dims.depthUnit || 'in';
            return `
              <div class="border border-zinc-300 p-4 rounded-xl space-y-3 bg-zinc-50">
                <div class="flex justify-between items-center border-b border-zinc-200 pb-1.5">
                  <h4 class="font-black text-sm text-zinc-900">${idx + 1}. Location Target: ${site.label}</h4>
                  <span class="text-xs text-zinc-500 font-mono">Verified by: ${site.measuredBy || 'Lead Designer'}</span>
                </div>
                <div class="grid grid-cols-4 gap-2 text-center font-mono text-xs text-zinc-900">
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Length</span>
                    <span class="text-sm font-extrabold">${dims.length || 'TBD'} ${displayLUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Width</span>
                    <span class="text-sm font-extrabold">${dims.width || 'TBD'} ${displayWUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Height</span>
                    <span class="text-sm font-extrabold">${dims.height || 'TBD'} ${displayHUnit}</span>
                  </div>
                  <div class="border border-zinc-300 p-2 rounded bg-white">
                    <span class="text-[9px] text-zinc-500 block uppercase font-bold leading-none mb-1">Offset Buffer</span>
                    <span class="text-sm font-extrabold">${dims.depth || 'TBD'} ${displayDUnit}</span>
                  </div>
                </div>
                ${site.notes ? `
                  <div class="text-xs pt-1">
                    <strong class="uppercase font-bold text-[9px] text-zinc-600 block mb-1 font-mono">Site Obstacles & Placement notes:</strong>
                    <p class="text-zinc-800 italic leading-relaxed font-sans">"${site.notes}"</p>
                  </div>
                ` : ''}
              </div>
            `;
          }).join('');

      const sheetContent = `
        <div class="border-b-4 border-black pb-4 flex justify-between items-end">
          <div>
            <h1 class="text-3xl font-black uppercase tracking-tight text-zinc-900">${appState.studioName}</h1>
            <p class="text-xs font-bold uppercase tracking-wider text-zinc-600 mt-1">Production Specification Blueprint Sheet</p>
          </div>
          <div class="text-right font-mono text-xs text-zinc-500 space-y-0.5">
            <p>Client: <span class="font-bold text-black">${client.name}</span></p>
            <p>Date Generated: ${new Date().toLocaleDateString()}</p>
            <p>Project Code: CS-${client.id?.substring(0, 5).toUpperCase()}</p>
          </div>
        </div>

        <div class="space-y-2 pt-2">
          <h3 class="text-xs font-extrabold uppercase tracking-wider border-b-2 border-black pb-1 font-mono text-zinc-700">Project Concept</h3>
          <p class="text-sm text-zinc-850 italic leading-relaxed">"${client.notes || 'No project description loaded.'}"</p>
        </div>

        <div class="space-y-4 pt-2">
          <h3 class="text-xs font-extrabold uppercase tracking-wider border-b-2 border-black pb-1 font-mono text-zinc-700">Workpieces Specifications Sheet</h3>
          <div class="space-y-4">${workpiecesHTML}</div>
        </div>

        <div class="space-y-4 pt-2">
          <h3 class="text-xs font-extrabold uppercase tracking-wider border-b-2 border-black pb-1 font-mono text-zinc-700">Site Clearance Parameters</h3>
          <div class="space-y-4">${siteHTML}</div>
        </div>

        <div class="pt-12 border-t border-dashed border-zinc-400 grid grid-cols-2 gap-8 text-xs font-mono">
          <div>
            <span class="block border-b-2 border-black pb-8"></span>
            <span class="block text-center mt-2 uppercase font-bold text-zinc-700">Studio Representative Signoff</span>
          </div>
          <div>
            <span class="block border-b-2 border-black pb-8"></span>
            <span class="block text-center mt-2 uppercase font-bold text-zinc-700">Buyer / Client Verification Signoff</span>
          </div>
        </div>
      `;

      previewContainer.innerHTML = sheetContent;
      physicalContainer.innerHTML = sheetContent;
      
      openModal('workshopPrintOverlay');
    };

    window.addEventListener('load', () => {
      initializeFirebase();
      renderCategoryFilters();
      runSimulatorCalculation();
      lucide.createIcons();
    });
  </script>
</body>
</html>