import "./index.css";

// Project interface matching our strategic portfolio
export interface Project {
  id: string;
  title: string;
  tagEN: string;
  tagES: string;
  roleEN: string;
  roleES: string;
  descriptionEN: string;
  descriptionES: string;
  image: string;
  categories: string[];
  isFeatured?: boolean;
  conceptEN: string;
  conceptES: string;
  processEN: string;
  processES: string;
  resultsEN: string;
  resultsES: string;
}

// Full projects array with case study specifics
export const PROJECTS: Project[] = [
  {
    id: "nagam-us",
    title: "NAGAM-US",
    tagEN: "Service Design",
    tagES: "Diseño de Servicios",
    roleEN: "Lead Service Designer",
    roleES: "Diseñadora de Servicios Principal",
    descriptionEN: "Redefining the digital ecosystem for high-stakes urban mobility. A deep dive into user journeys and service mapping for seamless infrastructure.",
    descriptionES: "Rediseñando el ecosistema digital para la movilidad urbana de alto impacto. Un análisis profundo de los viajes del usuario y mapeo de servicios para una infraestructura fluida.",
    image: "https://lh3.googleusercontent.com/aida-public/AB6AXuD5iB-lXeeU_DGkT-2rnGP8tH3f-KvdxUsHoAgr6xVJJAivMZvUyfokvN4bLcXI2HqXGwbOu1mIkwRuTeEnw2GiiCoblSvPAsRA1B9BvbydQUrTy_i_bzj-sh4cHJSi7Nl4mZpfOBtt6P7T2CDptTVpEQUUo5tdYoVkVAB3TaEaVhzyz09c2YPOqKmoye3CAsGVezt2xdQv8pCKi9nK4Y_JLtqdXMwZs7aMesDjKTDB3cYEC7HJCYp-C_DpRU4Aj7mk3YFYwYILcEzV",
    categories: ["Service Design", "Strategy", "Branding"],
    isFeatured: true,
    conceptEN: "Reimagining transit touchpoints as unified digital ecosystems, focusing on user fluidity and friction reduction.",
    conceptES: "Reimaginando los puntos de contacto de tránsito como ecosistemas digitales unificados, enfocándose en la fluidez del usuario.",
    processEN: "Created detailed service blue prints and journey maps for high-stakes urban transit, aligning strict infrastructure constraints with modern visual clarity and touchpoint orchestration.",
    processES: "Creado detailed mapas de servicio y planos de experiencia para tránsito urbano crítico, alineando limitaciones de infraestructura con claridad visual moderna y orquestación de puntos de contacto.",
    resultsEN: "Reduced average interface friction and wait-time perception by 40%, receiving visual accolades for corporate service strategy.",
    resultsES: "Reducción de fricción de interfaz promedio y percepción de tiempo de espera en 40%, recibiendo elogios visuales por estrategia de servicio corporativo."
  },
  {
    id: "levis-ai",
    title: "Levi's AI Background Shoot",
    tagEN: "AI / Branded Content",
    tagES: "IA / Contenido de Marca",
    roleEN: "AI Creative Technologist",
    roleES: "Tecnóloga Creativa de IA",
    descriptionEN: "A high-fashion editorial shot of denim products being reimagined through AI-generated backgrounds. The lighting is dramatic and studio-quality, emphasizing fabric texture against surreal landscapes.",
    descriptionES: "Una toma editorial de alta costura de productos denim reimaginados mediante fondos generados por IA. La iluminación es dramática y de calidad de estudio, destacando la textura del tejido frente a paisajes surrealistas.",
    image: "https://lh3.googleusercontent.com/aida-public/AB6AXuD-bUbR2BkDaA3Sot8WO707oAi0_4paFYjsgCNARg8xDrjNZvBb03y5MgLz9WvV-ohXKj01xR0IcrovXNoulKiriXyOCUHODAjBhQNY_vC8589Xi7l4wIOsn_UkbkD-c9XoAQD0rCU_o_Z939F7hoQwzY5yWiwzSOrT0POmRevdf8F3nkBk8iUCXgWdIjyfO5HNTC2yNPPiVcZEB4mci-JRx5PtfJKHDzh4cHu1uEKPv0ppD8x-Rj9rY0onmJ_FQyfig4pVw49071b-",
    categories: ["Branding", "Strategy", "AI"],
    conceptEN: "Blending heritage craftsmanship with the avant-garde using commercial generative AI workflows.",
    conceptES: "Fusionando herencia artesanal con la vanguardia utilizando flujos de trabajo de IA generativa comercial.",
    processEN: "Iteratively refined prompt weights and guidance scales, layering real-world studio fabric textures over surreal machine-generated environments in precision post-production masking.",
    processES: "Refinado de forma iterativa de pesos de prompts y escalas de guía, superponiendo texturas reales de estudio sobre entornos de máquina surrealistas en enmascaramiento de posproducción.",
    resultsEN: "Created a highly scalable editorial template reducing live background shooting budgets while maintaining authentic luxury fidelity.",
    resultsES: "Creado un modelo editorial altamente escalable que reduce presupuestos de tomas reales de fondos manteniendo una alta fidelidad y autenticidad de lujo."
  },
  {
    id: "shoe-campaign",
    title: "Shoe Campaign",
    tagEN: "Art Direction",
    tagES: "Dirección de Arte",
    roleEN: "Creative Director",
    roleES: "Directora Creativa",
    descriptionEN: "A minimalist, editorial art direction piece for a premium footwear campaign. A single architectural sneaker is placed on a pristine white marble block under soft side lighting.",
    descriptionES: "Una pieza de dirección de arte minimalista y editorial para una campaña de calzado premium. Una zapatilla de diseño arquitectónico sobre un bloque de mármol bajo luz lateral difusa.",
    image: "https://lh3.googleusercontent.com/aida-public/AB6AXuBVMN1vVRiY8qE3FkttqtU7FbiI2tdBWB9NskhVp7PYyCzdoumY7QqYlWrvnVVrhuQ3jnD8D7jQfu1feLb0jQyvMvbMltjoqFYghCBLTCNN3bhg3mUXksMZPP3y4Uj11S0zyVSsPCQHAX_IZTfiXPXYIsw6y_rtvgxYJ-RbCtOTacVhsEmqbA8Q97o7Qz-dm4Jt5jTtOYJAFwkJ7KMl7quSGCdTtTz8AU91F1IqtKLGKCHqqXPB8lpb-4ULSNEVxDqT-KWkd4W0N0Iw",
    categories: ["Branding", "Advertising"],
    conceptEN: "Architectural minimalism highlighting premium materials and structured geometry under dramatic lighting.",
    conceptES: "Minimalismo arquitectónico que destaca materiales premium y geometría estructurada bajo iluminación dramática.",
    processEN: "Coordinated studio side lighting with raw elemental blocks, capturing soft tactile surfaces against cold, geometric marble pillars.",
    processES: "Coordinado la iluminación lateral de estudio con bloques elementales, capturando superficies suaves táctiles contra columnas de mármol geométricas y frías.",
    resultsEN: "Successfully launched across direct-to-consumer digital channels with an 18% increase in catalog engagement and conversion metrics.",
    resultsES: "Lanzamiento exitoso en canales digitales directos con un aumento del 18% en métricas de conversión e interacción con el catálogo."
  },
  {
    id: "herd",
    title: "Herd",
    tagEN: "Videography",
    tagES: "Videografía",
    roleEN: "Cinematographer",
    roleES: "Directora de Fotografía",
    descriptionEN: "A cinematic exploration of human interaction within modern architecture. Captured through the lens of movement and stillness in geometric surroundings.",
    descriptionES: "Una exploración cinematográfica de la interacción humana en la arquitectura moderna. Capturada a través de la lente del movimiento y la quietud en entornos geométricos.",
    image: "https://lh3.googleusercontent.com/aida-public/AB6AXuCTboqqR1WeqDvb1Ysg_qGN0cs-SwQiE2VvPYpaKNzZ3lHR4AdlqANTgBQNCQRRMudGLdw4g-RDrwZ3fyzdnbp45jmYu_zkz1DIPtht-x2G4_vzei96wjhwC4G5rGUD57m0TYcrnExk8wFuloCGyeFihM2I3XM8t5miPgdq1YuJwYOfEMJw1L4o6rNVIK97v62f3U6ZAqN7YGlD3bTUtvcwTD0DdxFcKX1EGibwVY9-nZ8c5DOsnRrNDD-ZcALtJ97kPb5-ZeLU0lKX",
    categories: ["Film & Video"],
    conceptEN: "Cinematic study tracking human patterns within the hard shadows and sharp lines of brutalist and futuristic architecture.",
    conceptES: "Estudio cinematográfico que rastrea patrones humanos en las sombras duras y líneas afiladas de la arquitectura brutalista y futurista.",
    processEN: "Utilized carefully timed camera tracking systems and wide-angle lenses to emphasize the rhythmic cadence of crowds and individual moments of stillness.",
    processES: "Utilizado sistemas de seguimiento de cámara cronometrados y lentes de gran angular para enfatizar la cadencia rítmica de las multitudes y momentos de quietud individuales.",
    resultsEN: "Official selection at contemporary digital art showcases, highlighting structural movement storytelling.",
    resultsES: "Selección oficial en muestras de arte digital contemporáneo, destacando la narrativa de movimiento estructural."
  },
  {
    id: "nada",
    title: "Nada",
    tagEN: "Business Strategy",
    tagES: "Estrategia de Negocio",
    roleEN: "Lead Brand Strategist",
    roleES: "Estratega de Marca Principal",
    descriptionEN: "Consultancy for the circular economy. Redesigning value chains from the ground up to eliminate waste while maximizing brand equity and credibility.",
    descriptionES: "Consultoría para la economía circular. Rediseñando las cadenas de valor desde cero para eliminar los residuos maximizando el valor de marca y la credibilidad.",
    image: "https://lh3.googleusercontent.com/aida-public/AB6AXuDvMnewzFOXZIEQcfmLAlEqR9ZtLU3EH7jbCvy-Jd8ddA63aQWLrCPbWLbkQ_HzBAQBr9ox3PRxsUK5n8JrAzvSMAnLNJ9CnCJ07x-yCnEnJpYy5LhFODrYF-cDMLlQ2lBMUKzEHyxFCpQAYGgZ_ri4-WrRbDhPPQzhrFnJv75d6gx9ZrSODLj6lMIC5qZj4Pt_rojAwjGOT9U1ous4PmhX_JZ8Wc9xkxcB7gVioz0Bg6ETKe_U4UG-byIdnFyT7H7Xzcb_hq0Muyik",
    categories: ["Strategy"],
    conceptEN: "Brand identity integrity paired with transparent value chain design for next-generation zero-waste systems.",
    conceptES: "Integridad de identidad de marca junto con diseño de cadena de valor transparente para sistemas de cero residuos de próxima generación.",
    processEN: "Conducted life-cycle analysis on client resource structures, transforming raw engineering metrics into emotional, high-credibility messaging assets.",
    processES: "Realizado análisis de ciclo de vida en estructuras de recursos del cliente, transformando métricas de ingeniería pura en activos de narrativa corporativa altamente creíble.",
    resultsEN: "Positioned the client firm as a definitive circular economy authority, winning regional sustainable leadership prizes.",
    resultsES: "Posicionado a la firma cliente como autoridad definitiva en economía circular, obteniendo premios regionales de liderazgo sostenible."
  }
];

