// =========================================================================

// XAVIER VILLARROEL - 5 DISTINCT UI DESIGN PARADIGMS (v1 to v5)

// Dynamic URL Routing: /v1, /v2, /v3, /v4, /v5 (or ?v=1..5)

// Admin Career Intelligence Mode (/admin) supported across all versions

// =========================================================================


const { useState, useEffect, useMemo, useRef } = React;

// --- Helper Utilities ---
function parseMatchValue(matchStr) {
  if (!matchStr) return 0;
  const num = parseInt(matchStr.replace(/[^0-9]/g, ''), 10);
  return isNaN(num) ? 0 : num;
}

function parseSalaryValue(salaryStr) {
  if (!salaryStr || salaryStr.toLowerCase().includes('unknown')) return 0;
  const matches = salaryStr.match(/\$([0-9,]+)/g);
  if (matches && matches.length > 0) {
    const nums = matches.map(m => parseInt(m.replace(/[^0-9]/g, ''), 10));
    return Math.max(...nums);
  }
  return 0;
}

// --- Icons (Clean Minimal Outline SVG matching Figma Community Design) ---
const Icons = {
  User: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
    </svg>
  ),
  Briefcase: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
    </svg>
  ),
  Rocket: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
    </svg>
  ),
  Cpu: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 3v2m6-2v2M9 19v2m6-2v2M3 9h2m-2 6h2m14-6h2m-2 6h2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
    </svg>
  ),
  Search: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
    </svg>
  ),
  Chart: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
    </svg>
  ),
  Document: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
    </svg>
  ),
  CloudDownload: () => (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
    </svg>
  ),
  ExternalLink: () => (
    <svg className="w-3.5 h-3.5 inline ml-1 opacity-70 group-hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
    </svg>
  ),
  Check: () => (
    <svg className="w-4 h-4 text-cyan-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
    </svg>
  ),
  ArrowUp: () => (
    <svg className="w-3 h-3 inline ml-1 text-cyan-400" fill="currentColor" viewBox="0 0 20 20">
      <path fillRule="evenodd" d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z" clipRule="evenodd" />
    </svg>
  ),
  ArrowDown: () => (
    <svg className="w-3 h-3 inline ml-1 text-cyan-400" fill="currentColor" viewBox="0 0 20 20">
      <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
    </svg>
  ),
  Reset: () => (
    <svg className="w-3.5 h-3.5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
    </svg>
  ),
  Filter: () => (
    <svg className="w-3.5 h-3.5 inline-block mr-1 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
    </svg>
  ),
  ChevronLeft: () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
    </svg>
  ),
  ChevronRight: () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
    </svg>
  ),
  Mail: () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
    </svg>
  )
};

// =========================================================================
// REUSABLE PORTRAIT & IDENTITY CARD (Dual-Mode: Public vs Admin)
// =========================================================================

function PortraitCard({ skillsData, onExploreJobs, isAdmin, isMobile = false }) {
  return (
    <section className="figma-card w-full flex flex-col justify-between overflow-hidden shadow-card">
      {/* Studio Lighting Portrait Photo */}
      <div className={'relative w-full overflow-hidden bg-slate-900 ' + (isMobile ? 'h-72 sm:h-80' : 'h-[350px] xl:h-[390px] 2xl:h-[430px] shrink-0')}>
        <img
          src="portrait.jpg?v=20260912_studio_perfect"
          alt="Xavier Villarroel - Systems Architect"
          className="w-full h-full object-cover object-top transition duration-500 hover:scale-105"
        />
        <div className="absolute inset-x-0 bottom-0 h-28 bg-gradient-to-t from-[#151821] via-[#151821]/80 to-transparent"></div>
      </div>

      {/* Candidate Identity Details */}
      <div className="p-5 sm:p-6 flex-1 flex flex-col justify-between text-center space-y-3">
        <div>
          <h2 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight font-heading">
            {skillsData?.personalInfo?.fullName || 'Xavier Villarroel'}
          </h2>
          <p className="text-xs sm:text-sm font-medium text-cyan-400 tracking-wide mt-1">
            Distributed Systems Architect & AI Automation Specialist
          </p>
        </div>

        {/* Quick Stats Pills */}
        <div className="flex flex-wrap items-center justify-center gap-1.5 text-[11px] font-mono">
          <span className="px-2.5 py-0.5 rounded-full bg-cyan-950/60 text-cyan-300 border border-cyan-800">
            100% REMOTE LATAM
          </span>
          <span className="px-2.5 py-0.5 rounded-full bg-slate-800/80 text-slate-300 border border-slate-700">
            8+ YEARS EXP
          </span>
          <span className="px-2.5 py-0.5 rounded-full bg-cyan-950/60 text-cyan-300 border border-cyan-800">
            AWS SOLUTIONS ARCHITECT
          </span>
        </div>

        {/* Contact Details */}
        <div className="text-xs text-slate-400 space-y-1 font-mono pt-1">
          <div>📍 Santiago, Chile (AMER / Global Timezones)</div>
          <div>✉️ xavier.villarroel@outlook.com</div>
          <div>🌐 English C2 (Bilingual) • Spanish Native</div>
        </div>

        {/* 4 Quick-Stats Badges: Modern Frontier AI Architecture Focus */}
        <div className="w-full grid grid-cols-2 gap-2 pt-1 text-left font-mono">
          <div className="p-2.5 rounded-lg bg-slate-900/70 border border-white/[0.06] hover:border-cyan-500/30 transition">
            <div className="text-cyan-400 font-bold text-xs sm:text-sm">Agentic AI</div>
            <div className="text-[10px] text-slate-400 leading-tight">MCP & Multi-Agent Flows</div>
          </div>
          <div className="p-2.5 rounded-lg bg-slate-900/70 border border-white/[0.06] hover:border-cyan-500/30 transition">
            <div className="text-cyan-400 font-bold text-xs sm:text-sm">Context Eng</div>
            <div className="text-[10px] text-slate-400 leading-tight">BrainLifts & Prompt Systems</div>
          </div>
          <div className="p-2.5 rounded-lg bg-slate-900/70 border border-white/[0.06] hover:border-cyan-500/30 transition">
            <div className="text-cyan-400 font-bold text-xs sm:text-sm">RAG & Vectors</div>
            <div className="text-[10px] text-slate-400 leading-tight">Pinecone, FAISS & Search</div>
          </div>
          <div className="p-2.5 rounded-lg bg-slate-900/70 border border-white/[0.06] hover:border-cyan-500/30 transition">
            <div className="text-cyan-400 font-bold text-xs sm:text-sm">Voice AI & IVR</div>
            <div className="text-[10px] text-slate-400 leading-tight">Voiceflow & Auto-Triage</div>
          </div>
        </div>

        {/* Admin Switch Indicator or Public Hire Button */}
        {isAdmin ? (
          <div className="space-y-2 pt-1">
            <div className="flex items-center justify-between w-full px-2.5 py-1 rounded-lg bg-cyan-950/40 border border-cyan-800/40 text-[10px] font-mono text-cyan-300">
              <span className="flex items-center gap-1.5">
                <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse"></span>
                ADMIN VIEW
              </span>
              <a href="/" className="text-slate-400 hover:text-white underline">
                Public View
              </a>
            </div>
            <button
              onClick={onExploreJobs}
              className="w-full py-2.5 rounded-xl bg-gradient-to-r from-cyan-500 to-sky-600 hover:from-cyan-400 hover:to-sky-500 text-black font-bold font-heading text-xs uppercase tracking-wider shadow-lg shadow-cyan-500/20 transition duration-200"
            >
              Explore 184 Matched Jobs →
            </button>
          </div>
        ) : (
          <div className="pt-1">
            <a
              href="mailto:xavier.villarroel@outlook.com?subject=Senior%20Engineering%20Opportunity%20-%20Xavier%20Villarroel"
              className="w-full py-2.5 rounded-xl bg-gradient-to-r from-cyan-500 to-sky-600 hover:from-cyan-400 hover:to-sky-500 text-black font-bold font-heading text-xs uppercase tracking-wider shadow-lg shadow-cyan-500/20 transition duration-200 flex items-center justify-center gap-2"
            >
              <Icons.Mail />
              <span>Contact Xavier / Hire →</span>
            </a>
          </div>
        )}
      </div>
    </section>
  );
}

// =========================================================================
// TAB 1: EXECUTIVE OVERVIEW VIEW (Responsive Widescreen)
// =========================================================================