// TRANSLATIONS mapping dictionary for bilingual (EN/ES) switching
export const TRANSLATIONS = {
  en: {
    heroTitle: "CREATIVE DIRECTION, CONTENT & BRANDING",
    heroHeading: "Driven by strategy,<br>defined by design.",
    heroDescription: "I’m Marta Mexia, a Creative Direction, Content & Branding master’s student at IE Business School. My work connects strategic thinking with visual storytelling, ensuring every creative choice serves a business objective.",
    tagline: "Creative Strategist",
    navHome: "Home",
    navProjects: "Projects",
    navAbout: "About",
    navContact: "Contact",
    downloadCV: "Curriculum Vitae",
    viewProjects: "View Projects",
    letConnect: "Let's connect.",
    selectedProjects: "Selected Projects",
    workTitle: "01 / Work",
    workSummary: "Exploring the intersection of visual impact and strategic purpose.",
    viewCaseStudy: "View Case Study",
    allProjects: "All Projects",
    filterStrategy: "Strategy",
    filterBranding: "Branding",
    filterAdvertising: "Advertising",
    filterServiceDesign: "Service Design",
    filterFilmVideo: "Film & Video",
    filterAI: "AI",
    projectSubtitle: "Explorations at the intersection of human-centric design, creative direction, and emerging technologies.",
    languages: "Languages",
    spanish: "Spanish",
    english: "English",
    french: "French",
    native: "Native",
    languagesC1: "Advanced (C1)",
    frenchLvl: "Intermediate",
    methodology: "Methodology",
    methodologyDesc: "Focusing on data-backed creative decisions, utilizing tools like Salesforce and Adobe to drive measurable brand impact.",
    getInTouchTitle: "Get in Touch",
    contactInquiries: "Open to creative direction, branding, and digital experience opportunities worldwide.",
    emailCardTitle: "Email",
    linkedinCardTitle: "LinkedIn",
    linkedinCardSubtitle: "Network and professional profile.",
    viewProfile: "View Profile",
    locationTitle: "Based In",
    locationValue: "Lisbon, Portugal",
    cvTitle: "Curriculum Vitae",
    cvSubtitle: "Professional trajectory details.",
    contactSuccess: "Message sent! Thank you for reaching out.",
    sendMessage: "Send Message",
    footerTitle: "MARTA MEXIA",
    footerRights: "© 2024 Marta Mexia. Strategic Design & Creative Direction.",
    professionalJourney: "Professional Journey",
    education: "Education",
    getInTouch: "Get in Touch",
    collabQuestion: "Interested in starting a project together?",
    collabDetails: "Interested in discussing branding, creative direction, or a potential collaboration?",
    skillsBranding: "Branding",
    skillsStrategy: "Strategy",
    skillsContent: "Content",
    skillsAI: "AI Coproduction"
  },
  es: {
    heroTitle: "DIRECCIÓN CREATIVA, CONTENIDO Y BRANDING",
    heroHeading: "Impulsada por la estrategia,<br>definida por el diseño.",
    heroDescription: "Soy Marta Mexia, estudiante del Máster en Dirección Creativa, Contenido y Branding en IE Business School. Mi trabajo conecta el pensamiento estratégico con la narrativa visual, garantizando que cada decisión sirva a un objetivo comercial.",
    tagline: "Estratega Creativa",
    navHome: "Inicio",
    navProjects: "Proyectos",
    navAbout: "Sobre mí",
    navContact: "Contacto",
    downloadCV: "Curriculum Vitae",
    viewProjects: "Ver Proyectos",
    letConnect: "Hablemos.",
    selectedProjects: "Proyectos Destacados",
    workTitle: "01 / Trabajos",
    workSummary: "Explorando la intersección del impacto visual y el propósito estratégico del diseño.",
    viewCaseStudy: "Ver Caso de Estudio",
    allProjects: "Todos los Proyectos",
    filterStrategy: "Estrategia",
    filterBranding: "Branding",
    filterAdvertising: "Publicidad",
    filterServiceDesign: "Diseño de Servicios",
    filterFilmVideo: "Cine y Video",
    filterAI: "I.A.",
    projectSubtitle: "Exploraciones en la intersección del diseño centrado en el ser humano, la dirección creativa y las tecnologías emergentes.",
    languages: "Idiomas",
    spanish: "Español",
    english: "Inglés",
    french: "Francés",
    native: "Nativo",
    languagesC1: "Avanzado (C1)",
    frenchLvl: "Intermedio",
    methodology: "Metodología",
    methodologyDesc: "Centrada en decisiones creativas respaldadas por datos, utilizando herramientas como Salesforce y Adobe para impulsar un impacto de marca medible.",
    getInTouchTitle: "Contacto",
    contactInquiries: "Abierta a oportunidades de dirección creativa, branding y experiencias digitales a nivel global.",
    emailCardTitle: "Correo",
    linkedinCardTitle: "LinkedIn",
    linkedinCardSubtitle: "Red de contactos y perfil profesional.",
    viewProfile: "Ver Perfil",
    locationTitle: "Ubicación",
    locationValue: "Lisboa, Portugal",
    cvTitle: "Curriculum Vitae",
    cvSubtitle: "Detalles de trayectoria profesional.",
    contactSuccess: "¡Mensaje enviado! Gracias por ponerte en contacto.",
    sendMessage: "Enviar Mensaje",
    footerTitle: "MARTA MEXIA",
    footerRights: "© 2024 Marta Mexia. Diseño Estratégico y Dirección Creativa.",
    professionalJourney: "Trayectoria Profesional",
    education: "Educación",
    getInTouch: "Ponte en Contacto",
    collabQuestion: "¿Interesado en que colaboremos juntos?",
    collabDetails: "¿Interesado en hablar sobre branding, dirección creativa o una posible colaboración?",
    skillsBranding: "Branding",
    skillsStrategy: "Estrategia",
    skillsContent: "Contenido",
    skillsAI: "Coproducción de IA"
  }
};

// Document State Controller
let currentLang: "en" | "es" = "en";
let currentTab: "home" | "projects" | "about" | "contact" = "home";
let currentCategoryFilter = "All";
let activeCaseStudyProject: Project | null = null;
let activeCaseStudyTab: "concept" | "process" | "results" = "concept";

// Navigation Handler
function switchTab(tabId: "home" | "projects" | "about" | "contact") {
  currentTab = tabId;
  
  // Update section visibilities
  const sections = ["home", "projects", "about", "contact"];
  sections.forEach(s => {
    const el = document.getElementById(`section-${s}`);
    if (el) {
      if (s === tabId) {
        el.classList.remove("hidden");
        // Scroll to top
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        el.classList.add("hidden");
      }
    }
  });

  // Update navbar styling (Desktop)
  const navButtons = ["home", "projects", "about", "contact"];
  navButtons.forEach(b => {
    const dBtn = document.getElementById(`nav-btn-${b}`);
    const underline = document.getElementById(`nav-underline-${b}`);
    
    // Desktop Nav styling
    if (dBtn) {
      if (b === tabId) {
        dBtn.classList.add("text-accent-warm", "font-bold");
        dBtn.classList.remove("text-on-surface-variant");
      } else {
        dBtn.classList.remove("text-accent-warm", "font-bold");
        dBtn.classList.add("text-on-surface-variant");
      }
    }
    if (underline) {
      if (b === tabId) {
        underline.classList.remove("scale-x-0");
        underline.classList.add("scale-x-100");
      } else {
        underline.classList.remove("scale-x-100");
        underline.classList.add("scale-x-0");
      }
    }

    // Mobile Navbar styling
    const mBtn = document.getElementById(`mobile-nav-${b}`);
    if (mBtn) {
      if (b === tabId) {
        mBtn.classList.add("text-accent-warm", "scale-105");
        mBtn.classList.remove("text-on-surface-variant");
      } else {
        mBtn.classList.remove("text-accent-warm", "scale-105");
        mBtn.classList.add("text-on-surface-variant");
      }
    }
  });
}