function OverviewView({ data, onSelectMetric }) {
  if (!data) return null;
  const { executiveSummary, metricsAndImpact, verifiedEndorsements } = data;

  return (
    <div className="space-y-8 animate-fade-in">
      
      {/* Executive Pitch Banner */}
      <div className="p-6 sm:p-7 rounded-xl bg-slate-900/60 border border-white/[0.08] relative overflow-hidden">
        <div className="absolute top-0 right-0 w-80 h-80 bg-cyan-500/5 rounded-full blur-3xl pointer-events-none"></div>
        <div className="flex items-center space-x-2 text-cyan-400 text-xs font-mono font-semibold uppercase tracking-wider mb-2">
          <span>// Executive Summary & Value Proposition</span>
        </div>
        <h2 className="text-xl sm:text-2xl font-bold text-white font-heading tracking-tight mb-3">
          Senior Systems Architect & Distributed AI Specialist
        </h2>
        <p className="text-sm sm:text-base text-slate-300 leading-relaxed font-normal">
          {executiveSummary?.pitch}
        </p>
      </div>

      {/* 4 Core Architectural Pillars (Fluid across screen) */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="figma-section-heading">
            <span className="text-cyan-400 font-mono text-sm">//</span> Core Architectural Pillars
          </h3>
          <span className="text-xs font-mono text-slate-500">4 Proven Engineering Domains</span>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-4 gap-4">
          {executiveSummary?.corePillars?.map((pillar, idx) => (
            <div key={idx} className="p-5 rounded-xl bg-[#151821] border border-white/[0.07] hover:border-cyan-500/40 transition duration-300 flex flex-col justify-between group">
              <div>
                <div className="flex items-center space-x-2.5 mb-2.5">
                  <div className="w-2 h-2 rounded-full bg-cyan-400 shadow-[0_0_8px_#38bdf8]"></div>
                  <h4 className="text-sm sm:text-base font-bold text-white font-heading group-hover:text-cyan-300 transition">
                    {pillar.title}
                  </h4>
                </div>
                <p className="text-xs sm:text-sm text-slate-400 leading-relaxed">
                  {pillar.description}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 4 Quantified Impact Cards (Fluid 4-Col Widescreen) */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="figma-section-heading">
            <span className="text-cyan-400 font-mono text-sm">//</span> Quantified Production Impact
          </h3>
          <span className="text-xs font-mono text-cyan-400 animate-pulse">Click any card to inspect specs →</span>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 2xl:grid-cols-4 gap-4">
          {metricsAndImpact?.map((m) => (
            <div
              key={m.id}
              onClick={() => onSelectMetric(m)}
              className="p-5 rounded-xl bg-[#151821] border border-white/[0.07] hover:border-cyan-500/50 hover:bg-slate-900/80 transition duration-300 cursor-pointer group relative overflow-hidden flex flex-col justify-between"
            >
              <div>
                <div className="flex items-start justify-between">
                  <span className="text-3xl sm:text-4xl font-black text-cyan-400 font-mono tracking-tight group-hover:scale-105 transition transform origin-left">
                    {m.value}
                  </span>
                  <span className="px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                    VERIFIED
                  </span>
                </div>
                <h4 className="text-base font-bold text-white font-heading mt-2 mb-1">
                  {m.label}
                </h4>
                <p className="text-xs text-slate-400 leading-relaxed mb-3">
                  {m.detail}
                </p>
              </div>
              <div className="pt-3 border-t border-white/[0.06] flex items-center justify-between text-[11px] font-mono text-cyan-400/80 group-hover:text-cyan-300">
                <span>Inspect technical breakdown</span>
                <span>→</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Bare-Metal Diagnostic Lab Specs Breakdown (Widescreen 6-Col Grid) */}
      <div className="p-6 rounded-xl bg-slate-900/60 border border-white/[0.08]">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-3">
          <h4 className="text-sm font-bold text-white uppercase tracking-wider font-mono flex items-center gap-2">
            <span className="text-cyan-400">⚡</span> Private Bare-Metal Diagnostic Rig & Multi-OS Lab
          </h4>
          <span className="text-[11px] font-mono text-slate-400">192GB+ RAM • 64TB NAS • ZERO CLOUD DEPENDENCY</span>
        </div>
        <p className="text-xs sm:text-sm text-slate-300 leading-relaxed mb-4">
          Dedicated on-premise multi-node laboratory built to replicate high-throughput client topologies, kernel crash dumps, and multi-node distributed clusters without external cloud dependencies.
        </p>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-6 gap-3 text-xs font-mono">
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">1x Linux Ubuntu Rig</div>
            <div className="text-slate-400 text-[11px] mt-0.5">Headless kernel debugging, PCAP packets, Docker clusters.</div>
          </div>
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">1x Extreme Win11 Rig</div>
            <div className="text-slate-400 text-[11px] mt-0.5">Core i9 14th Gen, 128GB RAM. Local distributed cluster & VM swarm.</div>
          </div>
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">1x Mac Studio M4 Pro</div>
            <div className="text-slate-400 text-[11px] mt-0.5">Apple Silicon ARM64 native builds & Metal GPU validation.</div>
          </div>
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">1x Alienware Laptop</div>
            <div className="text-slate-400 text-[11px] mt-0.5">Core i9 13th Gen, 64GB RAM. Mobile Sev-1 emergency triage station.</div>
          </div>
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">1x Enterprise NAS 64TB</div>
            <div className="text-slate-400 text-[11px] mt-0.5">Multi-terabyte crash dumps, PCAP traces, offline mirrors.</div>
          </div>
          <div className="p-3.5 rounded-lg bg-black/40 border border-white/[0.06]">
            <div className="text-cyan-400 font-bold">Client Edge Telemetry</div>
            <div className="text-slate-400 text-[11px] mt-0.5">3x Microsoft Surfaces, Raspberry Pi ARM, iPad testing nodes.</div>
          </div>
        </div>
      </div>

      {/* Verified Peer & Leadership Endorsements */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="figma-section-heading">
            <span className="text-cyan-400 font-mono text-sm">//</span> Verified Leadership Endorsements
          </h3>
          <span className="text-xs font-mono text-slate-500">Peer & Management References</span>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {verifiedEndorsements?.map((end, idx) => (
            <div key={idx} className="p-5 rounded-xl bg-[#151821] border border-white/[0.07] flex flex-col justify-between space-y-3">
              <p className="text-xs sm:text-sm text-slate-300 italic leading-relaxed">
                "{end.quote}"
              </p>
              <div className="pt-3 border-t border-white/[0.06] flex items-center justify-between">
                <div>
                  <div className="text-xs font-bold text-white font-heading">{end.author}</div>
                  <div className="text-[11px] text-cyan-400">{end.role}</div>
                </div>
                <span className="text-xs text-slate-500 font-mono">Verified Reference</span>
              </div>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

// =========================================================================
// TAB 2: WORK EXPERIENCE & FORMAL EDUCATION
// =========================================================================

function ExperienceView({ data }) {
  if (!data) return null;
  const { workExperience, educationAndCertifications } = data;

  return (
    <div className="space-y-8 animate-fade-in">
      
      {/* Work Experience Timeline */}
      <div>
        <div className="flex items-center justify-between mb-5">
          <h3 className="figma-section-heading">
            <span className="text-cyan-400 font-mono text-sm">//</span> Detailed Career History (March 2018 – Present)
          </h3>
          <span className="text-xs font-mono text-cyan-400">8+ Continuous Remote Years</span>
        </div>

        <div className="space-y-6">
          {workExperience?.map((role, idx) => (
            <div key={idx} className="p-6 rounded-xl bg-[#151821] border border-white/[0.07] hover:border-cyan-500/40 transition duration-300">
              
              {/* Role Header */}
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4 pb-3 border-b border-white/[0.06]">
                <div>
                  <h4 className="text-lg font-bold text-white font-heading">
                    {role.role || role.title}
                  </h4>
                  <div className="text-xs font-medium text-cyan-400 font-mono mt-0.5">
                    {role.company}
                  </div>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <span className="px-2.5 py-0.5 rounded text-[11px] font-mono font-semibold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                    {role.period}
                  </span>
                  <span className="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-slate-300 border border-white/[0.08]">
                    {role.location}
                  </span>
                </div>
              </div>

              {/* Bullet Points / Highlights */}
              <ul className="space-y-2.5 text-xs sm:text-sm text-slate-300 leading-relaxed mb-4">
                {role.highlights?.map((h, i) => (
                  <li key={i} className="flex items-start space-x-2.5">
                    <span className="text-cyan-400 mt-1">▹</span>
                    <span>{h}</span>
                  </li>
                ))}
              </ul>

              {/* Technologies Tag Cloud */}
              <div className="flex flex-wrap items-center gap-1.5 pt-2">
                {role.techStack?.map((t, i) => (
                  <span key={i} className="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-900/80 text-slate-300 border border-white/[0.06]">
                    {t}
                  </span>
                ))}
              </div>

            </div>
          ))}
        </div>
      </div>

      {/* Formal Education & Certifications */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 pt-4">
        
        {/* Education */}
        <div className="p-6 rounded-xl bg-[#151821] border border-white/[0.07]">
          <h4 className="text-xs font-bold text-white uppercase tracking-wider mb-4 font-mono flex items-center gap-2">
            <span className="text-cyan-400">🎓</span> Formal Education
          </h4>
          <div className="space-y-4">
            {educationAndCertifications?.education?.map((edu, idx) => (
              <div key={idx} className="border-l-2 border-cyan-400 pl-3.5 space-y-1">
                <div className="text-sm font-bold text-white font-heading">{edu.degree}</div>
                <div className="text-xs text-cyan-400 font-medium">{edu.institution} • {edu.period}</div>
                <div className="text-xs text-slate-300 leading-relaxed pt-0.5">{edu.focus}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Certifications */}
        <div className="p-6 rounded-xl bg-[#151821] border border-white/[0.07]">
          <h4 className="text-xs font-bold text-white uppercase tracking-wider mb-4 font-mono flex items-center gap-2">
            <span className="text-cyan-400">📜</span> Certifications & Credentials
          </h4>
          <div className="space-y-3">
            {educationAndCertifications?.certifications?.map((cert, idx) => (
              <div key={idx} className="p-3.5 rounded-lg bg-slate-900/70 border border-white/[0.06] flex items-center justify-between">
                <div>
                  <div className="text-xs sm:text-sm font-bold text-white font-heading">{cert.name}</div>
                  <div className="text-[11px] text-slate-400 mt-0.5">{cert.issuer}</div>
                </div>
                <span className="px-2 py-0.5 rounded text-[10px] font-semibold font-mono uppercase bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                  {cert.status}
                </span>
              </div>
            ))}
          </div>
        </div>

      </div>

    </div>
  );
}

// =========================================================================
// TAB 3: FLAGSHIP PRODUCTION SYSTEMS
// =========================================================================

function ProjectsView({ data }) {
  if (!data) return null;
  const { flagshipProjects } = data;

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex items-center justify-between mb-2">
        <h3 className="figma-section-heading">
          <span className="text-cyan-400 font-mono text-sm">//</span> Flagship Production Systems
        </h3>
        <span className="text-xs font-mono text-slate-500">Autonomous AI & Tooling Fleet</span>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
        {flagshipProjects?.map((proj) => (
          <div key={proj.id} className="p-6 rounded-xl bg-[#151821] border border-white/[0.07] hover:border-cyan-500/40 transition duration-300 flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="px-2.5 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                  {proj.category}
                </span>
                <span className="text-[11px] font-mono text-slate-500">Production Ready</span>
              </div>
              
              <h4 className="text-base sm:text-lg font-bold text-white font-heading mt-2 mb-2">
                {proj.name}
              </h4>
              
              <p className="text-xs sm:text-sm text-slate-300 leading-relaxed mb-4">
                {proj.description}
              </p>

              {/* Capabilities checklist */}
              <div className="space-y-2 mb-5">
                {proj.keyCapabilities?.map((cap, i) => (
                  <div key={i} className="flex items-start space-x-2 text-xs text-slate-300">
                    <Icons.Check />
                    <span>{cap}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Technologies */}
            <div className="pt-3 border-t border-white/[0.06] flex flex-wrap gap-1.5">
              {proj.technologies?.map((tech, i) => (
                <span key={i} className="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-900/80 text-cyan-300 border border-white/[0.06]">
                  {tech}
                </span>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// =========================================================================
// TAB 4: TECHNICAL SKILLS & ENTERPRISE PRODUCTS CATALOG
// =========================================================================
// =========================================================================
// TAB 4: TECHNICAL SKILLS & ENTERPRISE PRODUCTS CATALOG
// =========================================================================

const DOMAIN_METADATA = {
  agenticAIAndLLMs: {
    title: 'Agentic AI & Large Language Models',
    subtitle: 'Model Context Protocol (MCP), Context Engineering & Agentic Workflows',
    icon: '🤖',
    badge: 'Core Focus'
  },
  cloudAndDevOps: {
    title: 'Cloud Architecture & Production DevOps',
    subtitle: 'AWS Certified Solutions Architect, Containers & Stealth Automation',
    icon: '☁️',
    badge: 'AWS Certified'
  },
  softwareAndData: {
    title: 'Distributed Software, Databases & Web3',
    subtitle: 'Modern Backend, High-Performance Streaming & SQL Optimization',
    icon: '⚡',
    badge: 'Full Stack'
  },
  supportAndQuality: {
    title: 'L3 Support Engineering & Incident RCA',
    subtitle: 'Deep Forensic Triage, 5 Whys & Zero-Downtime Maintenance',
    icon: '🛡️',
    badge: '390+ RCAs'
  }
};

function SkillsView({ data }) {
  if (!data) return null;
  const { technicalSkillsMatrix, enterpriseProductsCatalog } = data;

  return (
    <div className="space-y-8 animate-fade-in">
      
      {/* 1. Technical Skills Domains (4 Architecture Pillars) */}
      <div>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 mb-5">
          <div>
            <h3 className="figma-section-heading">
              <span className="text-cyan-400 font-mono text-sm">//</span> Technical Competency Matrix
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              Quantified proficiencies across agentic AI, AWS cloud architecture, modern software engineering, and L3 incident diagnostics.
            </p>
          </div>
          <span className="text-xs font-mono text-cyan-400 shrink-0 self-start sm:self-auto">
            4 Architecture Domains
          </span>
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
          {technicalSkillsMatrix && Object.keys(technicalSkillsMatrix).map((key) => {
            const meta = DOMAIN_METADATA[key] || {
              title: key,
              subtitle: 'Technical Competency Domain',
              icon: '❖',
              badge: 'Architecture'
            };
            const skillsList = technicalSkillsMatrix[key] || [];

            return (
              <div key={key} className="p-5 sm:p-6 rounded-2xl bg-[#151821] border border-white/[0.08] hover:border-cyan-500/30 transition duration-300 flex flex-col justify-between space-y-4">
                
                {/* Domain Header */}
                <div className="flex items-start justify-between gap-3 pb-3 border-b border-white/[0.06]">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-cyan-950/60 border border-cyan-800/60 flex items-center justify-center text-lg shrink-0">
                      {meta.icon}
                    </div>
                    <div>
                      <h4 className="text-base font-bold text-white font-heading">
                        {meta.title}
                      </h4>
                      <p className="text-xs text-slate-400 mt-0.5 line-clamp-1">
                        {meta.subtitle}
                      </p>
                    </div>
                  </div>
                  <span className="px-2 py-0.5 rounded-full text-[10px] font-mono font-bold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30 shrink-0">
                    {meta.badge}
                  </span>
                </div>

                {/* Skills List with Proficiency & Highlights */}
                <div className="space-y-4">
                  {skillsList.map((s, idx) => {
                    const pct = s.level === 'Expert' ? 96 : s.level === 'Advanced' ? 88 : 78;
                    const badgeStyle = s.level === 'Expert'
                      ? 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30'
                      : s.level === 'Advanced'
                      ? 'bg-sky-500/15 text-sky-300 border-sky-500/30'
                      : 'bg-slate-800 text-slate-300 border-white/[0.08]';

                    return (
                      <div key={idx} className="space-y-1.5 p-2.5 rounded-xl bg-slate-900/40 border border-white/[0.04] hover:border-white/[0.1] transition">
                        <div className="flex items-center justify-between text-xs">
                          <span className="font-semibold text-slate-100 font-sans">
                            {s.name}
                          </span>
                          <span className={'px-2 py-0.5 rounded text-[10px] font-mono font-bold border ' + badgeStyle}>
                            {s.level}
                          </span>
                        </div>

                        {/* Progress Bar */}
                        <div className="w-full h-1.5 rounded-full bg-slate-800/80 overflow-hidden">
                          <div
                            className="h-full rounded-full bg-gradient-to-r from-cyan-500 to-sky-400 shadow-[0_0_8px_#38bdf8]"
                            style={{ width: `${pct}%` }}
                          ></div>
                        </div>

                        {/* Highlight / Real-World Evidence */}
                        {s.highlight && (
                          <div className="text-[11px] text-slate-400 pt-0.5 flex items-start gap-1.5 leading-relaxed">
                            <span className="text-cyan-400 shrink-0 font-mono">↳</span>
                            <span>{s.highlight}</span>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>

              </div>
            );
          })}
        </div>
      </div>

      {/* 2. Enterprise Systems Track Record (Readable, Spacious 4-Col Grid) */}
      <div>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 mb-5">
          <div>
            <h3 className="figma-section-heading">
              <span className="text-cyan-400 font-mono text-sm">//</span> Enterprise Systems Track Record
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              Documented hands-on operational, administrative, and forensics mastery across 1,900+ enterprise customer cases.
            </p>
          </div>
          <span className="text-xs font-mono text-slate-400 shrink-0 self-start sm:self-auto">
            Documented Production Cases
          </span>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 xl:grid-cols-4 gap-4">
          {enterpriseProductsCatalog?.map((prod, idx) => (
            <div
              key={idx}
              className="p-5 rounded-2xl bg-[#151821] border border-white/[0.08] hover:border-cyan-500/40 hover:bg-slate-900/60 transition duration-300 flex flex-col justify-between space-y-3 group shadow-sm"
            >
              <div>
                {/* Product Title & Case Count Badge (Full, readable title - No truncate!) */}
                <div className="flex items-start justify-between gap-2 pb-2.5 border-b border-white/[0.06]">
                  <h5 className="text-sm sm:text-base font-bold text-white font-heading leading-snug group-hover:text-cyan-300 transition">
                    {prod.product}
                  </h5>
                  <span className="px-2 py-0.5 rounded text-[11px] font-mono font-bold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30 shrink-0">
                    {prod.documentedCases}
                  </span>
                </div>

                {/* Subtitle / Label */}
                <div className="text-[10px] uppercase font-mono text-slate-500 tracking-wider mt-2.5 mb-1.5">
                  Core Expertise Areas:
                </div>

                {/* Expertise Areas Pills (Generous, clean, readable) */}
                <div className="flex flex-wrap gap-1.5">
                  {prod.expertiseAreas?.map((area, i) => (
                    <span
                      key={i}
                      className="px-2 py-1 rounded-md text-[11px] font-mono bg-slate-900/90 text-slate-300 border border-white/[0.07] group-hover:border-cyan-500/20 transition"
                    >
                      {area}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

// Insert Legacy Components with Cyan theme and Mobile Card enhancement

function ClickHouseJobsView({ jobs, onSelectJob }) {
  // Sorting state
  const [sortField, setSortField] = useState('match'); // 'title' | 'department' | 'location' | 'match' | 'salary'
  const [sortDirection, setSortDirection] = useState('desc'); // 'asc' | 'desc'
  
  // Filtering state
  const [globalSearch, setGlobalSearch] = useState('');
  const [colTitleFilter, setColTitleFilter] = useState('');
  const [colDeptFilter, setColDeptFilter] = useState('All');
  const [colLocFilter, setColLocFilter] = useState('All');
  const [colMinMatch, setColMinMatch] = useState(0); // 0, 70, 80, 90
  const [colSalaryFilter, setColSalaryFilter] = useState('');

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 20;

  // Extract unique departments & locations
  const departments = useMemo(() => {
    const set = new Set();
    jobs.forEach(j => {
      if (j.department) set.add(j.department);
    });
    return ['All', ...Array.from(set).sort()];
  }, [jobs]);

  const locations = useMemo(() => {
    const counts = {};
    jobs.forEach(j => {
      const loc = j.location || 'Unknown';
      counts[loc] = (counts[loc] || 0) + 1;
    });
    const sorted = Object.keys(counts).sort((a, b) => counts[b] - counts[a]);
    return { counts, list: ['All', ...sorted] };
  }, [jobs]);

  // Handle header click to toggle sorting (A-Z / Z-A)
  const handleSort = (field) => {
    if (sortField === field) {
      setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection(field === 'match' || field === 'salary' ? 'desc' : 'asc');
    }
    setCurrentPage(1);
  };

  // Reset all filters helper
  const resetFilters = () => {
    setGlobalSearch('');
    setColTitleFilter('');
    setColDeptFilter('All');
    setColLocFilter('All');
    setColMinMatch(0);
    setColSalaryFilter('');
    setCurrentPage(1);
  };

  const isAnyFilterActive = Boolean(
    globalSearch ||
    colTitleFilter ||
    colDeptFilter !== 'All' ||
    colLocFilter !== 'All' ||
    colMinMatch > 0 ||
    colSalaryFilter
  );

  // Filter and Sort Pipeline
  const filteredAndSortedJobs = useMemo(() => {
    let result = [...jobs];

    // Global Search
    if (globalSearch.trim()) {
      const q = globalSearch.toLowerCase();
      result = result.filter(j => 
        (j.title && j.title.toLowerCase().includes(q)) ||
        (j.department && j.department.toLowerCase().includes(q)) ||
        (j.location && j.location.toLowerCase().includes(q)) ||
        (j.overview && j.overview.toLowerCase().includes(q))
      );
    }

    // Column Filter: Title
    if (colTitleFilter.trim()) {
      const q = colTitleFilter.toLowerCase();
      result = result.filter(j => j.title && j.title.toLowerCase().includes(q));
    }

    // Column Filter: Department
    if (colDeptFilter !== 'All') {
      result = result.filter(j => j.department === colDeptFilter);
    }

    // Column Filter: Location
    if (colLocFilter !== 'All') {
      if (colLocFilter.toLowerCase() === 'latam') {
        result = result.filter(j => 
          j.location && (
            j.location.toLowerCase().includes('latam') ||
            j.location.toLowerCase().includes('latin') ||
            j.location.toLowerCase().includes('mexico') ||
            j.location.toLowerCase().includes('brazil') ||
            j.location.toLowerCase().includes('chile')
          )
        );
      } else {
        result = result.filter(j => j.location === colLocFilter);
      }
    }

    // Column Filter: Min Match %
    if (colMinMatch > 0) {
      result = result.filter(j => parseMatchValue(j.match) >= colMinMatch);
    }

    // Column Filter: Salary Text
    if (colSalaryFilter.trim()) {
      const q = colSalaryFilter.toLowerCase();
      result = result.filter(j => j.salary && j.salary.toLowerCase().includes(q));
    }

    // Sort Logic
    result.sort((a, b) => {
      let valA, valB;
      
      if (sortField === 'match') {
        valA = parseMatchValue(a.match);
        valB = parseMatchValue(b.match);
        return sortDirection === 'asc' ? valA - valB : valB - valA;
      }
      
      if (sortField === 'salary') {
        valA = parseSalaryValue(a.salary);
        valB = parseSalaryValue(b.salary);
        return sortDirection === 'asc' ? valA - valB : valB - valA;
      }

      // String sorting (A-Z / Z-A)
      valA = (a[sortField] || '').toString().toLowerCase();
      valB = (b[sortField] || '').toString().toLowerCase();

      if (valA < valB) return sortDirection === 'asc' ? -1 : 1;
      if (valA > valB) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });

    return result;
  }, [jobs, globalSearch, colTitleFilter, colDeptFilter, colLocFilter, colMinMatch, colSalaryFilter, sortField, sortDirection]);

  // Paginated slice
  const paginatedJobs = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return filteredAndSortedJobs.slice(start, start + pageSize);
  }, [filteredAndSortedJobs, currentPage]);

  const totalPages = Math.ceil(filteredAndSortedJobs.length / pageSize) || 1;

  // Render sort indicator
  const renderSortIndicator = (field) => {
    if (sortField !== field) {
      return <span className="opacity-30 ml-1 text-xs font-mono">↕</span>;
    }
    return sortDirection === 'asc' ? <Icons.ArrowUp /> : <Icons.ArrowDown />;
  };

  return (
    <div className="space-y-5 animate-fade-in">
      
      {/* Search & Quick Filter Controls Card */}
      <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] space-y-4">
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
          <div>
            <h2 className="text-lg font-bold text-white font-heading tracking-tight flex items-center">
              <span>ClickHouse Open Roles Explorer</span>
              <span className="ml-3 px-2 py-0.5 text-xs font-mono rounded-md bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
                {filteredAndSortedJobs.length} of {jobs.length} Positions
              </span>
            </h2>
            <p className="text-xs text-slate-400 mt-0.5">
              Live Ashby data with multi-column sorting (A-Z & Z-A), direct header filters, and LatAm regional focus.
            </p>
          </div>

          {/* Global Search Input */}
          <div className="flex items-center space-x-2 w-full md:w-auto">
            <div className="relative w-full md:w-72">
              <input
                type="text"
                value={globalSearch}
                onChange={(e) => { setGlobalSearch(e.target.value); setCurrentPage(1); }}
                placeholder="Search across all fields..."
                className="w-full pl-9 pr-8 py-2 bg-slate-950/80 border border-white/[0.1] rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none focus:border-cyan-500 transition"
              />
              <div className="absolute left-3 top-2.5 pointer-events-none">
                <Icons.Search />
              </div>
              {globalSearch && (
                <button
                  onClick={() => setGlobalSearch('')}
                  className="absolute right-3 top-2.5 text-xs text-slate-400 hover:text-white"
                >
                  ✕
                </button>
              )}
            </div>

            {isAnyFilterActive && (
              <button
                onClick={resetFilters}
                className="px-3 py-2 rounded-xl text-xs font-medium text-rose-300 bg-rose-950/50 hover:bg-rose-900/60 border border-rose-800/60 flex items-center whitespace-nowrap transition"
                title="Clear all active filters"
              >
                <Icons.Reset />
                <span>Reset</span>
              </button>
            )}
          </div>
        </div>

        {/* Quick Region Pills (Including LatAm) */}
        <div className="space-y-2 pt-2 border-t border-white/[0.06]">
          <div className="flex items-center justify-between">
            <span className="text-xs font-medium text-slate-400 flex items-center">
              <Icons.Filter />
              <span>Filter by Region:</span>
            </span>
            {colLocFilter !== 'All' && (
              <span className="text-[11px] text-cyan-400 font-mono">
                Active Filter: <span className="font-bold underline">{colLocFilter}</span> ({filteredAndSortedJobs.length} matches)
              </span>
            )}
          </div>

          <div className="flex flex-wrap items-center gap-1.5 text-xs">
            <button
              onClick={() => { setColLocFilter('All'); setCurrentPage(1); }}
              className={`px-3 py-1 rounded-lg border text-xs font-medium transition ${
                colLocFilter === 'All'
                  ? 'bg-white/[0.1] text-white border-white/[0.16]'
                  : 'text-slate-400 border-white/[0.06] hover:bg-white/[0.03] hover:text-slate-200'
              }`}
            >
              All Locations ({jobs.length})
            </button>

            {/* LATAM Highlighted Pill */}
            <button
              onClick={() => { setColLocFilter('LatAm'); setCurrentPage(1); }}
              className={`px-3 py-1 rounded-lg border text-xs font-bold transition flex items-center space-x-1 ${
                colLocFilter === 'LatAm'
                  ? 'bg-cyan-600 text-white border-cyan-400 shadow-sm'
                  : 'text-cyan-400 bg-cyan-500/10 border-cyan-500/30 hover:bg-cyan-500/20'
              }`}
            >
              <span>🌎 LatAm</span>
              <span className="ml-1 px-1.5 py-0.2 rounded-full text-[10px] font-mono bg-cyan-900 text-cyan-200">
                {locations.counts['LatAm'] || 2}
              </span>
            </button>

            {/* Popular Regions */}
            {['AMER', 'United States', 'EMEA', 'United Kingdom', 'Germany', 'Spain', 'APJ'].map((locName) => {
              const count = locations.counts[locName] || 0;
              if (count === 0) return null;
              const isSelected = colLocFilter === locName;

              return (
                <button
                  key={locName}
                  onClick={() => { setColLocFilter(locName); setCurrentPage(1); }}
                  className={`px-2.5 py-1 rounded-lg border text-xs font-medium transition flex items-center space-x-1 ${
                    isSelected
                      ? 'bg-white/[0.1] text-white border-white/[0.16]'
                      : 'text-slate-400 border-white/[0.06] hover:bg-white/[0.03] hover:text-slate-200'
                  }`}
                >
                  <span>{locName}</span>
                  <span className="ml-1 px-1.5 py-0.2 rounded text-[10px] font-mono bg-slate-800 text-slate-400">
                    {count}
                  </span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Secondary Filters Bar: Department & Match Tier */}
        <div className="flex flex-wrap items-center justify-between gap-4 pt-2.5 border-t border-white/[0.06] text-xs">
          
          <div className="flex flex-wrap items-center gap-3">
            {/* Department Dropdown */}
            <div className="flex items-center space-x-2">
              <span className="text-slate-400 font-medium">Department:</span>
              <select
                value={colDeptFilter}
                onChange={(e) => { setColDeptFilter(e.target.value); setCurrentPage(1); }}
                className="bg-slate-950 border border-white/[0.1] text-xs text-slate-200 rounded-lg px-2.5 py-1.5 focus:outline-none focus:border-cyan-500"
              >
                {departments.map((d, i) => (
                  <option key={i} value={d}>{d}</option>
                ))}
              </select>
            </div>

            {/* Match Tier Filter */}
            <div className="flex items-center space-x-1.5">
              <span className="text-slate-400 font-medium mr-1">Match:</span>
              <button
                onClick={() => { setColMinMatch(0); setCurrentPage(1); }}
                className={`px-2.5 py-1 rounded-lg border text-xs transition ${
                  colMinMatch === 0
                    ? 'bg-white/[0.1] text-white border-white/[0.16]'
                    : 'text-slate-400 border-white/[0.06] hover:bg-white/[0.03]'
                }`}
              >
                All
              </button>
              <button
                onClick={() => { setColMinMatch(80); setCurrentPage(1); }}
                className={`px-2.5 py-1 rounded-lg border text-xs transition ${
                  colMinMatch === 80
                    ? 'bg-sky-950 text-sky-300 border-sky-700'
                    : 'text-slate-400 border-white/[0.06] hover:bg-white/[0.03]'
                }`}
              >
                80%+ High
              </button>
              <button
                onClick={() => { setColMinMatch(90); setCurrentPage(1); }}
                className={`px-2.5 py-1 rounded-lg border text-xs transition ${
                  colMinMatch === 90
                    ? 'bg-cyan-950 text-cyan-300 border-cyan-700'
                    : 'text-slate-400 border-white/[0.06] hover:bg-white/[0.03]'
                }`}
              >
                90%+ Top
              </button>
            </div>
          </div>

          {/* Active Sort Indicator */}
          <div className="text-xs text-slate-400 font-mono">
            Sorted by: <span className="text-cyan-400 font-semibold uppercase">{sortField}</span> ({sortDirection === 'asc' ? 'A-Z / Low-to-High' : 'Z-A / High-to-Low'})
          </div>

        </div>
      </div>

      {/* Main Interactive Table with Direct Header Filters */}
      <div className="overflow-x-auto rounded-xl border border-white/[0.08] bg-slate-900/30 shadow-2xl">
        <table className="w-full text-left text-xs text-slate-300">
          
          {/* Header Row: Clickable Sort Labels */}
          <thead className="bg-[#0b101d] text-slate-400 uppercase tracking-wider font-semibold border-b border-white/[0.08] select-none font-mono">
            <tr>
              <th
                onClick={() => handleSort('title')}
                className="py-3 px-4 cursor-pointer hover:text-white transition group"
              >
                <div className="flex items-center justify-between">
                  <span>Job Title</span>
                  <div className="flex items-center">
                    <span className="text-[10px] text-slate-500 mr-1">Sort</span>
                    {renderSortIndicator('title')}
                  </div>
                </div>
              </th>

              <th
                onClick={() => handleSort('department')}
                className="py-3 px-4 cursor-pointer hover:text-white transition group w-48"
              >
                <div className="flex items-center justify-between">
                  <span>Department</span>
                  <div className="flex items-center">
                    <span className="text-[10px] text-slate-500 mr-1">Sort</span>
                    {renderSortIndicator('department')}
                  </div>
                </div>
              </th>

              <th
                onClick={() => handleSort('location')}
                className="py-3 px-4 cursor-pointer hover:text-white transition group w-44"
              >
                <div className="flex items-center justify-between">
                  <span>Location</span>
                  <div className="flex items-center">
                    <span className="text-[10px] text-slate-500 mr-1">Sort</span>
                    {renderSortIndicator('location')}
                  </div>
                </div>
              </th>

              <th
                onClick={() => handleSort('match')}
                className="py-3 px-4 cursor-pointer hover:text-white transition group text-center w-28"
              >
                <div className="flex items-center justify-center">
                  <span>Match %</span>
                  {renderSortIndicator('match')}
                </div>
              </th>

              <th
                onClick={() => handleSort('salary')}
                className="py-3 px-4 cursor-pointer hover:text-white transition group hidden lg:table-cell w-56"
              >
                <div className="flex items-center justify-between">
                  <span>Compensation</span>
                  <div className="flex items-center">
                    <span className="text-[10px] text-slate-500 mr-1">Sort</span>
                    {renderSortIndicator('salary')}
                  </div>
                </div>
              </th>

              <th className="py-3 px-4 text-right w-28">Actions</th>
            </tr>

            {/* Direct Header Filter Controls Row */}
            <tr className="bg-[#080c16] border-b border-white/[0.08] lowercase font-normal text-slate-300 font-sans">
              
              {/* Title Filter */}
              <th className="p-2">
                <input
                  type="text"
                  value={colTitleFilter}
                  onChange={(e) => { setColTitleFilter(e.target.value); setCurrentPage(1); }}
                  placeholder="Filter title..."
                  className="w-full px-2.5 py-1 text-xs bg-slate-900 border border-white/[0.08] rounded-lg text-slate-200 placeholder-slate-500 focus:outline-none focus:border-cyan-500"
                />
              </th>

              {/* Department Filter */}
              <th className="p-2">
                <select
                  value={colDeptFilter}
                  onChange={(e) => { setColDeptFilter(e.target.value); setCurrentPage(1); }}
                  className="w-full px-2 py-1 text-xs bg-slate-900 border border-white/[0.08] rounded-lg text-slate-200 focus:outline-none focus:border-cyan-500"
                >
                  <option value="All">All Departments</option>
                  {departments.filter(d => d !== 'All').map((d, i) => (
                    <option key={i} value={d}>{d}</option>
                  ))}
                </select>
              </th>

              {/* Location Filter */}
              <th className="p-2">
                <select
                  value={colLocFilter}
                  onChange={(e) => { setColLocFilter(e.target.value); setCurrentPage(1); }}
                  className="w-full px-2 py-1 text-xs bg-slate-900 border border-white/[0.08] rounded-lg text-slate-200 focus:outline-none focus:border-cyan-500 font-medium text-cyan-400"
                >
                  <option value="All">All Locations</option>
                  <option value="LatAm">🌎 LatAm (All)</option>
                  {locations.list.filter(l => l !== 'All' && l !== 'LatAm').map((loc, i) => (
                    <option key={i} value={loc} className="text-slate-200">
                      {loc} ({locations.counts[loc] || 0})
                    </option>
                  ))}
                </select>
              </th>

              {/* Match Filter */}
              <th className="p-2">
                <select
                  value={colMinMatch}
                  onChange={(e) => { setColMinMatch(Number(e.target.value)); setCurrentPage(1); }}
                  className="w-full px-1.5 py-1 text-xs bg-slate-900 border border-white/[0.08] rounded-lg text-slate-200 focus:outline-none focus:border-cyan-500 text-center font-mono"
                >
                  <option value="0">All</option>
                  <option value="90">90%+</option>
                  <option value="80">80%+</option>
                  <option value="70">70%+</option>
                </select>
              </th>

              {/* Salary Filter */}
              <th className="p-2 hidden lg:table-cell">
                <input
                  type="text"
                  value={colSalaryFilter}
                  onChange={(e) => { setColSalaryFilter(e.target.value); setCurrentPage(1); }}
                  placeholder="Filter salary..."
                  className="w-full px-2.5 py-1 text-xs bg-slate-900 border border-white/[0.08] rounded-lg text-slate-200 placeholder-slate-500 focus:outline-none focus:border-cyan-500 font-mono"
                />
              </th>

              {/* Reset Action */}
              <th className="p-2 text-right">
                {isAnyFilterActive && (
                  <button
                    onClick={resetFilters}
                    className="px-2 py-1 text-[11px] rounded text-rose-400 hover:text-white hover:bg-rose-900/40 transition font-mono"
                  >
                    Clear
                  </button>
                )}
              </th>
            </tr>
          </thead>

          {/* Table Body */}
          <tbody className="divide-y divide-white/[0.04]">
            {paginatedJobs.length === 0 ? (
              <tr>
                <td colSpan="6" className="py-14 text-center">
                  <div className="max-w-md mx-auto space-y-3">
                    <p className="text-sm font-semibold text-slate-300 font-heading">
                      No positions match your selected filter criteria.
                    </p>
                    <p className="text-xs text-slate-400">
                      Try clearing or loosening your filters (e.g., location, department, or minimum match score).
                    </p>
                    <button
                      onClick={resetFilters}
                      className="mt-2 px-4 py-1.5 rounded-xl text-xs font-semibold bg-white/[0.1] hover:bg-white/[0.16] border border-white/[0.12] text-white transition shadow"
                    >
                      Clear All Filters
                    </button>
                  </div>
                </td>
              </tr>
            ) : (
              paginatedJobs.map((job, idx) => {
                const matchVal = parseMatchValue(job.match);
                const matchBadgeClass =
                  matchVal >= 90
                    ? 'bg-cyan-500/10 text-cyan-400 border-cyan-500/30 font-bold'
                    : matchVal >= 80
                    ? 'bg-sky-500/10 text-sky-300 border-sky-500/30 font-semibold'
                    : matchVal >= 70
                    ? 'bg-amber-500/10 text-amber-300 border-amber-500/30'
                    : 'bg-slate-800 text-slate-300 border-slate-700';

                const isLatAm =
                  job.location &&
                  (job.location.toLowerCase().includes('latam') ||
                    job.location.toLowerCase().includes('latin') ||
                    job.location.toLowerCase().includes('mexico'));

                return (
                  <tr
                    key={idx}
                    className={`hover:bg-white/[0.025] transition cursor-pointer group ${
                      isLatAm ? 'bg-cyan-500/[0.03]' : ''
                    }`}
                    onClick={() => onSelectJob(job)}
                  >
                    {/* Title */}
                    <td className="py-3 px-4">
                      <div className="font-semibold text-white group-hover:text-cyan-400 transition flex items-center flex-wrap gap-1.5">
                        <span>{job.title}</span>
                        {isLatAm && (
                          <span className="px-1.5 py-0.2 rounded text-[10px] font-bold font-mono bg-cyan-950 text-cyan-300 border border-cyan-700">
                            LatAm
                          </span>
                        )}
                      </div>
                      <div className="text-[11px] text-slate-400 line-clamp-1 mt-0.5">
                        {job.overview || 'Overview description available in details view.'}
                      </div>
                    </td>

                    {/* Department */}
                    <td className="py-3 px-4 whitespace-nowrap">
                      <span className="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-900 text-slate-300 border border-white/[0.06]">
                        {job.department}
                      </span>
                    </td>

                    {/* Location */}
                    <td className="py-3 px-4 whitespace-nowrap">
                      <span className={`inline-flex items-center px-2 py-0.5 rounded text-[11px] font-mono ${
                        isLatAm
                          ? 'bg-cyan-950 text-cyan-300 border border-cyan-700 font-bold'
                          : 'text-slate-300'
                      }`}>
                        📍 {job.location}
                      </span>
                    </td>

                    {/* Match */}
                    <td className="py-3 px-4 whitespace-nowrap text-center">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-mono border ${matchBadgeClass}`}>
                        {job.match || '50%'}
                      </span>
                    </td>

                    {/* Salary */}
                    <td className="py-3 px-4 whitespace-nowrap hidden lg:table-cell font-mono text-[11px] text-slate-300">
                      {job.salary}
                    </td>

                    {/* Actions */}
                    <td className="py-3 px-4 whitespace-nowrap text-right">
                      <div className="flex items-center justify-end space-x-1.5">
                        <button
                          onClick={(e) => { e.stopPropagation(); onSelectJob(job); }}
                          className="px-2.5 py-1 text-xs rounded-lg bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-white/[0.08] transition"
                        >
                          Details
                        </button>
                        <a
                          href={job.url}
                          target="_blank"
                          rel="noreferrer"
                          onClick={(e) => e.stopPropagation()}
                          className="px-2.5 py-1 text-xs rounded-lg bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 border border-cyan-500/30 transition flex items-center"
                        >
                          <span>Ashby</span>
                          <Icons.ExternalLink />
                        </a>
                      </div>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination Controls */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 p-4 rounded-xl bg-slate-900/40 border border-white/[0.08] text-xs text-slate-400 font-mono">
        <div>
          Showing page <span className="font-semibold text-white">{currentPage}</span> of{' '}
          <span className="font-semibold text-white">{totalPages}</span> ({filteredAndSortedJobs.length} matching positions)
        </div>
        <div className="flex items-center space-x-2">
          <button
            onClick={() => setCurrentPage(1)}
            disabled={currentPage === 1}
            className="px-2.5 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed text-white transition"
          >
            « First
          </button>
          <button
            onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
            disabled={currentPage === 1}
            className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed text-white transition"
          >
            ‹ Prev
          </button>
          <span className="px-3 py-1 font-bold text-cyan-400">
            {currentPage} / {totalPages}
          </span>
          <button
            onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
            disabled={currentPage === totalPages}
            className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed text-white transition"
          >
            Next ›
          </button>
          <button
            onClick={() => setCurrentPage(totalPages)}
            disabled={currentPage === totalPages}
            className="px-2.5 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed text-white transition"
          >
            Last »
          </button>
        </div>
      </div>
    </div>
  );
}



// =========================================================================
// METRIC MODAL (Centered Modal with Blurred Dark Backdrop & Forensic Breakdown)
// =========================================================================

function MetricModal({ metric, onClose, onSelectPrev, onSelectNext }) {
  if (!metric) return null;

  useEffect(() => {
    function handleKeyDown(e) {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft' && onSelectPrev) onSelectPrev();
      if (e.key === 'ArrowRight' && onSelectNext) onSelectNext();
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose, onSelectPrev, onSelectNext]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6 bg-black/80 backdrop-blur-md animate-fade-in"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="bg-[#151821] border border-white/[0.14] rounded-2xl max-w-2xl w-full p-5 sm:p-7 shadow-2xl space-y-5 relative max-h-[90vh] overflow-y-auto">
        
        {/* Top Header Controls */}
        <div className="flex items-start justify-between gap-4">
          <div>
            <div className="flex items-center space-x-2 mb-1.5">
              <span className="px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                METRIC FORENSIC DOSSIER
              </span>
              <span className="text-[11px] text-slate-400 font-mono hidden sm:inline">
                Verified Enterprise Track Record
              </span>
            </div>
            <div className="text-3xl sm:text-4xl font-bold font-mono text-cyan-400 tracking-tight">
              {metric.value}
            </div>
            <h2 className="text-base sm:text-lg font-bold text-white font-heading mt-1">
              {metric.label}
            </h2>
          </div>

          <button
            onClick={onClose}
            aria-label="Close dialog"
            className="text-slate-400 hover:text-white p-2 rounded-xl bg-slate-800/80 hover:bg-slate-700 transition flex-shrink-0"
          >
            ✕
          </button>
        </div>

        {/* Narrative Detail */}
        <div className="p-4 rounded-xl bg-slate-950/70 border border-white/[0.08]">
          <div className="text-[10px] font-bold text-slate-400 uppercase tracking-wider font-mono mb-1.5">
            Core Scope & Technical Context
          </div>
          <p className="text-xs sm:text-sm text-slate-200 leading-relaxed font-sans">
            {metric.detail}
          </p>
        </div>

        {/* Quantified Business Impact */}
        {metric.businessImpact && (
          <div className="p-4 rounded-xl bg-cyan-950/40 border border-cyan-500/40 text-xs sm:text-sm text-cyan-200 flex items-start space-x-3">
            <span className="text-cyan-400 font-bold text-base mt-0.5">★</span>
            <div>
              <span className="font-bold text-white uppercase font-mono tracking-wider text-xs block mb-0.5">
                Quantified Business Impact
              </span>
              <span className="leading-relaxed">{metric.businessImpact}</span>
            </div>
          </div>
        )}

        {/* Forensic Proof Bullets */}
        {metric.extendedBreakdown && metric.extendedBreakdown.length > 0 && (
          <div>
            <h4 className="text-xs font-bold text-slate-300 uppercase tracking-wider mb-2.5 font-mono">
              Forensic Engineering Methodology & Evidence
            </h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
              {metric.extendedBreakdown.map((item, idx) => (
                <div
                  key={idx}
                  className="p-3 rounded-xl bg-slate-950/60 border border-white/[0.06] flex items-start space-x-2 text-xs text-slate-200"
                >
                  <span className="text-cyan-400 font-bold font-mono text-sm leading-none mt-0.5">›</span>
                  <span className="leading-relaxed">{item}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Footer Navigation & Close */}
        <div className="pt-3 border-t border-white/[0.08] flex items-center justify-between gap-2 flex-wrap">
          <div className="flex items-center space-x-2">
            {onSelectPrev && (
              <button
                onClick={onSelectPrev}
                className="px-3 py-1.5 rounded-lg text-xs font-mono text-slate-300 hover:text-white bg-slate-800/80 hover:bg-slate-700 transition"
              >
                ← Prev Metric
              </button>
            )}
            {onSelectNext && (
              <button
                onClick={onSelectNext}
                className="px-3 py-1.5 rounded-lg text-xs font-mono text-slate-300 hover:text-white bg-slate-800/80 hover:bg-slate-700 transition"
              >
                Next Metric →
              </button>
            )}
          </div>

          <button
            onClick={onClose}
            className="px-4 py-1.5 rounded-xl text-xs font-medium text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 transition"
          >
            Done
          </button>
        </div>

      </div>
    </div>
  );
}

// =========================================================================
// JOB DETAILS MODAL / DRAWER
// =========================================================================

function JobDetailsModal({ job, onClose }) {
  if (!job) return null;

  useEffect(() => {
    function handleKeyDown(e) {
      if (e.key === 'Escape') onClose();
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-fade-in"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="bg-slate-900 border border-white/[0.12] rounded-2xl max-w-2xl w-full p-6 sm:p-8 shadow-2xl space-y-6 relative max-h-[90vh] overflow-y-auto">
        
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute top-5 right-5 text-slate-400 hover:text-white p-2 rounded-full hover:bg-slate-800 transition"
        >
          ✕
        </button>

        {/* Modal Header */}
        <div>
          <div className="flex flex-wrap items-center gap-2 mb-2">
            <span className="px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
              {job.department}
            </span>
            <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-300 border border-white/[0.06]">
              📍 {job.location}
            </span>
          </div>
          <h2 className="text-xl sm:text-2xl font-bold text-white tracking-tight font-heading">
            {job.title}
          </h2>
        </div>

        {/* Quick Stats Grid */}
        <div className="grid grid-cols-2 gap-3 p-4 rounded-xl bg-slate-950/70 border border-white/[0.08]">
          <div>
            <div className="text-[10px] text-slate-400 uppercase tracking-wider font-semibold font-mono">Match Score</div>
            <div className="text-2xl font-bold text-cyan-400 font-mono mt-0.5">
              {job.match || '50%'}
            </div>
            <div className="text-[11px] text-slate-500">Calculated against Xavier's profile</div>
          </div>
          <div>
            <div className="text-[10px] text-slate-400 uppercase tracking-wider font-semibold font-mono">Compensation Band</div>
            <div className="text-sm font-bold text-white font-mono mt-1">
              {job.salary}
            </div>
            <div className="text-[11px] text-slate-500">Market benchmark estimation</div>
          </div>
        </div>

        {/* Overview Section */}
        <div>
          <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2 font-mono">
            Role Overview & Mission (from Ashby)
          </h3>
          <div className="p-4 rounded-xl bg-slate-950/40 border border-white/[0.06] text-xs sm:text-sm text-slate-200 leading-relaxed whitespace-pre-line">
            {job.overview || 'Detailed overview available directly on the ClickHouse Ashby listing.'}
          </div>
        </div>

        {/* Modal Actions */}
        <div className="pt-4 border-t border-white/[0.08] flex items-center justify-between gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-xl text-xs font-medium text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 transition"
          >
            Close
          </button>
          <a
            href={job.url}
            target="_blank"
            rel="noreferrer"
            className="px-5 py-2 rounded-xl text-xs font-bold text-black bg-cyan-400 hover:bg-cyan-300 shadow-lg shadow-cyan-500/20 transition flex items-center space-x-1.5"
          >
            <span>Apply via Ashby</span>
            <Icons.ExternalLink />
          </a>
        </div>

      </div>
    </div>
  );
}

// =========================================================================

// =========================================================================
// TAB 3: RAW DOCS VIEW (Dual-Pane Reader for Markdown Files)
// =========================================================================

function renderMarkdownSafely(md) {
  if (!md) return '';
  // Try using window.marked if available
  try {
    if (typeof window !== 'undefined' && window.marked) {
      if (typeof window.marked.parse === 'function') {
        return window.marked.parse(md);
      } else if (typeof window.marked === 'function') {
        return window.marked(md);
      }
    }
  } catch (err) {
    console.warn('marked.parse failed, using fallback markdown parser:', err);
  }

  // Reliable Fallback Parser (Zero External Dependencies)
  let html = md
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');

  // Headings
  html = html.replace(/^#### (.*$)/gim, '<h4 class="text-xs font-bold text-white uppercase font-mono tracking-wider mt-4 mb-2">$1</h4>');
  html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
  html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
  html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');

  // Bold & Italic
  html = html.replace(/\*\*\*(.*?)\*\*\*/gim, '<strong><em>$1</em></strong>');
  html = html.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>');
  html = html.replace(/\*(.*?)\*/gim, '<em>$1</em>');

  // Links
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');

  // Code blocks & inline code
  html = html.replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>');
  html = html.replace(/`([^`]+)`/gim, '<code>$1</code>');

  // Horizontal rules
  html = html.replace(/^---$/gim, '<hr>');

  // Lists
  html = html.replace(/^\* (.*$)/gim, '<li>$1</li>');
  html = html.replace(/^- (.*$)/gim, '<li>$1</li>');

  // Paragraphs
  html = html.split('\n\n').map(p => {
    p = p.trim();
    if (!p) return '';
    if (p.startsWith('<h') || p.startsWith('<pre') || p.startsWith('<hr') || p.startsWith('<li')) return p;
    return '<p>' + p.replace(/\n/g, '<br>') + '</p>';
  }).join('\n');

  return html;
}

function RawDocsView({ skillsMd, positionsMd, isAdmin }) {
  const [docType, setDocType] = useState('skills'); // 'skills' | 'positions'
  const [copied, setCopied] = useState(false);

  const activeContent = (docType === 'positions' && isAdmin) ? positionsMd : skillsMd;
  const activeFileName = (docType === 'positions' && isAdmin) ? 'positions_analysis.md' : 'xavier_skills.md';

  const parsedHtml = useMemo(() => {
    return renderMarkdownSafely(activeContent);
  }, [activeContent]);

  const handleCopy = () => {
    if (activeContent && navigator.clipboard) {
      navigator.clipboard.writeText(activeContent).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }).catch(() => {});
    }
  };

  const handleDownload = () => {
    if (!activeContent) return;
    const blob = new Blob([activeContent], { type: 'text/markdown;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', activeFileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-5 animate-fade-in max-w-5xl mx-auto">
      
      {/* Top Controls Bar */}
      <div className="p-4 sm:p-5 rounded-2xl bg-slate-900/60 border border-white/[0.08] flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center space-x-2">
            <span className="text-cyan-400 font-mono text-xs font-semibold">// Dossier Artifact</span>
            <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-950/60 text-cyan-300 border border-cyan-800/60">
              {activeFileName}
            </span>
          </div>
          <h2 className="text-lg font-bold text-white tracking-tight font-heading mt-0.5">
            {docType === 'positions' && isAdmin
              ? 'Ashby Roles Scrape & Gap Analysis'
              : 'Executive Systems Architecture & Skills Dossier'}
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            {isAdmin 
              ? 'Live Markdown inspection and export interface.' 
              : 'Official production-grade engineering dossier and verified credentials.'}
          </p>
        </div>

        {/* Admin Document Switcher OR Public Actions */}
        <div className="flex items-center flex-wrap gap-2">
          {isAdmin && (
            <div className="flex items-center space-x-1.5 bg-slate-950 p-1 rounded-xl border border-white/[0.08] text-xs">
              <button
                onClick={() => setDocType('skills')}
                className={'px-3 py-1.5 rounded-lg font-medium transition ' + (
                  docType === 'skills' ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 shadow-sm' : 'text-slate-400 hover:text-white'
                )}
              >
                xavier_skills.md
              </button>
              <button
                onClick={() => setDocType('positions')}
                className={'px-3 py-1.5 rounded-lg font-medium transition ' + (
                  docType === 'positions' ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 shadow-sm' : 'text-slate-400 hover:text-white'
                )}
              >
                positions_analysis.md
              </button>
            </div>
          )}

          {/* Quick Copy & Download Buttons */}
          <div className="flex items-center space-x-1.5 text-xs font-mono">
            <button
              onClick={handleCopy}
              className="px-3 py-1.5 rounded-lg bg-slate-900 border border-white/[0.08] hover:border-cyan-500/40 text-slate-300 hover:text-white transition flex items-center gap-1.5"
              title="Copy Raw Markdown"
            >
              {copied ? (
                <>
                  <span className="text-cyan-400 font-bold">✓</span>
                  <span className="text-cyan-400">Copied</span>
                </>
              ) : (
                <>
                  <span>📋</span>
                  <span>Copy</span>
                </>
              )}
            </button>
            <button
              onClick={handleDownload}
              className="px-3 py-1.5 rounded-lg bg-cyan-500/10 border border-cyan-500/30 hover:bg-cyan-500/20 text-cyan-300 hover:text-white transition flex items-center gap-1.5"
              title="Download Markdown Document"
            >
              <Icons.CloudDownload />
              <span>Download</span>
            </button>
          </div>
        </div>
      </div>

      {/* Rendered Markdown Body */}
      <div className="p-6 sm:p-8 rounded-2xl bg-slate-900/40 border border-white/[0.08] min-h-[400px]">
        {parsedHtml ? (
          <div
            className="markdown-body text-xs sm:text-sm"
            dangerouslySetInnerHTML={{ __html: parsedHtml }}
          />
        ) : activeContent ? (
          <pre className="text-slate-300 font-mono text-xs whitespace-pre-wrap leading-relaxed p-4 bg-slate-950 rounded-xl overflow-x-auto">
            {activeContent}
          </pre>
        ) : (
          <div className="flex flex-col items-center justify-center py-20 space-y-3 text-slate-400 font-mono text-xs">
            <div className="w-8 h-8 border-2 border-slate-700 border-t-cyan-400 rounded-full animate-spin"></div>
            <p>Loading Technical Dossier Markdown...</p>
          </div>
        )}
      </div>

    </div>
  );
}

function ChartCanvas({ type, data, options, height = 260 }) {
  const canvasRef = useRef(null);
  const chartRef = useRef(null);

  useEffect(() => {
    if (!canvasRef.current || !window.Chart || !data) return;

    if (chartRef.current) {
      chartRef.current.destroy();
    }

    // Default typography and palette for dark enterprise theme
    Chart.defaults.color = '#94a3b8';
    Chart.defaults.font.family = "'Geist Sans', 'Inter', -apple-system, sans-serif";

    const ctx = canvasRef.current.getContext('2d');
    chartRef.current = new Chart(ctx, {
      type,
      data,
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: (type === 'doughnut' || type === 'pie' || type === 'polarArea'),
            position: 'bottom',
            labels: {
              boxWidth: 10,
              boxHeight: 10,
              padding: 12,
              color: '#cbd5e1',
              font: { size: 10, weight: '500' }
            }
          },
          tooltip: {
            backgroundColor: '#0d1527',
            borderColor: 'rgba(255, 255, 255, 0.12)',
            borderWidth: 1,
            titleColor: '#ffffff',
            bodyColor: '#cbd5e1',
            padding: 10,
            boxPadding: 4,
            usePointStyle: true,
            titleFont: { size: 11, weight: 'bold' },
            bodyFont: { size: 10 }
          }
        },
        scales: (type === 'doughnut' || type === 'pie' || type === 'polarArea') ? {} : {
          x: {
            grid: { color: 'rgba(255, 255, 255, 0.04)' },
            ticks: { color: '#64748b', font: { size: 10 } }
          },
          y: {
            grid: { color: 'rgba(255, 255, 255, 0.04)' },
            ticks: { color: '#64748b', font: { size: 10 } }
          }
        },
        ...options
      }
    });

    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    };
  }, [type, data, options]);

  return (
    <div style={{ height: `${height}px`, width: '100%', position: 'relative' }}>
      <canvas ref={canvasRef} />
    </div>
  );
}

// --- Statistics & Career Intelligence Analytics View ---

function StatisticsView({ data }) {
  const [selectedDomain, setSelectedDomain] = useState('ITSM & Support');
  const [searchQuery, setSearchQuery] = useState('');

  if (!data) {
    return (
      <div className="flex flex-col items-center justify-center py-28 space-y-4">
        <div className="w-10 h-10 border-2 border-slate-700 border-t-cyan-400 rounded-full animate-spin"></div>
        <p className="text-xs text-slate-400 font-mono tracking-wider uppercase">
          Synthesizing 3,018 Conversation Diagnostics...
        </p>
      </div>
    );
  }

  const {
    summary,
    domainDistribution = [],
    topTechnologies = [],
    topEntities = [],
    topProblemSolvingTags = [],
    timeline = [],
    complexityDistribution = [],
    sizeDistribution = [],
    domainShowcases = {}
  } = data;

  // Chart 1: Domain Distribution (Doughnut)
  const chart1Data = {
    labels: domainDistribution.map(d => d.category),
    datasets: [{
      data: domainDistribution.map(d => d.total),
      backgroundColor: domainDistribution.map(d => d.color),
      borderColor: '#090d16',
      borderWidth: 2,
      hoverOffset: 6
    }]
  };
  const chart1Options = {
    cutout: '62%'
  };

  // Chart 2: Top Production Technologies (Horizontal Bar)
  const topTechSlice = topTechnologies.filter(t => t.name !== 'LLMs & GenAI').slice(0, 10);
  const chart2Data = {
    labels: topTechSlice.map(t => t.name),
    datasets: [{
      label: 'Production Invocations',
      data: topTechSlice.map(t => t.count),
      backgroundColor: 'rgba(16, 185, 129, 0.75)',
      borderColor: '#38bdf8',
      borderWidth: 1,
      borderRadius: 4
    }]
  };
  const chart2Options = {
    indexAxis: 'y',
    plugins: { legend: { display: false } }
  };

  // Chart 3: Enterprise Systems & Platform Footprint (Bar)
  const topEntitiesSlice = topEntities.slice(0, 10);
  const chart3Data = {
    labels: topEntitiesSlice.map(e => e.name),
    datasets: [{
      label: 'Ecosystem Engagements',
      data: topEntitiesSlice.map(e => e.count),
      backgroundColor: 'rgba(6, 182, 212, 0.75)',
      borderColor: '#06b6d4',
      borderWidth: 1,
      borderRadius: 4
    }]
  };
  const chart3Options = {
    plugins: { legend: { display: false } },
    scales: {
      x: {
        ticks: {
          maxRotation: 40,
          minRotation: 40,
          font: { size: 9 },
          color: '#94a3b8'
        }
      }
    }
  };

  // Chart 4: 25-Month Investigation Velocity Timeline (Line/Area)
  const chart4Data = {
    labels: timeline.map(t => t.month),
    datasets: [{
      label: 'Monthly Conversations',
      data: timeline.map(t => t.count),
      borderColor: '#3b82f6',
      backgroundColor: 'rgba(59, 130, 246, 0.15)',
      fill: true,
      tension: 0.35,
      pointRadius: 2.5,
      pointHoverRadius: 5,
      pointBackgroundColor: '#60a5fa'
    }]
  };
  const chart4Options = {
    plugins: { legend: { display: false } }
  };

  // Chart 5: Core Problem-Solving & Operational Disciplines (Polar Area)
  const problemTags = topProblemSolvingTags.filter(t => !['LLMs & GenAI', 'ITSM', 'Support'].includes(t.name)).slice(0, 7);
  const chart5Data = {
    labels: problemTags.map(p => p.name),
    datasets: [{
      data: problemTags.map(p => p.count),
      backgroundColor: [
        'rgba(244, 63, 94, 0.75)',
        'rgba(168, 85, 247, 0.75)',
        'rgba(59, 130, 246, 0.75)',
        'rgba(16, 185, 129, 0.75)',
        'rgba(245, 158, 11, 0.75)',
        'rgba(6, 182, 212, 0.75)',
        'rgba(99, 102, 241, 0.75)'
      ],
      borderColor: '#090d16',
      borderWidth: 2
    }]
  };

  // Chart 6: Dialogue Turn Complexity & Depth Distribution (Bar)
  const chart6Data = {
    labels: complexityDistribution.map(c => c.label),
    datasets: [{
      label: 'Conversations in Turn Bucket',
      data: complexityDistribution.map(c => c.count),
      backgroundColor: [
        'rgba(59, 130, 246, 0.75)',
        'rgba(16, 185, 129, 0.75)',
        'rgba(245, 158, 11, 0.75)',
        'rgba(236, 72, 153, 0.75)'
      ],
      borderColor: ['#3b82f6', '#38bdf8', '#f59e0b', '#ec4899'],
      borderWidth: 1,
      borderRadius: 6
    }]
  };
  const chart6Options = {
    plugins: { legend: { display: false } }
  };

  // Chart 7: Content Volume & Character Density by Domain (Horizontal Bar)
  const domainCharSorted = [...domainDistribution].sort((a, b) => b.totalChars - a.totalChars);
  const chart7Data = {
    labels: domainCharSorted.map(d => d.category),
    datasets: [{
      label: 'Characters (Millions)',
      data: domainCharSorted.map(d => +(d.totalChars / 1000000).toFixed(2)),
      backgroundColor: 'rgba(236, 72, 153, 0.75)',
      borderColor: '#ec4899',
      borderWidth: 1,
      borderRadius: 4
    }]
  };
  const chart7Options = {
    indexAxis: 'y',
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          label: (context) => ` ${context.raw}M characters`
        }
      }
    }
  };

  // Chart 8: Cloud, Infrastructure & DevOps Stack (Bar)
  const cloudStack = [
    { name: 'Bash / CLI', count: 358 },
    { name: 'AWS Lambda', count: 306 },
    { name: 'REST API', count: 283 },
    { name: 'SSL / TLS', count: 188 },
    { name: 'DNS Config', count: 94 },
    { name: 'Amazon S3', count: 80 },
    { name: 'Amazon EC2', count: 64 },
    { name: 'DynamoDB', count: 60 }
  ];
  const chart8Data = {
    labels: cloudStack.map(c => c.name),
    datasets: [{
      label: 'Systems & Cloud Workflows',
      data: cloudStack.map(c => c.count),
      backgroundColor: 'rgba(245, 158, 11, 0.75)',
      borderColor: '#f59e0b',
      borderWidth: 1,
      borderRadius: 4
    }]
  };
  const chart8Options = {
    plugins: { legend: { display: false } },
    scales: {
      x: {
        ticks: {
          maxRotation: 40,
          minRotation: 40,
          font: { size: 9 },
          color: '#94a3b8'
        }
      }
    }
  };

  // Chart 9: Investigation Payload Scope (Doughnut)
  const chart9Data = {
    labels: sizeDistribution.map(s => s.label),
    datasets: [{
      data: sizeDistribution.map(s => s.count),
      backgroundColor: [
        '#6366f1',
        '#3b82f6',
        '#38bdf8',
        '#f59e0b'
      ],
      borderColor: '#090d16',
      borderWidth: 2,
      hoverOffset: 6
    }]
  };
  const chart9Options = {
    cutout: '62%'
  };

  // Chart 10: Technical Intensity (Average Turns per Domain) (Horizontal Bar)
  const domainTurnsSorted = [...domainDistribution].sort((a, b) => b.avgTurns - a.avgTurns);
  const chart10Data = {
    labels: domainTurnsSorted.map(d => d.category),
    datasets: [{
      label: 'Avg Dialogue Turns',
      data: domainTurnsSorted.map(d => d.avgTurns),
      backgroundColor: 'rgba(139, 92, 246, 0.75)',
      borderColor: '#8b5cf6',
      borderWidth: 1,
      borderRadius: 4
    }]
  };
  const chart10Options = {
    indexAxis: 'y',
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          label: (context) => ` ${context.raw} turns / conversation`
        }
      }
    }
  };

  // Filter showcase conversations
  const showcaseList = domainShowcases[selectedDomain] || [];
  const filteredShowcase = showcaseList.filter(c => {
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    return (
      (c.title && c.title.toLowerCase().includes(q)) ||
      (c.summary && c.summary.toLowerCase().includes(q)) ||
      (c.tags && c.tags.some(t => t.toLowerCase().includes(q))) ||
      (c.technologies && c.technologies.some(t => t.toLowerCase().includes(q)))
    );
  });

  return (
    <div className="space-y-8 animate-fade-in">
      
      {/* Executive Header Banner */}
      <div className="p-6 sm:p-8 rounded-3xl bg-gradient-to-br from-slate-900 via-[#0d1527] to-slate-950 border border-white/[0.08] relative overflow-hidden shadow-2xl">
        <div className="absolute -right-24 -top-24 w-96 h-96 bg-cyan-500/10 rounded-full blur-3xl pointer-events-none"></div>
        <div className="absolute -left-24 -bottom-24 w-96 h-96 bg-cyan-500/10 rounded-full blur-3xl pointer-events-none"></div>

        <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div className="space-y-2 max-w-3xl">
            <div className="inline-flex items-center space-x-2 px-3 py-1 rounded-full bg-cyan-500/10 border border-cyan-500/25 text-cyan-400 text-xs font-mono">
              <span className="w-2 h-2 rounded-full bg-cyan-400 animate-pulse"></span>
              <span>GPT Professional Archives & Dialogue Intelligence</span>
            </div>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight font-heading">
              Conversations & Career Intelligence Analytics
            </h2>
            <p className="text-sm text-slate-300 leading-relaxed">
              Empirical diagnostic telemetry extracted from <strong className="text-white">{summary.totalConversationsAnalyzed.toLocaleString()}</strong> professional engineering conversations spanning <strong className="text-white">25 continuous months</strong> across 8 specialized production domains.
            </p>
          </div>

          <div className="flex flex-col items-start md:items-end flex-shrink-0 text-xs text-slate-400 font-mono space-y-1">
            <div>Data Ingestion: <span className="text-cyan-400 font-semibold">100% Validated</span></div>
            <div>Timeframe: <span className="text-white">{summary.activeTimeframe}</span></div>
            <div>Index Version: <span className="text-slate-300">2026.09-PRO-INDEX</span></div>
          </div>
        </div>

        {/* 4 Top Executive KPI Metric Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-8 pt-6 border-t border-white/[0.08]">
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.06] backdrop-blur-sm">
            <div className="text-[11px] font-mono text-slate-400 uppercase tracking-wider">Total Dialogues</div>
            <div className="text-2xl sm:text-3xl font-extrabold text-white font-heading mt-1">
              {summary.totalConversationsAnalyzed.toLocaleString()}
            </div>
            <div className="text-[11px] text-cyan-400 mt-1 font-mono">
              8 Specialization Domains
            </div>
          </div>

          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.06] backdrop-blur-sm">
            <div className="text-[11px] font-mono text-slate-400 uppercase tracking-wider">Dialogue Turns</div>
            <div className="text-2xl sm:text-3xl font-extrabold text-white font-heading mt-1">
              {summary.totalDialogueTurns.toLocaleString()}
            </div>
            <div className="text-[11px] text-cyan-400 mt-1 font-mono">
              {summary.userTurns.toLocaleString()} Prompts / {summary.assistantTurns.toLocaleString()} Answers
            </div>
          </div>

          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.06] backdrop-blur-sm">
            <div className="text-[11px] font-mono text-slate-400 uppercase tracking-wider">Telemetry Analyzed</div>
            <div className="text-2xl sm:text-3xl font-extrabold text-white font-heading mt-1">
              {(summary.totalCharactersAnalyzed / 1000000).toFixed(1)}M
            </div>
            <div className="text-[11px] text-violet-400 mt-1 font-mono">
              ~{(summary.estimatedWords / 1000000).toFixed(2)}M Words Processed
            </div>
          </div>

          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.06] backdrop-blur-sm">
            <div className="text-[11px] font-mono text-slate-400 uppercase tracking-wider">Continuous Activity</div>
            <div className="text-2xl sm:text-3xl font-extrabold text-white font-heading mt-1">
              25 Mo
            </div>
            <div className="text-[11px] text-amber-400 mt-1 font-mono">
              Sep 2024 &rarr; Sep 2026
            </div>
          </div>
        </div>
      </div>

      {/* 10 Visual Charts Section */}
      <div>
        <div className="flex items-center justify-between mb-5">
          <div>
            <h3 className="text-lg font-bold text-white font-heading flex items-center">
              <Icons.Chart />
              <span className="ml-2">10 Comprehensive Technical & Operational Visualizations</span>
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              Empirical breakdowns of architecture, runtime stacks, platform footprints, and operational complexity.
            </p>
          </div>
        </div>

        {/* Responsive Grid of 10 Visual Charts */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          
          {/* Chart 1: Domain Distribution */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  1. Domain Distribution & Focus
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
                  Doughnut
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Volume of investigations across the 8 professional engineering domain categories.
              </p>
            </div>
            <ChartCanvas type="doughnut" data={chart1Data} options={chart1Options} height={260} />
          </div>

          {/* Chart 2: Top Production Technologies */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  2. Top Production Technologies & Frameworks
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
                  Horizontal Bar
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Core technologies, runtimes, and engineering frameworks most frequently mobilized.
              </p>
            </div>
            <ChartCanvas type="bar" data={chart2Data} options={chart2Options} height={260} />
          </div>

          {/* Chart 3: Enterprise Platforms & Ecosystems */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  3. Enterprise Systems & Platform Footprint
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
                  Vertical Bar
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Frequency of mission-critical platforms, vendor ecosystems, and enterprise ITSMs.
              </p>
            </div>
            <ChartCanvas type="bar" data={chart3Data} options={chart3Options} height={260} />
          </div>

          {/* Chart 4: 25-Month Velocity Timeline */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  4. Investigation Velocity Timeline (25 Continuous Months)
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-blue-500/10 text-blue-400 border border-blue-500/20">
                  Area / Line
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Monthly trajectory of dialogue turns, troubleshooting bursts, and engineering iterations.
              </p>
            </div>
            <ChartCanvas type="line" data={chart4Data} options={chart4Options} height={260} />
          </div>

          {/* Chart 5: Core Problem-Solving Focus */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  5. Operational Disciplines & Problem-Solving Focus
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/20">
                  Polar Area
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Distribution of engineering disciplines: troubleshooting, migrations, UI/UX, scripting, auth.
              </p>
            </div>
            <ChartCanvas type="polarArea" data={chart5Data} height={260} />
          </div>

          {/* Chart 6: Dialogue Turn Complexity */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  6. Technical Depth & Turn Complexity Distribution
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-purple-500/10 text-purple-400 border border-purple-500/20">
                  Histogram
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Categorization into Quick Triage (1-2), Standard (3-4), Deep Dive (5-8), and Architectural (9+).
              </p>
            </div>
            <ChartCanvas type="bar" data={chart6Data} options={chart6Options} height={260} />
          </div>

          {/* Chart 7: Content Volume by Domain */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  7. Content Volume & Character Density by Domain
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-pink-500/10 text-pink-400 border border-pink-500/20">
                  Horizontal Bar
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Total character volume generated and analyzed (Millions) demonstrating rigorous depth.
              </p>
            </div>
            <ChartCanvas type="bar" data={chart7Data} options={chart7Options} height={260} />
          </div>

          {/* Chart 8: Cloud & DevOps Stack */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  8. Cloud, Infrastructure & DevOps Stack
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-amber-500/10 text-amber-400 border border-amber-500/20">
                  Vertical Bar
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Engagement across serverless (Lambda), object storage (S3), compute (EC2), security & DNS.
              </p>
            </div>
            <ChartCanvas type="bar" data={chart8Data} options={chart8Options} height={260} />
          </div>

          {/* Chart 9: Investigation Payload Scope */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  9. Investigation Payload & Artifact Scope
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/10 text-indigo-400 border border-indigo-500/20">
                  Doughnut
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Payload distribution from Flash questions (&lt;2KB) to extensive architectural logs (25KB+).
              </p>
            </div>
            <ChartCanvas type="doughnut" data={chart9Data} options={chart9Options} height={260} />
          </div>

          {/* Chart 10: Technical Intensity (Avg Turns per Domain) */}
          <div className="p-5 rounded-2xl bg-slate-900/50 border border-white/[0.08] shadow-xl flex flex-col justify-between">
            <div>
              <div className="flex items-center justify-between mb-1">
                <h4 className="text-sm font-bold text-white font-heading">
                  10. Technical Intensity (Average Turns per Dialogue)
                </h4>
                <span className="px-2 py-0.5 rounded text-[10px] font-mono bg-violet-500/10 text-violet-400 border border-violet-500/20">
                  Horizontal Bar
                </span>
              </div>
              <p className="text-[11px] text-slate-400 mb-3">
                Average iterations per investigation across domains (Web Frameworks & DB lead at 4.6 & 4.4).
              </p>
            </div>
            <ChartCanvas type="bar" data={chart10Data} options={chart10Options} height={260} />
          </div>

        </div>
      </div>

      {/* Interactive Domain Explorer & Conversation Highlights */}
      <div className="p-6 sm:p-8 rounded-3xl bg-slate-900/50 border border-white/[0.08] shadow-2xl space-y-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h3 className="text-lg font-bold text-white font-heading">
              Domain Showcase & Conversation Explorer
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              Inspect real sample conversations, dialogue depth, payload size, and direct ChatGPT links for each domain.
            </p>
          </div>

          {/* Search Filter */}
          <div className="relative w-full sm:w-72">
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Filter sample dialogues..."
              className="w-full bg-slate-950/80 border border-white/[0.1] rounded-xl px-3.5 py-2 pl-9 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-cyan-500 transition"
            />
            <div className="absolute left-3 top-2.5">
              <Icons.Search />
            </div>
          </div>
        </div>

        {/* Domain Selection Tabs */}
        <div className="flex flex-wrap gap-2 pt-2 border-t border-white/[0.06]">
          {domainDistribution.map(dom => (
            <button
              key={dom.category}
              onClick={() => setSelectedDomain(dom.category)}
              className={`px-3 py-1.5 rounded-xl text-xs font-medium transition-all flex items-center space-x-2 ${
                selectedDomain === dom.category
                  ? 'bg-white/[0.12] text-white border border-white/[0.2] shadow-md'
                  : 'bg-slate-950/60 text-slate-400 border border-white/[0.04] hover:text-slate-200 hover:bg-white/[0.04]'
              }`}
            >
              <span
                className="w-2.5 h-2.5 rounded-full"
                style={{ backgroundColor: dom.color }}
              ></span>
              <span>{dom.category}</span>
              <span className="font-mono text-[10px] text-slate-400">
                ({dom.total.toLocaleString()})
              </span>
            </button>
          ))}
        </div>

        {/* Conversation Cards Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredShowcase.length === 0 ? (
            <div className="col-span-full py-12 text-center text-xs text-slate-500 font-mono">
              No conversations matched the filter criteria in {selectedDomain}.
            </div>
          ) : (
            filteredShowcase.map(conv => (
              <div
                key={conv.id}
                className="p-4 rounded-2xl bg-slate-950/70 border border-white/[0.06] hover:border-white/[0.14] transition-all flex flex-col justify-between space-y-3 group"
              >
                <div>
                  <div className="flex items-start justify-between gap-2">
                    <h5 className="text-xs font-bold text-white tracking-tight group-hover:text-cyan-400 transition-colors line-clamp-2">
                      {conv.title || 'Untitled Diagnostic'}
                    </h5>
                    {conv.url && (
                      <a
                        href={conv.url}
                        target="_blank"
                        rel="noreferrer"
                        className="text-slate-400 hover:text-cyan-400 flex-shrink-0 p-1"
                        title="Open in ChatGPT"
                      >
                        <Icons.ExternalLink />
                      </a>
                    )}
                  </div>

                  {conv.summary && (
                    <p className="text-[11px] text-slate-400 mt-2 line-clamp-2 leading-relaxed">
                      {conv.summary}
                    </p>
                  )}
                </div>

                <div className="space-y-2 pt-2 border-t border-white/[0.04]">
                  {/* Badges: Turns & Size */}
                  <div className="flex items-center justify-between text-[10px] font-mono text-slate-400">
                    <span className="px-2 py-0.5 rounded bg-blue-500/10 text-blue-400 border border-blue-500/20">
                      {conv.turns} {conv.turns === 1 ? 'Turn' : 'Turns'}
                    </span>
                    <span className="px-2 py-0.5 rounded bg-purple-500/10 text-purple-400 border border-purple-500/20">
                      {conv.sizeKB} KB Payload
                    </span>
                  </div>

                  {/* Tags */}
                  {conv.tags && conv.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                      {conv.tags.slice(0, 3).map(tag => (
                        <span
                          key={tag}
                          className="px-1.5 py-0.2 rounded text-[9px] font-mono bg-white/[0.04] text-slate-300 border border-white/[0.06]"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))
          )}
        </div>
      </div>

    </div>
  );
}

// Render the application into #root
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);


// =========================================================================
// FLOATING 1-CLICK VERSION SWITCHER BAR (v1 to v5)
// =========================================================================
function VersionSwitcherBar({ activeVersion, onSelectVersion }) {
  const versions = [
    { id: 'v1', label: 'V1: Dock Console', subtitle: 'Matte Charcoal & Vertical Rail Dock' },
    { id: 'v2', label: 'V2: Bento Grid', subtitle: 'Raycast & Linear Frosted Glass Widgets' },
    { id: 'v4', label: 'V4: Swiss Editorial', subtitle: 'ReadCV Monochromatic & Sticky Index' },
  ];

  return (
    <nav aria-label="Version Switcher" className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 floating-version-bar px-3 py-2 rounded-2xl flex items-center gap-1.5 sm:gap-2 shadow-2xl border border-white/[0.15]">
      <div className="hidden sm:flex items-center gap-1.5 px-2 text-[10px] font-mono font-bold text-cyan-400 uppercase tracking-wider border-r border-white/[0.1] shrink-0">
        <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse"></span>
        <span>Designs:</span>
      </div>
      <div className="flex items-center gap-1 overflow-x-auto no-scrollbar">
        {versions.map((v) => {
          const isActive = activeVersion === v.id;
          return (
            <button
              key={v.id}
              onClick={() => onSelectVersion(v.id)}
              title={v.subtitle}
              className={
                'px-2.5 sm:px-3 py-1.5 rounded-xl text-xs font-mono font-bold transition duration-200 flex items-center gap-1.5 whitespace-nowrap ' +
                (isActive
                  ? 'bg-cyan-500 text-black shadow-[0_0_15px_rgba(56,189,248,0.5)] scale-105'
                  : 'text-slate-300 hover:text-white hover:bg-white/[0.08]')
              }
            >
              <span>{v.label}</span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}



// =========================================================================
// VERSION 1: CURRENT DOCK CONSOLE (Figma 1287502706882772309 Recreation)
// =========================================================================
function LayoutV1({
  skillsData,
  jobsData,
  statsData,
  rawSkillsMd,
  rawPositionsMd,
  isAdmin,
  activeTab,
  setActiveTab,
  navItems,
  mobileNavItems,
  onExploreJobs,
  onSelectJob,
  onSelectMetric,
  handleDownloadDossier,
  loading
}) {
  return (
    <div className="w-full flex-1 flex flex-col lg:flex-row items-stretch gap-3 lg:gap-4 xl:gap-5 animate-fade-in lg:h-[calc(100vh-5rem)]">
      
      {/* MOBILE TOP BAR (< lg screens) */}
      <div className="lg:hidden flex flex-col gap-2.5 p-3 rounded-2xl bg-[#151821] border border-white/[0.08] shadow-card">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-cyan-400 to-sky-600 flex items-center justify-center font-extrabold text-black font-heading text-xs shadow-[0_0_12px_rgba(56,189,248,0.4)]">
              XV
            </div>
            <div>
              <div className="text-sm font-bold text-white font-heading leading-none">
                Xavier Villarroel
              </div>
              <div className="text-[11px] text-cyan-400 font-mono mt-0.5">
                Distributed Systems Architect
              </div>
            </div>
          </div>

          <button
            onClick={handleDownloadDossier}
            className="px-2.5 py-1.5 rounded-lg bg-slate-900 border border-cyan-500/40 text-cyan-400 text-xs font-mono flex items-center gap-1.5"
          >
            <Icons.CloudDownload />
            <span>.MD</span>
          </button>
        </div>

        {/* Mobile Horizontal Sticky Tabs Bar */}
        <div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar py-1">
          {mobileNavItems.map((tab) => {
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={
                  'px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition duration-200 ' +
                  (isActive
                    ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/50 shadow-sm'
                    : 'text-slate-400 hover:text-white bg-slate-900/60 border border-white/[0.05]')
                }
              >
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* PANEL 1: SLIM ICON NAVIGATION DOCK */}
      <aside className="figma-dock rounded-2xl py-6 px-2.5 hidden lg:flex flex-col items-center justify-between shadow-card w-16 xl:w-20 shrink-0 h-full">
        <div className="flex items-center justify-center mb-6">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-cyan-400 to-sky-600 flex items-center justify-center font-extrabold text-black font-heading text-sm shadow-[0_0_15px_rgba(56,189,248,0.4)]">
            XV
          </div>
        </div>

        <nav className="flex flex-col items-center gap-3">
          {navItems.map((item) => {
            const IconComponent = item.icon;
            const isActive = activeTab === item.id;
            return (
              <button
                key={item.id}
                onClick={() => setActiveTab(item.id)}
                title={item.label}
                className={'figma-dock-btn ' + (isActive ? 'active' : '')}
              >
                <IconComponent />
              </button>
            );
          })}
        </nav>

        <div className="flex items-center justify-center mt-6">
          <button
            onClick={handleDownloadDossier}
            title="Download Executive Dossier (Markdown)"
            className="figma-dock-btn text-cyan-400 hover:text-white"
          >
            <Icons.CloudDownload />
          </button>
        </div>
      </aside>

      {/* PANEL 2: PORTRAIT & IDENTITY CARD */}
      <div className="hidden lg:flex flex-col shrink-0 w-[340px] xl:w-[380px] 2xl:w-[410px] h-full">
        <PortraitCard
          skillsData={skillsData}
          isAdmin={isAdmin}
          onExploreJobs={onExploreJobs}
        />
      </div>

      {/* PANEL 3: INTERACTIVE CONTENT CARD */}
      <main className="figma-card flex-1 min-w-0 flex flex-col overflow-hidden shadow-card h-full">
        <div className="px-5 sm:px-8 py-4 sm:py-5 border-b border-white/[0.07] flex flex-col md:flex-row md:items-center justify-between gap-3 bg-[#151821]/90 backdrop-blur-md shrink-0">
          <div>
            <div className="figma-subtitle uppercase tracking-widest font-mono text-xs">
              // {activeTab}
            </div>
            <h1 className="text-xl sm:text-2xl xl:text-3xl font-extrabold text-white font-heading tracking-tight capitalize mt-0.5">
              {activeTab === 'profile' && 'Candidate Profile & Dossier Identity'}
              {activeTab === 'overview' && 'Executive Overview'}
              {activeTab === 'experience' && 'Work History & Education'}
              {activeTab === 'projects' && 'Flagship Production Systems'}
              {activeTab === 'skills' && 'Skills Matrix & Enterprise Systems'}
              {activeTab === 'jobs' && '184 ClickHouse Opportunities'}
              {activeTab === 'analytics' && 'Conversation Telemetry & Analytics'}
              {activeTab === 'docs' && 'Executive Markdown Dossier'}
            </h1>
          </div>

          <div className="hidden md:flex items-center gap-1.5 overflow-x-auto no-scrollbar">
            {navItems.map((tab) => {
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={
                    'px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition duration-200 ' +
                    (isActive
                      ? 'bg-cyan-500/15 text-cyan-400 border border-cyan-500/40 shadow-sm'
                      : 'text-slate-400 hover:text-white hover:bg-white/[0.04]')
                  }
                >
                  {tab.label}
                </button>
              );
            })}
          </div>
        </div>

        <div className="p-4 sm:p-6 lg:p-8 flex-1 overflow-y-auto">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-28 space-y-4">
              <div className="w-10 h-10 border-2 border-slate-700 border-t-cyan-400 rounded-full animate-spin"></div>
              <p className="text-xs text-slate-400 font-mono tracking-wider uppercase">
                {isAdmin ? 'Loading Dossier Intelligence & Job Matches...' : 'Loading Executive Profile & Systems Portfolio...'}
              </p>
            </div>
          ) : (
            <>
              {activeTab === 'profile' && (
                <div className="lg:hidden">
                  <PortraitCard
                    skillsData={skillsData}
                    isAdmin={isAdmin}
                    onExploreJobs={onExploreJobs}
                    isMobile={true}
                  />
                </div>
              )}
              {activeTab === 'overview' && (
                <OverviewView
                  data={skillsData}
                  onSelectMetric={onSelectMetric}
                />
              )}
              {activeTab === 'experience' && (
                <ExperienceView data={skillsData} />
              )}
              {activeTab === 'projects' && (
                <ProjectsView data={skillsData} />
              )}
              {activeTab === 'skills' && (
                <SkillsView data={skillsData} />
              )}
              {isAdmin && activeTab === 'jobs' && (
                <ClickHouseJobsView
                  jobs={jobsData}
                  onSelectJob={onSelectJob}
                />
              )}
              {isAdmin && activeTab === 'analytics' && (
                <StatisticsView data={statsData} />
              )}
              {activeTab === 'docs' && (
                <RawDocsView
                  skillsMd={rawSkillsMd}
                  positionsMd={rawPositionsMd}
                  isAdmin={isAdmin}
                />
              )}
            </>
          )}
        </div>
      </main>
    </div>
  );
}



// =========================================================================
// =========================================================================
// VERSION 2: INTERACTIVE BENTO GRID & GLASSMORPHIC WORKSPACE (Raycast / Linear Style)
// =========================================================================
function LayoutV2({
  skillsData,
  jobsData,
  statsData,
  rawSkillsMd,
  rawPositionsMd,
  isAdmin,
  activeTab,
  setActiveTab,
  navItems,
  onExploreJobs,
  onSelectJob,
  onSelectMetric,
  handleDownloadDossier,
  loading
}) {
  const [bentoFilter, setBentoFilter] = useState('all');
  const [selectedBentoProject, setSelectedBentoProject] = useState(null);

  const projects = skillsData?.flagshipProjects || [];
  const metrics = skillsData?.metricsAndImpact || [];
  const career = skillsData?.workExperience || [];
  const products = skillsData?.enterpriseProductsCatalog || [];

  return (
    <div className="w-full max-w-7xl mx-auto space-y-6 pb-28 animate-fade-in font-sans">
      
      {/* Top Glassmorphic Navigation Header */}
      <header className="p-4 sm:p-5 rounded-2xl bento-grid-item flex flex-col md:flex-row items-center justify-between gap-4">
        <div className="flex items-center space-x-3.5">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 via-purple-500 to-cyan-400 flex items-center justify-center font-extrabold text-black font-heading text-sm shadow-[0_0_20px_rgba(99,102,241,0.5)]">
            XV
          </div>
          <div>
            <div className="text-base font-bold text-white font-heading tracking-tight flex items-center gap-2">
              <span>Xavier Villarroel</span>
              <span className="px-2 py-0.5 rounded-full text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                V2 BENTO WORKSPACE
              </span>
            </div>
            <div className="text-xs text-indigo-300 font-mono">
              AI Automation Engineer • L3 Customer Support Architect • AWS Solutions Architect
            </div>
          </div>
        </div>

        {/* Quick Action Buttons */}
        <div className="flex items-center gap-2">
          {isAdmin && (
            <button
              onClick={onExploreJobs}
              className="px-3.5 py-1.5 rounded-xl text-xs font-mono font-bold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 hover:bg-cyan-500/30 transition flex items-center gap-1.5"
            >
              <span>184 ClickHouse Jobs</span>
              <span className="px-1.5 py-0.2 rounded bg-cyan-400/20 text-[10px]">Active</span>
            </button>
          )}
          <button
            onClick={handleDownloadDossier}
            className="px-3.5 py-1.5 rounded-xl text-xs font-mono font-bold bg-white/[0.08] hover:bg-white/[0.15] text-white border border-white/[0.1] transition flex items-center gap-1.5"
          >
            <span>Download MD Dossier</span>
          </button>
          <a
            href="mailto:xavier.villarroel@outlook.com?subject=Senior%20Engineering%20Opportunity"
            className="px-4 py-1.5 rounded-xl text-xs font-mono font-bold bg-gradient-to-r from-indigo-500 to-cyan-500 hover:from-indigo-400 hover:to-cyan-400 text-white shadow-lg transition"
          >
            Contact
          </a>
        </div>
      </header>

      {/* Hero Bento Grid (12 Columns) */}
      <div className="grid grid-cols-1 md:grid-cols-12 gap-5">
        
        {/* Card 1: Executive Pitch & Bio (Span 8) */}
        <div className="md:col-span-8 p-6 sm:p-8 rounded-3xl bento-grid-item relative overflow-hidden flex flex-col justify-between space-y-6">
          <div className="space-y-4">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-950/60 border border-indigo-800/50 text-indigo-300 text-xs font-mono">
              <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
              <span>AVAILABLE FOR HIGH-IMPACT AMER / GLOBAL ROLES</span>
            </div>
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-extrabold text-white font-heading tracking-tight leading-snug">
              Architecting <span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-300 via-cyan-300 to-purple-300">Agentic AI Workflows, Remote MCP Fleets & Forensic L3 Incident Diagnostics</span>
            </h1>
            <p className="text-sm text-slate-300 leading-relaxed font-normal">
              {skillsData?.executiveSummary?.pitch || 'Over 8 years of uninterrupted high-rigor remote execution in ESW Capital / Trilogy portfolios.'}
            </p>
          </div>

          {/* Core Feature Badges */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 pt-2">
            <div className="p-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08]">
              <div className="text-[11px] font-mono text-indigo-400 font-bold">MCP Fleet</div>
              <div className="text-[10px] text-slate-400">10+ Remote SSE Servers</div>
            </div>
            <div className="p-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08]">
              <div className="text-[11px] font-mono text-indigo-400 font-bold">Forensic RCAs</div>
              <div className="text-[10px] text-slate-400">390+ Documented</div>
            </div>
            <div className="p-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08]">
              <div className="text-[11px] font-mono text-indigo-400 font-bold">Mission-Critical</div>
              <div className="text-[10px] text-slate-400">160+ Sev-1 Outages</div>
            </div>
            <div className="p-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08]">
              <div className="text-[11px] font-mono text-indigo-400 font-bold">BrainLift DOK</div>
              <div className="text-[10px] text-slate-400">Context Engineering</div>
            </div>
          </div>
        </div>

        {/* Card 2: Interactive Hardware Lab & Profile Aura (Span 4) */}
        <div className="md:col-span-4 p-6 rounded-3xl bento-grid-item flex flex-col items-center justify-between text-center space-y-4">
          <div className="relative">
            <div className="w-36 h-36 sm:w-40 sm:h-40 rounded-full overflow-hidden p-1 bg-gradient-to-tr from-indigo-500 via-purple-500 to-cyan-400 shadow-[0_0_35px_rgba(99,102,241,0.35)]">
              <img
                src="portrait.jpg?v=20260912_studio_perfect"
                alt="Xavier Villarroel"
                className="w-full h-full object-cover rounded-full"
              />
            </div>
          </div>

          <div className="w-full space-y-2">
            <div className="text-sm font-bold text-white font-heading">
              Dedicated Bare-Metal Diagnostics
            </div>
            <div className="p-3 rounded-2xl bg-black/40 border border-white/[0.08] text-left text-xs font-mono space-y-1 text-slate-300">
              <div className="flex justify-between">
                <span className="text-indigo-400">RAM Pool:</span>
                <span className="text-white font-bold">192 GB+ Multi-Node</span>
              </div>
              <div className="flex justify-between">
                <span className="text-indigo-400">NAS Storage:</span>
                <span className="text-white font-bold">64 TB Diagnostics</span>
              </div>
              <div className="flex justify-between">
                <span className="text-indigo-400">Apple Silicon:</span>
                <span className="text-white font-bold">Mac Studio M4 Pro</span>
              </div>
              <div className="flex justify-between">
                <span className="text-indigo-400">Linux Rig:</span>
                <span className="text-white font-bold">Ubuntu Kernel Host</span>
              </div>
            </div>
          </div>
        </div>

        {/* Card 3: Metrics & Business Impact Carousel (Span 12) */}
        <div className="md:col-span-12 space-y-3">
          <div className="flex items-center justify-between px-1">
            <h2 className="text-sm font-mono font-bold uppercase tracking-wider text-slate-400 flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-cyan-400"></span>
              <span>Quantified Impact & Verified Telemetry (Click to Inspect Breakdown)</span>
            </h2>
            <span className="text-xs text-slate-500 font-mono">Interactive Cards</span>
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
            {metrics.slice(0, 6).map((m) => (
              <div
                key={m.id}
                onClick={() => onSelectMetric(m)}
                className="p-4 rounded-2xl bento-grid-item cursor-pointer group hover:scale-[1.02] transition"
              >
                <div className="text-2xl sm:text-3xl font-extrabold font-heading text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 to-indigo-300 group-hover:from-white group-hover:to-cyan-200">
                  {m.value}
                </div>
                <div className="text-xs font-bold text-white mt-1 group-hover:text-cyan-400 transition">
                  {m.label}
                </div>
                <div className="text-[10px] text-slate-400 line-clamp-2 mt-1 leading-tight">
                  {m.detail}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Card 4: Flagship Architectural Implementations (Span 7) */}
        <div className="md:col-span-7 p-6 rounded-3xl bento-grid-item space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-base font-bold text-white font-heading flex items-center gap-2">
              <span>Flagship Architectural Systems</span>
              <span className="px-2 py-0.5 rounded-full text-[10px] font-mono bg-purple-500/20 text-purple-300">
                {projects.length} Systems
              </span>
            </h2>
          </div>

          <div className="space-y-3">
            {projects.map((proj) => {
              const isSelected = selectedBentoProject?.id === proj.id;
              return (
                <div
                  key={proj.id}
                  onClick={() => setSelectedBentoProject(isSelected ? null : proj)}
                  className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.08] hover:border-indigo-500/40 transition cursor-pointer"
                >
                  <div className="flex items-start justify-between">
                    <div>
                      <div className="text-sm font-bold text-white font-heading">
                        {proj.name}
                      </div>
                      <div className="text-[11px] text-indigo-400 font-mono">
                        {proj.category}
                      </div>
                    </div>
                    <span className="text-xs text-slate-500 font-mono">
                      {isSelected ? '▲ Collapse' : '▼ Details'}
                    </span>
                  </div>

                  <p className="text-xs text-slate-300 mt-2 line-clamp-2">
                    {proj.description}
                  </p>

                  {isSelected && (
                    <div className="mt-3 pt-3 border-t border-white/[0.08] space-y-2 animate-fade-in text-xs">
                      <div className="text-slate-400 font-semibold">Key Capabilities:</div>
                      <ul className="list-disc list-inside text-slate-300 space-y-1 text-[11px]">
                        {proj.keyCapabilities?.map((c, i) => (
                          <li key={i}>{c}</li>
                        ))}
                      </ul>
                      <div className="flex flex-wrap gap-1.5 pt-2">
                        {proj.technologies?.map((tech, idx) => (
                          <span key={idx} className="px-2 py-0.5 rounded-md bg-indigo-950/60 text-indigo-300 text-[10px] font-mono border border-indigo-800/40">
                            {tech}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Card 5: Enterprise Battle-Tested Products Catalog (Span 5) */}
        <div className="md:col-span-5 p-6 rounded-3xl bento-grid-item space-y-4">
          <h2 className="text-base font-bold text-white font-heading flex items-center gap-2">
            <span>Enterprise Products Ecosystem</span>
            <span className="px-2 py-0.5 rounded-full text-[10px] font-mono bg-cyan-500/20 text-cyan-300">
              1,900+ Interventions
            </span>
          </h2>
          <p className="text-xs text-slate-400">
            Documented production incidents across enterprise communications, database clusters, and ticketing workflows:
          </p>

          <div className="space-y-2.5">
            {products.slice(0, 5).map((prod, idx) => (
              <div key={idx} className="p-3 rounded-xl bg-white/[0.03] border border-white/[0.08] flex items-center justify-between">
                <div>
                  <div className="text-xs font-bold text-white font-heading">
                    {prod.product}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5 line-clamp-1">
                    {prod.expertiseAreas?.join(' • ')}
                  </div>
                </div>
                <div className="px-2.5 py-1 rounded-lg bg-indigo-500/20 text-indigo-300 text-[11px] font-mono font-bold shrink-0 ml-2">
                  {prod.documentedCases}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Card 6: Career Trajectory (Span 12) */}
        <div className="md:col-span-12 p-6 rounded-3xl bento-grid-item space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-base font-bold text-white font-heading flex items-center gap-2">
              <span>Tenure & Promotion Trajectory (ESW Capital / Trilogy)</span>
              <span className="text-xs font-mono text-emerald-400">8+ Years Uninterrupted Remote</span>
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {career.map((role, idx) => (
              <div key={idx} className="p-4 rounded-2xl bg-white/[0.03] border border-white/[0.08] space-y-2">
                <div className="text-xs font-mono text-cyan-400 font-bold">{role.period}</div>
                <div className="text-sm font-bold text-white font-heading">{role.role}</div>
                <div className="text-xs text-slate-400">{role.company} • {role.duration}</div>
                <ul className="text-[11px] text-slate-300 list-disc list-inside space-y-1 pt-1">
                  {role.highlights?.slice(0, 2).map((h, i) => (
                    <li key={i} className="line-clamp-2">{h}</li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

      </div>
    </div>
  );
}



// =========================================================================
// VERSION 4: SWISS EDITORIAL & MONOCHROMATIC DOSSIER (ReadCV / Vercel Press)
// =========================================================================
function LayoutV4({
  skillsData,
  jobsData,
  statsData,
  rawSkillsMd,
  rawPositionsMd,
  isAdmin,
  onExploreJobs,
  onSelectJob,
  onSelectMetric,
  handleDownloadDossier
}) {
  const [activeChapter, setActiveChapter] = useState('01');

  const chapters = [
    { id: '01', title: '01. Executive Overview', target: '#chapter-01' },
    { id: '02', title: '02. Quantified Track Record', target: '#chapter-02' },
    { id: '03', title: '03. Flagship Architectures', target: '#chapter-03' },
    { id: '04', title: '04. High-Rigor Trajectory', target: '#chapter-04' },
    { id: '05', title: '05. Enterprise Ecosystem', target: '#chapter-05' },
    { id: '06', title: '06. Bare-Metal Infrastructure', target: '#chapter-06' },
  ];

  const projects = skillsData?.flagshipProjects || [];
  const metrics = skillsData?.metricsAndImpact || [];
  const career = skillsData?.workExperience || [];
  const products = skillsData?.enterpriseProductsCatalog || [];

  return (
    <div className="w-full max-w-6xl mx-auto pb-32 animate-fade-in font-sans text-neutral-200">
      
      {/* Two-Column Swiss Grid Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 pt-6">
        
        {/* Left Sticky Column (4 Cols): Executive ID & Chapter Index */}
        <aside className="lg:col-span-4 space-y-8 lg:sticky lg:top-8 self-start">
          
          {/* Identity Block */}
          <div className="space-y-4 border-b border-neutral-800 pb-6">
            <div className="w-28 h-28 rounded-2xl overflow-hidden border border-neutral-700">
              <img
                src="portrait.jpg?v=20260912_studio_perfect"
                alt="Xavier Villarroel"
                className="w-full h-full object-cover grayscale contrast-125"
              />
            </div>
            <div>
              <div className="text-[11px] font-mono tracking-widest uppercase text-neutral-400">
                Curriculum Vitae • Technical Dossier
              </div>
              <h1 className="text-2xl font-bold text-white font-heading tracking-tight mt-1">
                Xavier Villarroel
              </h1>
              <p className="text-xs text-neutral-400 font-mono mt-0.5">
                AI Automation Engineer & L3 Architect
              </p>
            </div>
          </div>

          {/* Contact Details */}
          <div className="space-y-2 text-xs font-mono text-neutral-400 border-b border-neutral-800 pb-6">
            <div className="flex items-center gap-2">
              <span className="text-neutral-500">LOC:</span>
              <span className="text-neutral-200">Santiago, Chile (100% Remote)</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-neutral-500">MAIL:</span>
              <a href="mailto:xavier.villarroel@outlook.com" className="text-white hover:underline">
                xavier.villarroel@outlook.com
              </a>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-neutral-500">LANG:</span>
              <span className="text-neutral-200">English (C2 Bilingual) • Spanish</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-neutral-500">CERT:</span>
              <span className="text-neutral-200">AWS Certified Solutions Architect</span>
            </div>
          </div>

          {/* Sticky Chapter TOC */}
          <nav className="space-y-1 text-xs font-mono">
            <div className="text-[10px] uppercase tracking-widest text-neutral-500 mb-2 font-bold">
              Index Chapters
            </div>
            {chapters.map((ch) => (
              <a
                key={ch.id}
                href={ch.target}
                onClick={() => setActiveChapter(ch.id)}
                className={
                  'block py-1.5 px-2 rounded-md transition ' +
                  (activeChapter === ch.id
                    ? 'bg-neutral-800 text-white font-bold pl-3 border-l-2 border-white'
                    : 'text-neutral-400 hover:text-white hover:bg-neutral-900')
                }
              >
                {ch.title}
              </a>
            ))}
          </nav>

          {/* Download & Actions */}
          <div className="pt-2 space-y-2">
            <button
              onClick={handleDownloadDossier}
              className="w-full py-2.5 px-4 rounded-xl bg-white text-black font-mono font-bold text-xs hover:bg-neutral-200 transition"
            >
              Download Markdown Dossier ↓
            </button>
            {isAdmin && (
              <button
                onClick={onExploreJobs}
                className="w-full py-2 px-4 rounded-xl border border-neutral-700 hover:border-neutral-500 text-neutral-300 font-mono text-xs transition"
              >
                Browse 184 Matched Jobs →
              </button>
            )}
          </div>
        </aside>

        {/* Right Fluid Column (8 Cols): Narrative Technical Dossier */}
        <main className="lg:col-span-8 space-y-16">
          
          {/* Chapter 01: Executive Overview */}
          <section id="chapter-01" className="space-y-6 pt-2">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 01 — Executive Overview
            </div>
            <blockquote className="text-xl sm:text-2xl font-light text-white leading-relaxed border-l-2 border-neutral-700 pl-6 italic">
              "Over 8 years of uninterrupted high-rigor execution operating inside the top percentile of global remote software organizations."
            </blockquote>
            <p className="text-sm text-neutral-300 leading-relaxed font-normal">
              {skillsData?.executiveSummary?.pitch || 'Elite AI Automation Engineer, Level 3 Support Architect, and AWS Solutions Architect with over 8 continuous years operating in top-tier performance models.'}
            </p>

            {/* Core Pillars */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-4">
              {skillsData?.executiveSummary?.corePillars?.map((p, i) => (
                <div key={i} className="p-4 rounded-xl editorial-card space-y-2">
                  <div className="text-sm font-bold text-white font-heading">{p.title}</div>
                  <div className="text-xs text-neutral-400 leading-relaxed">{p.description}</div>
                </div>
              ))}
            </div>
          </section>

          {/* Chapter 02: Quantified Track Record */}
          <section id="chapter-02" className="space-y-6 border-t border-neutral-800 pt-10">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 02 — Quantified Track Record
            </div>
            
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-6">
              {metrics.map((m) => (
                <div key={m.id} className="space-y-1 border-b border-neutral-800 pb-4">
                  <div className="text-3xl font-extrabold text-white font-heading">{m.value}</div>
                  <div className="text-xs font-bold text-neutral-200">{m.label}</div>
                  <div className="text-[11px] text-neutral-400 leading-snug">{m.detail}</div>
                </div>
              ))}
            </div>
          </section>

          {/* Chapter 03: Flagship Architectures */}
          <section id="chapter-03" className="space-y-6 border-t border-neutral-800 pt-10">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 03 — Flagship Architectures
            </div>

            <div className="space-y-6">
              {projects.map((proj) => (
                <div key={proj.id} className="p-6 rounded-xl editorial-card space-y-3">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1">
                    <h3 className="text-base font-bold text-white font-heading">{proj.name}</h3>
                    <span className="text-xs font-mono text-neutral-400">{proj.category}</span>
                  </div>
                  <p className="text-xs sm:text-sm text-neutral-300 leading-relaxed">
                    {proj.description}
                  </p>
                  <ul className="text-xs text-neutral-400 list-disc list-inside space-y-1 pt-1">
                    {proj.keyCapabilities?.map((c, i) => (
                      <li key={i}>{c}</li>
                    ))}
                  </ul>
                  <div className="flex flex-wrap gap-1.5 pt-2">
                    {proj.technologies?.map((tech, i) => (
                      <span key={i} className="px-2 py-0.5 rounded bg-neutral-800 text-neutral-300 text-[10px] font-mono">
                        {tech}
                      </span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </section>

          {/* Chapter 04: High-Rigor Trajectory */}
          <section id="chapter-04" className="space-y-6 border-t border-neutral-800 pt-10">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 04 — Career Trajectory
            </div>

            <div className="space-y-8 border-l border-neutral-800 pl-6 relative">
              {career.map((c, i) => (
                <div key={i} className="space-y-2 relative">
                  <span className="absolute -left-[31px] top-1.5 w-2.5 h-2.5 rounded-full bg-neutral-400 border-2 border-black"></span>
                  <div className="text-xs font-mono text-neutral-400">{c.period} • {c.duration}</div>
                  <h3 className="text-base font-bold text-white font-heading">{c.role}</h3>
                  <div className="text-xs text-neutral-300">{c.company}</div>
                  <ul className="text-xs text-neutral-400 list-disc list-inside space-y-1 pt-2">
                    {c.highlights?.map((h, idx) => (
                      <li key={idx}>{h}</li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </section>

          {/* Chapter 05: Enterprise Products Ecosystem */}
          <section id="chapter-05" className="space-y-6 border-t border-neutral-800 pt-10">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 05 — Enterprise Products Ecosystem
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {products.map((p, idx) => (
                <div key={idx} className="p-4 rounded-xl editorial-card space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-bold text-white">{p.product}</span>
                    <span className="text-xs font-mono text-neutral-400">{p.documentedCases}</span>
                  </div>
                  <div className="text-xs text-neutral-400">
                    {p.expertiseAreas?.join(' • ')}
                  </div>
                </div>
              ))}
            </div>
          </section>

          {/* Chapter 06: Bare-Metal Diagnostic Lab */}
          <section id="chapter-06" className="space-y-4 border-t border-neutral-800 pt-10">
            <div className="text-xs font-mono uppercase tracking-widest text-neutral-500">
              Chapter 06 — Bare-Metal Hardware Fleet
            </div>
            <p className="text-xs sm:text-sm text-neutral-300 leading-relaxed">
              To eliminate environment discrepancies and diagnose multi-OS enterprise crashes, a dedicated 10+ node lab operates with 192GB+ RAM, 64TB Synology NAS, Ubuntu headless servers, Windows 11 high-throughput rigs, and Apple Silicon Mac Studio M4 Pro.
            </p>
          </section>

        </main>

      </div>

    </div>
  );
}



// =========================================================================
// MASTER ROOT APP COMPONENT (DUAL MODE + 10 UI PARADIGMS)
// =========================================================================
function detectInitialVersion() {
  const allowed = ['v1', 'v2', 'v4'];
  const path = window.location.pathname.toLowerCase();
  const match = path.match(/\/(v[1-9]|v10)/);
  if (match && allowed.includes(match[1])) return match[1];
  const params = new URLSearchParams(window.location.search);
  const vParam = params.get('v');
  if (vParam && allowed.includes('v' + vParam)) return 'v' + vParam;
  const hash = window.location.hash.toLowerCase();
  const hashMatch = hash.match(/(v[1-9]|v10)/);
  if (hashMatch && allowed.includes(hashMatch[1])) return hashMatch[1];
  return 'v1';
}

function App() {
  const [activeVersion, setActiveVersion] = useState(detectInitialVersion);

  // Detect if user is accessing /admin
  const isAdmin = useMemo(() => {
    return (
      window.location.pathname.includes('/admin') ||
      window.location.search.includes('admin=true') ||
      window.location.hash.includes('admin')
    );
  }, []);

  const [activeTab, setActiveTab] = useState('overview');
  
  // Data states
  const [skillsData, setSkillsData] = useState(null);
  const [jobsData, setJobsData] = useState([]);
  const [rawSkillsMd, setRawSkillsMd] = useState('');
  const [rawPositionsMd, setRawPositionsMd] = useState('');
  const [statsData, setStatsData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Selected modals
  const [selectedJob, setSelectedJob] = useState(null);
  const [selectedMetric, setSelectedMetric] = useState(null);

  useEffect(() => {
    async function loadAllData() {
      try {
        setLoading(true);
        const promises = [
          fetch('/api/skills/json').then(r => r.ok ? r.json() : null).catch(e => { console.error(e); return null; }),
          fetch('/api/skills').then(r => r.ok ? r.text() : '').catch(e => { console.error(e); return ''; }),
        ];
        if (isAdmin) {
          promises.push(fetch('/api/positions/json').then(r => r.ok ? r.json() : null).catch(e => { console.error(e); return null; }));
          promises.push(fetch('/api/positions').then(r => r.ok ? r.text() : '').catch(e => { console.error(e); return ''; }));
          promises.push(fetch('/api/statistics').then(r => r.ok ? r.json() : null).catch(e => { console.error(e); return null; }));
        }

        const results = await Promise.all(promises);
        setSkillsData(results[0]);
        setRawSkillsMd(results[1] || '');
        if (isAdmin) {
          setJobsData(results[2]?.jobs || []);
          setRawPositionsMd(results[3] || '');
          setStatsData(results[4] || null);
        }
      } catch (err) {
        console.error("Data load error:", err);
        setError("Failed to load intelligence backend data.");
      } finally {
        setLoading(false);
      }
    }
    loadAllData();
  }, [isAdmin]);

  // Dynamic document title based on view mode and version
  useEffect(() => {
    const vUpper = activeVersion.toUpperCase();
    if (isAdmin) {
      document.title = `Xavier Villarroel | Admin Suite (${vUpper}) - 184 ClickHouse Jobs`;
    } else {
      document.title = `Xavier Villarroel | Systems Architect & Distributed AI (${vUpper})`;
    }
  }, [isAdmin, activeVersion]);

  // Safety check: if non-admin tries to open jobs or analytics, redirect to overview
  useEffect(() => {
    if (!isAdmin && (activeTab === 'jobs' || activeTab === 'analytics')) {
      setActiveTab('overview');
    }
  }, [isAdmin, activeTab]);

  // Handler for Version Switching with URL Sync
  const handleSelectVersion = (versionId) => {
    setActiveVersion(versionId);
    try {
      const adminPrefix = isAdmin ? '/admin' : '';
      const newUrl = `/${versionId}${adminPrefix}`;
      window.history.pushState({ version: versionId }, '', newUrl);
    } catch (e) {
      // ignore
    }
  };

  // Metric carousel handlers
  const metricsList = skillsData && skillsData.metricsAndImpact ? skillsData.metricsAndImpact : [];
  const currentMetricIndex = selectedMetric ? metricsList.findIndex(m => m.label === selectedMetric.label) : -1;
  const handlePrevMetric = currentMetricIndex > 0 ? () => setSelectedMetric(metricsList[currentMetricIndex - 1]) : null;
  const handleNextMetric = currentMetricIndex >= 0 && currentMetricIndex < metricsList.length - 1 ? () => setSelectedMetric(metricsList[currentMetricIndex + 1]) : null;

  const handleDownloadDossier = () => {
    const blob = new Blob([rawSkillsMd || '# Xavier Villarroel - Skills Dossier'], { type: 'text/markdown;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'xavier_villarroel_dossier.md');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // Build navigation items based on Admin Mode vs Public Mode
  const navItems = useMemo(() => {
    const base = [
      { id: 'overview', label: 'Overview', icon: Icons.User },
      { id: 'experience', label: 'Experience', icon: Icons.Briefcase },
      { id: 'projects', label: 'Flagship Systems', icon: Icons.Rocket },
      { id: 'skills', label: 'Skills & Systems', icon: Icons.Cpu },
    ];
    if (isAdmin) {
      base.push(
        { id: 'jobs', label: '184 Jobs (' + (jobsData.length || 184) + ')', icon: Icons.Search },
        { id: 'analytics', label: 'Analytics', icon: Icons.Chart }
      );
    }
    base.push({ id: 'docs', label: 'Dossier MD', icon: Icons.Document });
    return base;
  }, [isAdmin, jobsData.length]);

  const mobileNavItems = useMemo(() => {
    return [
      { id: 'profile', label: 'Profile' },
      ...navItems
    ];
  }, [navItems]);

  return (
    <div className="w-full flex-1 flex flex-col min-h-screen relative pb-16">
      
      {/* 10 Distinct Layout Paradigms */}
      {activeVersion === 'v1' && (
        <LayoutV1
          skillsData={skillsData}
          jobsData={jobsData}
          statsData={statsData}
          rawSkillsMd={rawSkillsMd}
          rawPositionsMd={rawPositionsMd}
          isAdmin={isAdmin}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          navItems={navItems}
          mobileNavItems={mobileNavItems}
          onExploreJobs={() => setActiveTab('jobs')}
          onSelectJob={setSelectedJob}
          onSelectMetric={setSelectedMetric}
          handleDownloadDossier={handleDownloadDossier}
          loading={loading}
        />
      )}

      {activeVersion === 'v2' && (
        <LayoutV2
          skillsData={skillsData}
          jobsData={jobsData}
          statsData={statsData}
          rawSkillsMd={rawSkillsMd}
          rawPositionsMd={rawPositionsMd}
          isAdmin={isAdmin}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          navItems={navItems}
          onExploreJobs={() => setActiveTab('jobs')}
          onSelectJob={setSelectedJob}
          onSelectMetric={setSelectedMetric}
          handleDownloadDossier={handleDownloadDossier}
          loading={loading}
        />
      )}

      {activeVersion === 'v4' && (
        <LayoutV4
          skillsData={skillsData}
          jobsData={jobsData}
          statsData={statsData}
          rawSkillsMd={rawSkillsMd}
          rawPositionsMd={rawPositionsMd}
          isAdmin={isAdmin}
          onExploreJobs={() => setActiveTab('jobs')}
          onSelectJob={setSelectedJob}
          onSelectMetric={setSelectedMetric}
          handleDownloadDossier={handleDownloadDossier}
        />
      )}

      {/* Persistent Floating 1-Click Version Switcher */}
      <VersionSwitcherBar
        activeVersion={activeVersion}
        onSelectVersion={handleSelectVersion}
      />

      {/* Global Interactive Modals */}
      {selectedMetric && (
        <MetricModal
          metric={selectedMetric}
          onClose={() => setSelectedMetric(null)}
          onSelectPrev={handlePrevMetric}
          onSelectNext={handleNextMetric}
        />
      )}

      {selectedJob && (
        <JobDetailsModal
          job={selectedJob}
          onClose={() => setSelectedJob(null)}
        />
      )}

    </div>
  );
}

// Render React App
const rootElement = document.getElementById('root');
if (rootElement) {
  ReactDOM.render(<App />, rootElement);
}