// Update translations based on active language settings
function updateTranslations() {
  document.querySelectorAll("[data-translate]").forEach(el => {
    const key = el.getAttribute("data-translate") as keyof typeof TRANSLATIONS.en;
    if (key) {
      const text = TRANSLATIONS[currentLang][key] || TRANSLATIONS.en[key];
      if (text.includes("<br>")) {
        el.innerHTML = text;
      } else {
        el.textContent = text;
      }
    }
  });
}

// Language Handler
function setLanguage(lang: "en" | "es") {
  currentLang = lang;
  
  // Update translation nodes in DOM
  updateTranslations();
  
  // Toggle language button active states
  const btnEn = document.getElementById("btn-lang-en");
  const btnEs = document.getElementById("btn-lang-es");
  
  if (lang === "en") {
    if (btnEn && btnEs) {
      btnEn.classList.add("bg-accent-warm", "text-white");
      btnEn.classList.remove("text-on-surface-variant");
      btnEs.classList.remove("bg-accent-warm", "text-white");
      btnEs.classList.add("text-on-surface-variant");
    }
  } else {
    if (btnEn && btnEs) {
      btnEn.classList.remove("bg-accent-warm", "text-white");
      btnEn.classList.add("text-on-surface-variant");
      btnEs.classList.add("bg-accent-warm", "text-white");
      btnEs.classList.remove("text-on-surface-variant");
    }
  }

  // If there's an active case study modal open, refresh its translations
  if (activeCaseStudyProject) {
    renderCaseStudyDetails();
  }
}

// Category Filtering logic
function applyCategoryFilter(category: string) {
  currentCategoryFilter = category;
  
  // Set active capsule classes
  const categories = ["All", "Strategy", "Branding", "Advertising", "Service Design", "Film & Video", "AI"];
  categories.forEach(cat => {
    // We target category elements via ids e.g. `filter-all`, `filter-strategy`, etc.
    const cleanId = cat.toLowerCase().replace(" & ", "-").replace(" ", "-");
    const el = document.getElementById(`filter-${cleanId}`);
    if (el) {
      if (cat === category) {
        el.classList.add("bg-accent-warm", "text-white", "shadow-md", "scale-105");
        el.classList.remove("bg-surface-container", "text-on-surface");
      } else {
        el.classList.remove("bg-accent-warm", "text-white", "shadow-md", "scale-105");
        el.classList.add("bg-surface-container", "text-on-surface");
      }
    }
  });

  // Loop through and hide/show project cards
  let visibleCount = 0;
  PROJECTS.forEach(proj => {
    const cardEl = document.getElementById(`active-project-card-${proj.id}`);
    if (cardEl) {
      if (category === "All" || proj.categories.includes(category)) {
        cardEl.classList.remove("hidden");
        visibleCount++;
      } else {
        cardEl.classList.add("hidden");
      }
    }
  });

  // Handle empty state placeholder
  const emptyStateEl = document.getElementById("empty-project-category");
  if (emptyStateEl) {
    if (visibleCount === 0) {
      emptyStateEl.classList.remove("hidden");
    } else {
      emptyStateEl.classList.add("hidden");
    }
  }
}

// Project Case Study Modal rendering
function openCaseStudy(projId: string) {
  const proj = PROJECTS.find(p => p.id === projId);
  if (!proj) return;
  
  activeCaseStudyProject = proj;
  activeCaseStudyTab = "concept";
  
  // Render details
  renderCaseStudyDetails();
  
  // Show Modal container
  const modal = document.getElementById("case-study-modal");
  if (modal) {
    modal.classList.remove("hidden");
    modal.classList.add("flex");
    document.body.classList.add("overflow-hidden");
  }
}

function closeCaseStudy() {
  activeCaseStudyProject = null;
  const modal = document.getElementById("case-study-modal");
  if (modal) {
    modal.classList.add("hidden");
    modal.classList.remove("flex");
    document.body.classList.remove("overflow-hidden");
  }
}

function switchCaseStudyTab(tab: "concept" | "process" | "results") {
  activeCaseStudyTab = tab;
  
  // Highlights
  ["concept", "process", "results"].forEach(t => {
    const tabBtn = document.getElementById(`cs-tab-${t}`);
    if (tabBtn) {
      if (t === tab) {
        tabBtn.classList.add("border-accent-warm", "text-accent-warm");
        tabBtn.classList.remove("border-transparent", "text-on-surface-variant");
      } else {
        tabBtn.classList.remove("border-accent-warm", "text-accent-warm");
        tabBtn.classList.add("border-transparent", "text-on-surface-variant");
      }
    }
  });

  // Update text body
  const bodyEl = document.getElementById("cs-tab-content-body");
  if (bodyEl && activeCaseStudyProject) {
    if (currentLang === "en") {
      bodyEl.innerText = activeCaseStudyProject[`${tab}EN` as keyof Project] as string;
    } else {
      bodyEl.innerText = activeCaseStudyProject[`${tab}ES` as keyof Project] as string;
    }
  }
}

function renderCaseStudyDetails() {
  if (!activeCaseStudyProject) return;
  const p = activeCaseStudyProject;
  
  // Fill text/image values
  const imgEl = document.getElementById("cs-modal-image") as HTMLImageElement;
  const titleEl = document.getElementById("cs-modal-title");
  const roleEl = document.getElementById("cs-modal-role");
  const tagEl = document.getElementById("cs-modal-tag");
  const descEl = document.getElementById("cs-modal-description");
  
  if (imgEl) imgEl.src = p.image;
  if (titleEl) titleEl.innerText = p.title;
  if (tagEl) {
    tagEl.innerText = currentLang === "en" ? p.tagEN : p.tagES;
  }
  if (roleEl) {
    roleEl.innerText = `Role / Rol: ${currentLang === "en" ? p.roleEN : p.roleES}`;
  }
  if (descEl) {
    descEl.innerText = currentLang === "en" ? p.descriptionEN : p.descriptionES;
  }
  
  // Subcategories badge lists
  const subCatsEl = document.getElementById("cs-modal-subcategories");
  if (subCatsEl) {
    subCatsEl.innerHTML = p.categories.map(c => `
      <span class="text-[10px] bg-surface-dim font-semibold px-2.5 py-1 rounded tracking-wider text-on-surface">
        ${c}
      </span>
    `).join("");
  }

  // Set tab details immediately
  switchCaseStudyTab(activeCaseStudyTab);
}

// Copy clipboard utility
function copyEmail(text: string) {
  navigator.clipboard.writeText(text);
  const triggerBtn = document.getElementById("copy-email-btn");
  const checkIcon = document.getElementById("copy-check-icon");
  const copyIcon = document.getElementById("copy-icon");
  
  if (triggerBtn && checkIcon && copyIcon) {
    checkIcon.classList.remove("hidden");
    copyIcon.classList.add("hidden");
    triggerBtn.classList.add("bg-green-100", "text-green-800");
    
    setTimeout(() => {
      checkIcon.classList.add("hidden");
      copyIcon.classList.remove("hidden");
      triggerBtn.classList.remove("bg-green-100", "text-green-800");
    }, 2000);
  }
}

// CV Modal Toggle triggers
function openCVModal() {
  const modal = document.getElementById("cv-modal");
  if (modal) {
    modal.classList.remove("hidden");
    modal.classList.add("flex");
    document.body.classList.add("overflow-hidden");
  }
}

function closeCVModal() {
  const modal = document.getElementById("cv-modal");
  if (modal) {
    modal.classList.add("hidden");
    modal.classList.remove("flex");
    document.body.classList.remove("overflow-hidden");
  }
}

// Custom form submit handling
function handleFormSubmission(e: Event) {
  e.preventDefault();
  
  const nameEl = document.getElementById("form-name") as HTMLInputElement;
  const emailEl = document.getElementById("form-email") as HTMLInputElement;
  const msgEl = document.getElementById("form-message") as HTMLTextAreaElement;
  const btnEl = document.getElementById("form-submit-btn");
  const btnTextEl = document.getElementById("form-btn-text");
  const successEl = document.getElementById("contact-success-banner");
  
  if (!nameEl.value || !emailEl.value || !msgEl.value) return;
  
  if (btnEl && btnTextEl && successEl) {
    // Set loading
    btnEl.setAttribute("disabled", "true");
    const originalText = btnTextEl.innerText;
    btnTextEl.innerText = currentLang === "en" ? "Sending..." : "Enviando...";
    
    setTimeout(() => {
      // Show success
      btnEl.removeAttribute("disabled");
      btnTextEl.innerText = originalText;
      successEl.classList.remove("hidden");
      
      // Reset values
      nameEl.value = "";
      emailEl.value = "";
      msgEl.value = "";
      
      // Auto-hide success
      setTimeout(() => {
        successEl.classList.add("hidden");
      }, 5000);
    }, 1200);
  }
}

// Initialize listeners on DOM Content load
window.addEventListener("DOMContentLoaded", () => {
  // Navigation Tabs Event bindings (Desktop and Mobile)
  ["home", "projects", "about", "contact"].forEach(tab => {
    // Nav Logo goes to home
    if (tab === "home") {
      const navLogo = document.getElementById("nav-logo-container");
      if (navLogo) {
        navLogo.addEventListener("click", () => switchTab("home"));
      }
    }

    const dBtn = document.getElementById(`nav-btn-${tab}`);
    if (dBtn) {
      dBtn.addEventListener("click", () => switchTab(tab as any));
    }
    const mBtn = document.getElementById(`mobile-nav-${tab}`);
    if (mBtn) {
      mBtn.addEventListener("click", () => switchTab(tab as any));
    }
  });

  // Language buttons
  const btnEn = document.getElementById("btn-lang-en");
  if (btnEn) btnEn.addEventListener("click", () => setLanguage("en"));
  const btnEs = document.getElementById("btn-lang-es");
  if (btnEs) btnEs.addEventListener("click", () => setLanguage("es"));

  // Open-all-projects navigations
  const allProjBtn = document.getElementById("btn-nav-all-projects");
  if (allProjBtn) {
    allProjBtn.addEventListener("click", () => {
      switchTab("projects");
      applyCategoryFilter("All");
    });
  }

  // Primary action buttons pointing to routes on hero
  const heroBtnWork = document.getElementById("hero-btn-work");
  if (heroBtnWork) {
    heroBtnWork.addEventListener("click", () => switchTab("projects"));
  }
  const heroBtnCollab = document.getElementById("hero-btn-collab");
  if (heroBtnCollab) {
    heroBtnCollab.addEventListener("click", () => switchTab("contact"));
  }
  const homeBannerContactBtn = document.getElementById("btn-cta-contact-home");
  if (homeBannerContactBtn) {
    homeBannerContactBtn.addEventListener("click", () => switchTab("contact"));
  }
  const homeBannerCVBtn = document.getElementById("btn-cta-cv-home");
  if (homeBannerCVBtn) {
    homeBannerCVBtn.addEventListener("click", () => openCVModal());
  }

  // Open project cards click events (All grids)
  PROJECTS.forEach(p => {
    const cardHp = document.getElementById(`project-card-${p.id}`);
    if (cardHp) cardHp.addEventListener("click", () => openCaseStudy(p.id));
    
    const cardProj = document.getElementById(`active-project-card-${p.id}`);
    if (cardProj) cardProj.addEventListener("click", () => openCaseStudy(p.id));
  });

  // Category filter toggles
  const categories = ["All", "Strategy", "Branding", "Advertising", "Service Design", "Film & Video", "AI"];
  categories.forEach(cat => {
    const cleanId = cat.toLowerCase().replace(" & ", "-").replace(" ", "-");
    const el = document.getElementById(`filter-${cleanId}`);
    if (el) {
      el.addEventListener("click", () => applyCategoryFilter(cat));
    }
  });

  // Category empty reset action button link
  const emptyReset = document.getElementById("empty-project-category")?.querySelector("button");
  if (emptyReset) {
    emptyReset.addEventListener("click", () => applyCategoryFilter("All"));
  }

  // Case Study sub-tabs control bindings inside modal
  ["concept", "process", "results"].forEach(tab => {
    const btn = document.getElementById(`cs-tab-${tab}`);
    if (btn) {
      btn.addEventListener("click", () => switchCaseStudyTab(tab as any));
    }
  });

  // Close modal button
  const closeCsBtn = document.getElementById("close-cs-modal");
  if (closeCsBtn) closeCsBtn.addEventListener("click", closeCaseStudy);
  const overlayCs = document.getElementById("cs-modal-overlay");
  if (overlayCs) overlayCs.addEventListener("click", closeCaseStudy);

  // Email Copy button
  const copyBtn = document.getElementById("copy-email-btn");
  if (copyBtn) {
    copyBtn.addEventListener("click", () => copyEmail("mexiamarta@gmail.com"));
  }

  // CV Trigger Buttons
  const headerCVBtn = document.getElementById("header-cv-button");
  if (headerCVBtn) headerCVBtn.addEventListener("click", openCVModal);
  const footerCVBtn = document.getElementById("footer-cv-button");
  if (footerCVBtn) footerCVBtn.addEventListener("click", openCVModal);
  const rightColCVBtn = document.getElementById("right-col-cv-button");
  if (rightColCVBtn) rightColCVBtn.addEventListener("click", openCVModal);
  
  // Close CV button
  const closeCvBtn = document.getElementById("close-cv-modal");
  if (closeCvBtn) closeCvBtn.addEventListener("click", closeCVModal);
  const overlayCv = document.getElementById("cv-modal-overlay");
  if (overlayCv) overlayCv.addEventListener("click", closeCVModal);

  // CV print action trigger
  const printBtn = document.getElementById("print-cv-btn");
  if (printBtn) {
    printBtn.addEventListener("click", () => {
      window.print();
    });
  }

  // Contact Form handler
  const form = document.getElementById("contact-message-form");
  if (form) {
    form.addEventListener("submit", handleFormSubmission);
  }

  // Initial language synchronizations
  setLanguage("en");
});
