const { useState, useEffect, useRef, useContext, createContext } = React;

/* ===== TRANSLATIONS ===== */
const T = {
  SI: {
    routes: {
      home: '/', dc: '/podatkovni-centri', ro: '/racunalniska-omrezja',
      bz: '/brezzicna-omrezja', dp: '/dvignjeni-pod',
      about: '/o-podjetju', references: '/reference',
      news: '/novice', careers: '/kariera',
      article: '/novice/'
    },
    nav: {
      resitve: "Rešitve", opodjetju: "O podjetju", reference: "Reference",
      novice: "Novice", kontakt: "Kontakt",
      featEyebrow: "Glavna dejavnost", featTitle: "Podatkovni centri",
      featDesc: "Načrtovanje, gradnja in dolgoročno vzdrževanje, od koncepta do dolgoročnega partnerstva.",
      more: "Podrobno", allAreas: "Vsa področja",
      mobileKicker: "Imate projekt?", mobileCta: "Pošljite povpraševanje",
      services: "Storitve", closeMenu: "Zapri meni", openMenu: "Odpri meni",
      megaSubDc: "Projektiranje, gradnja in dolgoročno vzdrževanje.",
      megaSubRo: "Bakreni in optični sistemi po standardih.",
      megaSubWf: "Wi-Fi, point-to-point in industrijska omrežja.",
      megaSubDp: "Modularni sistemi za serverske prostore."
    },
    hero: {
      kicker: "Podatkovni centri · Računalniška omrežja · WiFi · Dvignjeni pod",
      yearsNum: "28", est: "SI · EST. 1998",
      coords: "46.0569° N · 14.5058° E", city: "Ljubljana, Slovenija",
      h1Lead: "Podatkovni centri",
      h1Tail: "in zanesljiva IT infrastruktura za zahtevna okolja.",
      sub: "Kot vodilni regionalni specialist za podatkovne centre združujemo znanje, izkušnje in inovacije za gradnjo zanesljivih digitalnih temeljev sodobne družbe.",
      rotateLead: "Načrtujemo",
      rotateWords: ["podatkovne centre", "računalniška omrežja", "WiFi omrežja"],
      cta: "Pogovor z našim strokovnjakom",
      ctaSecondary: "Naše storitve",
      years: "let izkušenj"
    },
    solutions: {
      idx: "REŠITVE",
      h2full: "Celovite infrastrukturne rešitve za kritična IT okolja.",
      descText: "Načrtujemo, gradimo in vzdržujemo podatkovne centre, kjer zmogljivost in zanesljivost nista naključje. Vsako področje obravnavamo z enakim inženirskim standardom, od dimenzioniranja in redundance do dokumentacije in dolgoročnega vzdrževanja.",
      h2: ["Ključni gradniki", "en pristop k zanesljivosti."],
      desc: "Vsako področje obravnavamo z enakim inženirskim standardom, od dimenzioniranja in redundance do dokumentacije in dolgoročnega vzdrževanja.",
      items: [
      { t: "Podatkovni centri", d: "Projektiranje, gradnja in dolgoročno vzdrževanje.", tag: "TIER I-IV" },
      { t: "Računalniška omrežja", d: "Bakreni in optični sistemi po standardih.", tag: "LAN · WLAN · CAT6A" },
      { t: "WiFi", d: "Wi-Fi, point-to-point in industrijska omrežja.", tag: "WIFI · DAS" },
      { t: "Dvignjeni pod", d: "Modularni sistemi za serverske prostore.", tag: "NESITE · A1" }]
    },
    dc: {
      idx: "Glavna dejavnost",
      h2: ["Podatkovni centri", "so jedro našega dela."],
      lede: "Ne dobavljamo opreme. Dobavljamo sistem, usklajen, dokumentiran in vzdrževan. Z eno ekipo od prve risbe do brezhibnega delovanja.",
      cta: "Več o podatkovnih centrih",
      kpis: [
        ["15+ LET", "življenjska doba"],
        ["≤ 1.3", "ciljni PUE"],
        ["TIER I-IV", "topologija"],
        ["24/7", "monitoring & SLA"],
      ],
      rows: [
      ["01", "Načrtovanje in zasnova", "Tehnični projekt · dimenzioniranje · prostorska študija"],
      ["02", "Napajanje in redundanca", "UPS · diesel · N+1 / 2N topologije"],
      ["03", "Hlajenje in optimizacija", "Hot/cold aisle · CRAH · PUE optimizacija"],
      ["04", "Dolgoročna podpora", "24/7 monitoring · SLA · načrtovano vzdrževanje"]]
    },
    trust: {
      idx: "Zaupanje",
      h2: "Zaupajo nam organizacije, podjetja in institucije.",
      clients: [
        ["Krka", "PHARMA"], ["Lek", "PHARMA"], ["NLB", "FINANCE"],
        ["SID Banka", "FINANCE"], ["Triglav", "INSURANCE"], ["Petrol", "ENERGY"],
        ["Pošta Slovenije", "PUBLIC"], ["DARS", "PUBLIC"],
        ["Iskratel", "TELCO"], ["UKC Ljubljana", "HEALTH"]
      ]
    },
    collab: {
      line1: "Stabilnost sistema",
      line2: "se odloči že v načrtu.",
      cta: "Pogovor z našim strokovnjakom"
    },
    refs: {
      idx: "ŠTUDIJE PRIMEROV",
      h2: "Rešitve izvedenih projektov",
      cta: "Vse reference",
      items: [
      ["01", "Podatkovni center za farmacevtsko podjetje", "Tier III · 2N napajanje · 1.2 MW", "2024"],
      ["02", "Infrastruktura za finančni sektor", "Računalniška omrežja · 12 nadstropij", "2023"],
      ["03", "Nadgradnja obstoječega sistema", "Migracija · brez prekinitve delovanja", "2023"],
      ["04", "Brezžična omrežja v industrijskem objektu", "Wi-Fi 6 · 84 dostopnih točk", "2022"]]
    },
    contact: {
      idx: "Kontakt",
      h2: ["Imate projekt, težavo", "ali pa samo vprašanje?"],
      desc: "V nekaj korakih vas usmerimo do prave rešitve. Odgovor v roku enega delovnega dne, tehnični sestanek po dogovoru.",
      aside: "Brez prodajnih klicev. Pogovor začnemo z inženirjem, ki pozna vaše področje.",
      step1h: "Katero področje vas zanima?", step1sub: "Izberite eno, kasneje lahko dodate več.",
      step2h: "Povejte nam več.", step2sub: "Kratek opis zadošča, tehnične podrobnosti uskladimo na sestanku.",
      step3h: "Pregled pred pošiljanjem.", step3sub: "Preverite podatke. Po pošiljanju se vam oglasimo v enem delovnem dnevu.",
      back: "← Nazaj", next: "Naprej", send: "Pošlji povpraševanje",
      successTitle: "Hvala. Sporočilo je sprejeto.",
      areas: [
      { id: "dc", name: "Podatkovni centri", code: "01" },
      { id: "kabli", name: "Računalniška omrežja", code: "02" },
      { id: "wifi", name: "WiFi", code: "03" },
      { id: "podi", name: "Dvignjeni pod", code: "04" }],
      fields: { msg: "Sporočilo", name: "Ime in priimek", company: "Podjetje", email: "E-pošta", phone: "Telefon (neobvezno)", send: "Pošlji povpraševanje" },
      summary: { area: "Področje", contact: "Kontakt", email: "E-pošta", phone: "Telefon", msg: "Sporočilo" },
      ph: { msg: "Npr. načrtujemo selitev podatkovnega centra; potrebujemo svetovanje o redundanci napajanja…", msgShort: "Npr. načrtujemo selitev DC…", name: "Janez Novak", company: "Podjetje d.o.o.", email: "ime@podjetje.si", phone: "+386 …" },
      sending: "Pošiljanje…", sendErr: "Napaka pri pošiljanju.",
      successSub: ["Inženir s področja ", " se vam oglasi v roku enega delovnega dne na ", "."],
      meta: {
        email: "E-pošta", emailVal: "info@advant.si",
        phone: "Telefon", phoneVal: "+386 1 470 00 00",
        fax: "Fax", faxVal: "+386 1 470 00 10",
        address: "Sedež", addressVal: "Cesta na Brdo 119A, Ljubljana",
        mapsUrl: "https://maps.app.goo.gl/9o4sCinG27XLJLbd9",
        response: "Odzivni čas", responseVal: "≤ 1 delovni dan",
        hours: "Delovni čas"
      }
    },
    footer: {
      desc: "Inženirsko podjetje za zanesljivo infrastrukturo. Podatkovni centri, računalniška omrežja, WiFi in dvojni podi.",
      services: "Storitve", company: "Podjetje", contact: "Stik", legal: "Pravno",
      emailVal: "info@advant.si", phoneVal: "+386 1 470 00 00",
      links: { dc: "Podatkovni centri", kab: "Računalniška omrežja", wifi: "WiFi", pod: "Dvignjeni pod",
        about: "O podjetju", ref: "Reference", news: "Novice", career: "Kariera",
        contactLink: "Kontakt", privacy: "Zasebnost", cookies: "Piškotki", legal: "Pravne informacije" }
    }
  },
  EN: {
    routes: {
      home: '/en', dc: '/en/data-centers', ro: '/en/networking',
      bz: '/en/wireless-networks', dp: '/en/raised-floor',
      about: '/en/about', references: '/en/references',
      news: '/en/news', careers: '/en/careers',
      article: '/novice/'
    },
    nav: {
      resitve: "Solutions", opodjetju: "About", reference: "References",
      novice: "News", kontakt: "Contact",
      featEyebrow: "Core activity", featTitle: "Data centers",
      featDesc: "Design, construction and long-term maintenance, from concept to a long-term partnership.",
      more: "Learn more", allAreas: "All areas",
      mobileKicker: "Have a project?", mobileCta: "Send an enquiry",
      services: "Services", closeMenu: "Close menu", openMenu: "Open menu",
      megaSubDc: "Design, construction and long-term maintenance.",
      megaSubRo: "Copper and optical systems to standards.",
      megaSubWf: "Wi-Fi, point-to-point and industrial networks.",
      megaSubDp: "Modular systems for server rooms."
    },
    hero: {
      kicker: "Data Centers · Computer Networks · WiFi · Raised Floors",
      yearsNum: "28", est: "SI · EST. 1998",
      coords: "46.0569° N · 14.5058° E", city: "Ljubljana, Slovenia",
      h1Lead: "Data centers",
      h1Tail: "and reliable IT infrastructure for demanding environments.",
      sub: "We specialise in data centers, computer networks, WiFi networks and raised floors, from planning to delivery and maintenance.",
      rotateLead: "We engineer",
      rotateWords: ["data centers", "computer networks", "WiFi networks"],
      cta: "Talk to our expert",
      ctaSecondary: "Our services",
      years: "years of experience"
    },
    solutions: {
      idx: "SOLUTIONS",
      h2full: "Comprehensive infrastructure solutions for critical IT environments.",
      descText: "We design, build and maintain data centers where performance and reliability are by design. Every area treated with the same engineering standard.",
      h2: ["Key building blocks -", "one approach to reliability."],
      desc: "We treat every area with the same engineering standard, from dimensioning and redundancy to documentation and long-term maintenance.",
      items: [
      { t: "Data Centers", d: "Design, construction and long-term maintenance.", tag: "TIER I-IV" },
      { t: "Computer Networks", d: "Copper and optical systems to standards.", tag: "LAN · WLAN · CAT6A" },
      { t: "WiFi", d: "Wi-Fi, point-to-point and industrial networks.", tag: "WIFI · DAS" },
      { t: "Raised Floors", d: "Modular systems for server rooms.", tag: "NESITE · A1" }]
    },
    dc: {
      idx: "Core activity",
      h2: ["Data centers", "are the core of our work."],
      lede: "We don't supply equipment. We deliver a system, aligned, documented and maintained. One team from the first drawing to flawless operation.",
      cta: "More about data centers",
      kpis: [
        ["15+ YRS", "lifespan"],
        ["≤ 1.3", "target PUE"],
        ["TIER I-IV", "topology"],
        ["24/7", "monitoring & SLA"],
      ],
      rows: [
      ["01", "Design & planning", "Technical project · dimensioning · spatial study"],
      ["02", "Power & redundancy", "UPS · diesel · N+1 / 2N topologies"],
      ["03", "Cooling & optimization", "Hot/cold aisle · CRAH · PUE optimization"],
      ["04", "Long-term support", "24/7 monitoring · SLA · planned maintenance"]]
    },
    trust: {
      idx: "Clients",
      h2: "Trusted by organisations, companies and institutions.",
      clients: [
        ["Krka", "PHARMA"], ["Lek", "PHARMA"], ["NLB", "FINANCE"],
        ["SID Bank", "FINANCE"], ["Triglav", "INSURANCE"], ["Petrol", "ENERGY"],
        ["Post of Slovenia", "PUBLIC"], ["DARS", "PUBLIC"],
        ["Iskratel", "TELCO"], ["UKC Ljubljana", "HEALTH"]
      ]
    },
    collab: {
      line1: "System reliability",
      line2: "is decided at the design stage.",
      cta: "Talk to our expert"
    },
    refs: {
      idx: "CASE STUDIES",
      h2: "Completed project solutions",
      cta: "All references",
      items: [
      ["01", "Data center for a pharmaceutical company", "Tier III · 2N power · 1.2 MW", "2024"],
      ["02", "Financial sector infrastructure", "Structured cabling · 12 floors", "2023"],
      ["03", "Upgrade of an existing system", "Migration · without downtime", "2023"],
      ["04", "Wireless networks in an industrial facility", "Wi-Fi 6 · 84 access points", "2022"]]
    },
    contact: {
      idx: "Contact",
      h2: ["Got a project, a challenge,", "or just a question?"],
      desc: "We'll guide you to the right solution in a few steps. Response within one business day, technical meeting within two.",
      aside: "No sales calls. We start the conversation with an engineer who knows your field.",
      step1h: "Which area are you interested in?", step1sub: "Choose one, you can add more later.",
      step2h: "Tell us more.", step2sub: "A brief description is enough, technical details are discussed at the meeting.",
      step3h: "Review before sending.", step3sub: "Check your details. After sending, we'll get back to you within one business day.",
      back: "← Back", next: "Next", send: "Submit inquiry",
      successTitle: "Thank you. Message received.",
      areas: [
      { id: "dc", name: "Data Centers", code: "01" },
      { id: "kabli", name: "Computer Networks", code: "02" },
      { id: "wifi", name: "WiFi", code: "03" },
      { id: "podi", name: "Raised Floors", code: "04" }],
      fields: { msg: "Message", name: "Full name", company: "Company", email: "Email", phone: "Phone (optional)", send: "Submit inquiry" },
      summary: { area: "Area", contact: "Contact", email: "Email", phone: "Phone", msg: "Message" },
      ph: { msg: "E.g. we're planning a data center migration; we need advice on power redundancy…", msgShort: "E.g. we're planning a DC migration…", name: "John Smith", company: "Company Ltd.", email: "name@company.com", phone: "+386 …" },
      sending: "Sending…", sendErr: "Error while sending.",
      successSub: ["An engineer specializing in ", " will contact you within one business day at ", "."],
      meta: {
        email: "Email", emailVal: "info@advant.si",
        phone: "Phone", phoneVal: "+386 1 470 00 00",
        fax: "Fax", faxVal: "+386 1 470 00 10",
        address: "Address", addressVal: "Cesta na Brdo 119A, Ljubljana",
        mapsUrl: "https://maps.app.goo.gl/9o4sCinG27XLJLbd9",
        response: "Response time", responseVal: "≤ 1 business day",
        hours: "Office hours"
      }
    },
    footer: {
      desc: "Engineering company for reliable infrastructure. Data centers, computer networks, WiFi and raised floors.",
      services: "Services", company: "Company", contact: "Contact", legal: "Legal",
      emailVal: "info@advant.si", phoneVal: "+386 1 470 00 00",
      links: { dc: "Data Centers", kab: "Computer Networks", wifi: "WiFi", pod: "Raised Floors",
        about: "About us", ref: "References", news: "News", career: "Careers",
        contactLink: "Contact", privacy: "Privacy", cookies: "Cookies", legal: "Legal notice" }
    }
  },
  DE: {
    routes: {
      home: '/de', dc: '/de/datenzentren', ro: '/de/netzwerke',
      bz: '/de/drahtlose-netzwerke', dp: '/de/doppelboden',
      about: '/de/uber-uns', references: '/de/referenzen',
      news: '/de/neuigkeiten', careers: '/de/karriere',
      article: '/novice/'
    },
    nav: {
      resitve: "Lösungen", opodjetju: "Über uns", reference: "Referenzen",
      novice: "Neuigkeiten", kontakt: "Kontakt",
      featEyebrow: "Kerntätigkeit", featTitle: "Rechenzentren",
      featDesc: "Planung, Bau und langfristige Wartung, vom Konzept bis zur langfristigen Partnerschaft.",
      more: "Mehr erfahren", allAreas: "Alle Bereiche",
      mobileKicker: "Haben Sie ein Projekt?", mobileCta: "Anfrage senden",
      services: "Leistungen", closeMenu: "Menü schließen", openMenu: "Menü öffnen",
      megaSubDc: "Planung, Bau und Langzeitwartung.",
      megaSubRo: "Kupfer- und Glasfasersysteme nach Standards.",
      megaSubWf: "Wi-Fi, Point-to-Point und industrielle Netze.",
      megaSubDp: "Modulare Systeme für Serverräume."
    },
    hero: {
      kicker: "Rechenzentren · Computernetzwerke · WiFi · Doppelböden",
      yearsNum: "28", est: "SI · EST. 1998",
      coords: "46.0569° N · 14.5058° E", city: "Ljubljana, Slowenien",
      h1Lead: "Rechenzentren",
      h1Tail: "und zuverlässige IT-Infrastruktur für anspruchsvolle Umgebungen.",
      sub: "Wir sind spezialisiert auf Rechenzentren, Computernetzwerke, WiFi-Netze und Doppelböden, von der Planung bis zur Umsetzung und Wartung.",
      rotateLead: "Wir planen",
      rotateWords: ["Rechenzentren", "Computernetzwerke", "WiFi-Netze"],
      cta: "Gespräch mit unserem Experten",
      ctaSecondary: "Unsere Leistungen",
      years: "Jahre Erfahrung"
    },
    solutions: {
      idx: "LÖSUNGEN",
      h2full: "Umfassende Infrastrukturlösungen für kritische IT-Umgebungen.",
      descText: "Wir planen, bauen und warten Rechenzentren, bei denen Leistung und Zuverlässigkeit kein Zufall sind.",
      h2: ["Schlüsselkomponenten -", "ein Ansatz für Zuverlässigkeit."],
      desc: "Jedes Bereich behandeln wir mit demselben Engineering-Standard, von Dimensionierung und Redundanz bis zu Dokumentation und Langzeitwartung.",
      items: [
      { t: "Rechenzentren", d: "Planung, Bau und Langzeitwartung.", tag: "TIER I-IV" },
      { t: "Computernetzwerke", d: "Kupfer- und Glasfasersysteme nach Standards.", tag: "LAN · WLAN · CAT6A" },
      { t: "WiFi", d: "Wi-Fi, Point-to-Point und industrielle Netze.", tag: "WIFI · DAS" },
      { t: "Doppelböden", d: "Modulare Systeme für Serverräume.", tag: "NESITE · A1" }]
    },
    dc: {
      idx: "Kerngeschäft",
      h2: ["Rechenzentren sind", "der Kern unserer Arbeit."],
      lede: "Wir liefern keine Geräte. Wir liefern ein System, abgestimmt, dokumentiert und gewartet. Ein Team vom ersten Entwurf bis zum reibungslosen Betrieb.",
      cta: "Mehr über Rechenzentren",
      kpis: [
        ["15+ J.", "Lebensdauer"],
        ["≤ 1.3", "Ziel-PUE"],
        ["TIER I-IV", "Topologie"],
        ["24/7", "Monitoring & SLA"],
      ],
      rows: [
      ["01", "Planung & Entwurf", "Technisches Projekt · Dimensionierung · Raumplanung"],
      ["02", "Stromversorgung & Redundanz", "USV · Diesel · N+1 / 2N-Topologien"],
      ["03", "Kühlung & Optimierung", "Hot/Cold-Aisle · CRAH · PUE-Optimierung"],
      ["04", "Langzeitsupport", "24/7-Monitoring · SLA · geplante Wartung"]]
    },
    trust: {
      idx: "Vertrauen",
      h2: "Vertrauen von Organisationen, Unternehmen und Institutionen.",
      clients: [
        ["Krka", "PHARMA"], ["Lek", "PHARMA"], ["NLB", "FINANZEN"],
        ["SID Bank", "FINANZEN"], ["Triglav", "VERSICHERUNG"], ["Petrol", "ENERGIE"],
        ["Post Slowenien", "ÖFFENTLICH"], ["DARS", "ÖFFENTLICH"],
        ["Iskratel", "TELKO"], ["UKC Ljubljana", "GESUNDHEIT"]
      ]
    },
    collab: {
      line1: "Systemzuverlässigkeit",
      line2: "entscheidet sich bereits in der Planung.",
      cta: "Gespräch mit unserem Experten"
    },
    refs: {
      idx: "FALLSTUDIEN",
      h2: "Abgeschlossene Projektlösungen",
      cta: "Alle Referenzen",
      items: [
      ["01", "Rechenzentrum für ein Pharmaunternehmen", "Tier III · 2N-Stromversorgung · 1,2 MW", "2024"],
      ["02", "Infrastruktur für den Finanzsektor", "Computernetzwerke · 12 Etagen", "2023"],
      ["03", "Erweiterung eines bestehenden Systems", "Migration · ohne Ausfallzeit", "2023"],
      ["04", "Drahtlose Netzwerke in einem Industrieobjekt", "Wi-Fi 6 · 84 Access Points", "2022"]]
    },
    contact: {
      idx: "Kontakt",
      h2: ["Haben Sie ein Projekt, ein Problem", "oder einfach eine Frage?"],
      desc: "Wir führen Sie in wenigen Schritten zur richtigen Lösung. Antwort innerhalb eines Werktages, technisches Treffen innerhalb von zwei.",
      aside: "Keine Verkaufsgespräche. Wir beginnen das Gespräch mit einem Ingenieur, der Ihr Fachgebiet kennt.",
      step1h: "Welcher Bereich interessiert Sie?", step1sub: "Wählen Sie einen aus, Sie können später weitere hinzufügen.",
      step2h: "Erzählen Sie uns mehr.", step2sub: "Eine kurze Beschreibung reicht, technische Details besprechen wir beim Treffen.",
      step3h: "Überprüfung vor dem Senden.", step3sub: "Überprüfen Sie Ihre Daten. Nach dem Senden melden wir uns innerhalb eines Werktages.",
      back: "← Zurück", next: "Weiter", send: "Anfrage absenden",
      successTitle: "Danke. Nachricht erhalten.",
      areas: [
      { id: "dc", name: "Rechenzentren", code: "01" },
      { id: "kabli", name: "Computernetzwerke", code: "02" },
      { id: "wifi", name: "WiFi", code: "03" },
      { id: "podi", name: "Doppelböden", code: "04" }],
      fields: { msg: "Nachricht", name: "Vor- und Nachname", company: "Unternehmen", email: "E-Mail", phone: "Telefon (optional)", send: "Anfrage absenden" },
      summary: { area: "Bereich", contact: "Kontakt", email: "E-Mail", phone: "Telefon", msg: "Nachricht" },
      ph: { msg: "Z. B. wir planen einen Rechenzentrumsumzug; wir benötigen Beratung zur Stromredundanz…", msgShort: "Z. B. wir planen einen RZ-Umzug…", name: "Max Mustermann", company: "Firma GmbH", email: "name@firma.de", phone: "+386 …" },
      sending: "Senden…", sendErr: "Fehler beim Senden.",
      successSub: ["Ein auf ", " spezialisierter Ingenieur meldet sich innerhalb eines Werktages bei Ihnen unter ", "."],
      meta: {
        email: "E-Mail", emailVal: "info@advant.si",
        phone: "Telefon", phoneVal: "+386 1 470 00 00",
        fax: "Fax", faxVal: "+386 1 470 00 10",
        address: "Adresse", addressVal: "Cesta na Brdo 119A, Ljubljana",
        mapsUrl: "https://maps.app.goo.gl/9o4sCinG27XLJLbd9",
        response: "Reaktionszeit", responseVal: "≤ 1 Werktag",
        hours: "Öffnungszeiten"
      }
    },
    footer: {
      desc: "Ingenieurbüro für zuverlässige Infrastruktur. Rechenzentren, Computernetzwerke, WiFi und Doppelböden.",
      services: "Leistungen", company: "Unternehmen", contact: "Kontakt", legal: "Rechtliches",
      emailVal: "info@advant.si", phoneVal: "+386 1 470 00 00",
      links: { dc: "Rechenzentren", kab: "Computernetzwerke", wifi: "WiFi", pod: "Doppelböden",
        about: "Über uns", ref: "Referenzen", news: "Neuigkeiten", career: "Karriere",
        contactLink: "Kontakt", privacy: "Datenschutz", cookies: "Cookies", legal: "Rechtliche Hinweise" }
    }
  }
};

/* ===== LANG CONTEXT ===== */
const LangContext = createContext("SI");

/* Cross-language URL map — used by LangSwitch to navigate to equivalent page */
const ROUTE_XREF = [
  { SI: '/',                     EN: '/en',                     DE: '/de'                     },
  { SI: '/podatkovni-centri',    EN: '/en/data-centers',        DE: '/de/datenzentren'        },
  { SI: '/racunalniska-omrezja', EN: '/en/networking',          DE: '/de/netzwerke'           },
  { SI: '/brezzicna-omrezja',    EN: '/en/wireless-networks',   DE: '/de/drahtlose-netzwerke' },
  { SI: '/dvignjeni-pod',        EN: '/en/raised-floor',        DE: '/de/doppelboden'         },
  { SI: '/o-podjetju',           EN: '/en/about',               DE: '/de/uber-uns'            },
  { SI: '/reference',            EN: '/en/references',          DE: '/de/referenzen'          },
  { SI: '/novice',               EN: '/en/news',                DE: '/de/neuigkeiten'         },
  { SI: '/kariera',              EN: '/en/careers',             DE: '/de/karriere'            },
];

function getEquivalentUrl(targetLang) {
  try {
    const path = window.location.pathname.replace(/\/$/, "") || "/";
    const entry = ROUTE_XREF.find(function(r) { return Object.values(r).indexOf(path) !== -1; });
    if (entry) return entry[targetLang];
    return T[targetLang].routes.home;
  } catch(e) {
    return targetLang === "SI" ? "/" : ("/" + targetLang.toLowerCase());
  }
}


/* ----- IMAGES ----- */
const IMG = {
  hero: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=2400&q=85&auto=format&fit=crop",
  dc: "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=1600&q=85&auto=format&fit=crop",
  // sol1..sol4 are index-aligned to the solutions cards (DC / networks / WiFi / raised floor),
  // matching WP hp_sol{i}_img and the title order in T[lang].solutions.items.
  sol1: "/images/data-centers/_ABP7614.webp", // data centers
  sol2: "https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=1200&q=85&auto=format&fit=crop", // dense computer networks, patch panels
  sol3: "/images/brezzicna-omrezja.png", // wireless access point, user-provided
  sol4: "/images/dvignjeni-pod.png" // raised floor, user-provided
};

/* ----- ARROW (no icon library, just a tiny mark) ----- */
const Arrow = ({ size = 14, className }) =>
<svg className={className} width={size} height={size} viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.25">
    <path d="M3 11 L11 3 M5 3 H11 V9" />
  </svg>;


/* ===== LANGUAGE SWITCH ===== */
function LangSwitch({ lang }) {
  const langs = ["SI", "EN", "DE"];
  return (
    <div className="lang" role="group" aria-label="Language">
      {langs.map((l, i) =>
      <React.Fragment key={l}>
          <a
          href={getEquivalentUrl(l)}
          className={"lang__btn " + (lang === l ? "is-active" : "")}
          aria-current={lang === l ? "true" : undefined}>
            {l}
          </a>
          {i < langs.length - 1 && <span className="lang__sep" aria-hidden="true" />}
        </React.Fragment>
      )}
    </div>);
}

/* ===== HEADER ===== */
function PageLabel() {
  // Derive a section label from <title>. Format expected: "Section | Advant".
  // Homepage (single-token title, or starts with "Advant") shows nothing.
  const label = React.useMemo(() => {
    if (typeof document === "undefined") return null;
    const t = (document.title || "").trim();
    if (!t.includes("|")) return null;
    const first = t.split("|")[0].trim();
    if (!first || first.toLowerCase().startsWith("advant")) return null;
    return first;
  }, []);
  if (!label) return null;
  return (
    <span className="nav__crumb" aria-label={`Trenutna stran: ${label}`}>
      <span className="nav__crumb-bar" aria-hidden="true" />
      <span className="nav__crumb-text">{label}</span>
    </span>
  );
}

function Header() {
  const lang = useContext(LangContext);
  const t = T[lang].nav;
  const [scrolled, setScrolled] = useState(false);
  const [openSol, setOpenSol] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeTimer = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.classList.toggle("menu-open", mobileOpen);
  }, [mobileOpen]);

  const open = () => {clearTimeout(closeTimer.current);setOpenSol(true);};
  const close = () => {closeTimer.current = setTimeout(() => setOpenSol(false), 120);};
  const closeMobile = () => setMobileOpen(false);

  const solutions = [
  ["Podatkovni centri", "01", true],
  ["Dvignjeni podi", "02", false],
  ["Računalniška omrežja", "03", false],
  ["Brezžična omrežja", "04", false]];


  return (
    <header className={"nav " + (scrolled ? "is-scrolled" : "")}>
      <div className={"nav-scrim " + (openSol ? "is-on" : "")} aria-hidden="true" />
      <div className="nav__inner">
        <a href={T[lang].routes.home} className="logo" aria-label="Advant" onClick={closeMobile}>
          <img src="/assets/advant-logo-hires.png" alt="Advant" />
        </a>
        <PageLabel />
        <nav className="nav__links">
          <div
            className={"nav__item " + (openSol ? "nav__item--open" : "")}
            onMouseEnter={open}
            onMouseLeave={close}>
            
            <a href="#solutions" className="nav__link">
              {t.resitve}
              <span className="nav__caret" />
            </a>
            <div className="dropdown" onMouseEnter={open} onMouseLeave={close}>
              <a href={T[lang].routes.dc} className="dropdown__featured">
                <div
                  className="dropdown__featured-bg"
                  style={{ backgroundImage: 'url("/images/data-centers/_ABP7578.webp")' }} />
                
                <span className="eyebrow">{t.featEyebrow}</span>
                <div className="dropdown__featured-body">
                  <h4>{t.featTitle}</h4>
                  <small>{t.featDesc}</small>
                </div>
                <div className="dropdown__featured-foot">
                  <span>{t.more} <Arrow size={11} className="arr" /></span>
                </div>
              </a>
              <div className="dropdown__list">
                <div className="dropdown__list-head">{t.allAreas}</div>
                {[
                ["01", T[lang].solutions.items[0].t, t.megaSubDc, T[lang].routes.dc],
                ["02", T[lang].solutions.items[1].t, t.megaSubRo, T[lang].routes.ro],
                ["03", T[lang].solutions.items[2].t, t.megaSubWf, T[lang].routes.bz],
                ["04", T[lang].solutions.items[3].t, t.megaSubDp, T[lang].routes.dp]].
                map(([n, t, d, href]) =>
                <a key={n} href={href} className="dropdown__item">
                    <span className="dropdown__item-num">{n}</span>
                    <span className="dropdown__item-text">
                      <span className="dropdown__item-title">{t}</span>
                      <span className="dropdown__item-desc">{d}</span>
                    </span>
                    <Arrow size={11} className="dropdown__item-arr" />
                  </a>
                )}
              </div>
            </div>
          </div>
          <a href={T[lang].routes.about} className="nav__link">{t.opodjetju}</a>
          <a href={T[lang].routes.references} className="nav__link">{t.reference}</a>
          <a href={T[lang].routes.news} className="nav__link">{t.novice}</a>
          <LangSwitch lang={lang} />
          <a href="#contact" className="btn btn--primary" style={{ height: 40, padding: "0 18px", marginLeft: 4 }}
          onClick={(e) => {e.preventDefault();window.__openContactModal && window.__openContactModal();}}>
            {t.kontakt} <Arrow size={12} className="arrow" />
          </a>
        </nav>
        <button
          className={"nav__toggle " + (mobileOpen ? "is-open" : "")}
          aria-label={mobileOpen ? t.closeMenu : t.openMenu}
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen((o) => !o)}>
          
          <span className="nav__toggle-bars"><span /><span /><span /></span>
        </button>
      </div>

      <div className={"mobile-menu " + (mobileOpen ? "is-open" : "")}>

        {/* PRIMARY ACTION, povpraševanje */}
        <a href="#contact" className="mobile-menu__primary" onClick={(e) => { e.preventDefault(); closeMobile(); window.__openContactModal && window.__openContactModal(); }}>
          <div>
            <span className="kicker">{t.mobileKicker}</span>
            <strong>{t.mobileCta}</strong>
          </div>
          <Arrow size={16} />
        </a>

        {/* STORITVE */}
        <div className="mobile-menu__group">
          <h6>{t.services}</h6>
          <a href={T[lang].routes.dc} className="mobile-menu__sub" onClick={closeMobile}>
            <span><span className="num">01</span>{T[lang].solutions.items[0].t}</span>
            <span className="meta">→</span>
          </a>
          <a href={T[lang].routes.ro} className="mobile-menu__sub" onClick={closeMobile}>
            <span><span className="num">02</span>{T[lang].solutions.items[1].t}</span>
            <span className="meta">→</span>
          </a>
          <a href={T[lang].routes.bz} className="mobile-menu__sub" onClick={closeMobile}>
            <span><span className="num">03</span>{T[lang].solutions.items[2].t}</span>
            <span className="meta">→</span>
          </a>
          <a href={T[lang].routes.dp} className="mobile-menu__sub" onClick={closeMobile}>
            <span><span className="num">04</span>{T[lang].solutions.items[3].t}</span>
            <span className="meta">→</span>
          </a>
        </div>

        {/* DRUGO */}
        <div className="mobile-menu__group">
          <a href={T[lang].routes.references} className="mobile-menu__link" onClick={closeMobile}>{t.reference} <span className="meta">→</span></a>
          <a href={T[lang].routes.about} className="mobile-menu__link" onClick={closeMobile}>{t.opodjetju} <span className="meta">→</span></a>
          <a href={T[lang].routes.news} className="mobile-menu__link" onClick={closeMobile}>{t.novice} <span className="meta">→</span></a>
          {/* Kariera začasno skrita iz mobilnega menija */}
          {/* <a href={T[lang].routes.careers} className="mobile-menu__link" onClick={closeMobile}>{T[lang].footer.links.career} <span className="meta">→</span></a> */}
        </div>

        {/* CONTACT INFO */}
        <div className="mobile-menu__contact">
          <a href={"mailto:" + T[lang].contact.meta.emailVal} className="mobile-menu__contact-row">
            <span className="lbl">{T[lang].contact.meta.email}</span>
            <span className="val">{T[lang].contact.meta.emailVal}</span>
          </a>
          <a href={"tel:" + (T[lang].contact.meta.phoneVal || "").replace(/\s/g, "")} className="mobile-menu__contact-row">
            <span className="lbl">{T[lang].contact.meta.phone}</span>
            <span className="val">{T[lang].contact.meta.phoneVal}</span>
          </a>
          <a href={T[lang].contact.meta.mapsUrl} target="_blank" rel="noopener" className="mobile-menu__contact-row">
            <span className="lbl">{T[lang].contact.meta.address}</span>
            <span className="val">{T[lang].contact.meta.addressVal}</span>
          </a>
        </div>

        {/* THUMB-REACH CLOSE, at the bottom for long menus */}
        <button type="button" className="mobile-menu__close-foot" onClick={closeMobile}>
          <span>{t.closeMenu}</span>
          <span aria-hidden="true">×</span>
        </button>
      </div>
    </header>);

}

/* ===== HERO ===== */
function Hero() {
  const lang = useContext(LangContext);
  const th = T[lang].hero;
  const words = th.rotateWords;
  const [wi, setWi] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setWi(i => (i + 1) % words.length), 2600);
    return () => clearInterval(id);
  }, [words.length]);

  return (
    <section className="hero" style={{ padding: 0, borderBottom: "1px solid var(--line)" }}>
      <div className="hero__bg">
        <video autoPlay muted loop playsInline className="hero__bg-video"
        src="/assets/hero.m4v" poster="/assets/hero-poster.jpg" />
        <div className="hero__bg-scrim" aria-hidden="true" />
      </div>
      <div className="hero__frame" aria-hidden="true"><span /></div>
      <div className="hero__topbar">
        <div className="hero__topbar-left mono">
          <span>{th.yearsNum} {th.years}</span>
          <span className="hero__topbar-sep" />
          <span>{th.est}</span>
        </div>
        <div className="hero__topbar-right mono">
          <span>{th.coords}</span>
          <span className="hero__topbar-sep" />
          <span>{th.city}</span>
        </div>
      </div>

      {/* Hero content */}
      <div className="hero__content">


        <div className="hero__rotator mono" aria-hidden="true">
          <span className="hero__rotator-lead">{th.rotateLead}</span>
          <span className="hero__rotator-stage">
            {words.map((w, i) => (
              <span
                key={i}
                className={"hero__rotator-word" + (i === wi ? " is-on" : "")}
              >{w}</span>
            ))}
          </span>
        </div>

        <h1 className="hero__title">
          <span className="hero__title-line1">{th.h1Lead}</span>
          <span className="hero__title-line2">{th.h1Tail}</span>
        </h1>
        <p className="hero__sub">{th.sub}</p>

        <div className="hero__foot">
          <a href="#contact" className="btn btn--primary hero__foot-cta" style={{ whiteSpace: "nowrap" }}
             onClick={(e) => { e.preventDefault(); window.__openContactModal && window.__openContactModal(); }}>
            {th.cta} <Arrow className="arrow" />
          </a>
          <div className="hero__solutions-pills">
            {[
            ["01", T[lang].solutions.items[0].t, T[lang].routes.dc],
            ["02", T[lang].solutions.items[1].t, T[lang].routes.ro],
            ["03", T[lang].solutions.items[2].t, T[lang].routes.bz],
            ["04", T[lang].solutions.items[3].t, T[lang].routes.dp]].
            map(([n, label, href], i) =>
            <a key={n} href={href} className="hero__pill" style={{ animationDelay: `${0.3 + i * 0.12}s` }}>
                <span className="hero__pill-num mono">{n}</span>
                <span className="hero__pill-label">{label}</span>
                <Arrow size={10} className="hero__pill-arrow" />
              </a>
            )}
          </div>
        </div>
      </div>
    </section>);

}


/* ===== SOLUTIONS ===== */
function Solutions() {
  const lang = useContext(LangContext);
  const ts = T[lang].solutions;

  const r = T[lang].routes;
  const items = [
  { n: "01", t: ts.items[0].t, d: ts.items[0].d, img: IMG.sol1, href: r.dc, tag: ts.items[0].tag },
  { n: "02", t: ts.items[1].t, d: ts.items[1].d, img: IMG.sol2, href: r.ro, tag: ts.items[1].tag },
  { n: "03", t: ts.items[2].t, d: ts.items[2].d, img: IMG.sol3, href: r.bz, tag: ts.items[2].tag },
  { n: "04", t: ts.items[3].t, d: ts.items[3].d, img: IMG.sol4, href: r.dp, tag: ts.items[3].tag }];

  return (
    <section id="solutions" className="solutions-section">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head__left">
            <div className="sec-head__index"><span className="num">01</span><span>{ts.idx}</span></div>
            <h2>{ts.h2full}</h2>
          </div>
          <div className="sec-head__right">
            {ts.descText}
          </div>
        </div>

        <div className="sol-bento">

          {/* ── Left main: Podatkovni centri, 60% full height ── */}
          <a href={items[0].href} className="sol-bento__main">
            <div className="sol-bento__bg">
              <img src={items[0].img} alt={items[0].t} loading="lazy" />
              <div className="sol-bento__bg-overlay" />
            </div>
            <div className="sol-bento__main-body">
              <div className="sol-bento__top">
                <span className="sol-mono">{items[0].n}</span>
                <span className="sol-tag">{items[0].tag}</span>
              </div>
              <div className="sol-bento__foot">
                <div className="sol-bento__rule" />
                <div className="sol-bento__title-row">
                  <h3 className="sol-bento__main-title">{items[0].t}</h3>
                  <Arrow size={18} className="sol-bento__arrow" />
                </div>
                <p className="sol-bento__desc">{items[0].d}</p>
              </div>
            </div>
          </a>

          {/* ── Right: 3 stacked cards, 40% ── */}
          <div className="sol-bento__stack">
            {items.slice(1).map((it) => (
              <a key={it.n} href={it.href} className="sol-bento__row">
                <div className="sol-bento__bg">
                  <img src={it.img} alt={it.t} loading="lazy" />
                  <div className="sol-bento__bg-overlay" />
                </div>
                <div className="sol-bento__row-body">
                  <div className="sol-bento__top">
                    <span className="sol-mono">{it.n}</span>
                    <span className="sol-tag">{it.tag}</span>
                  </div>
                  <div className="sol-bento__foot">
                    <div className="sol-bento__rule" />
                    <div className="sol-bento__title-row">
                      <h3 className="sol-bento__row-title">{it.t}</h3>
                      <Arrow size={14} className="sol-bento__arrow" />
                    </div>
                    <p className="sol-bento__desc">{it.d}</p>
                  </div>
                </div>
              </a>
            ))}
          </div>

        </div>
      </div>
    </section>);

}

/* ===== DC FOCUS ===== */

const DC_HOME_SUBS_ALL = {
SI: [
  {
    id: "advisory", title: "Svetovanje & načrtovanje", subtitle: "Strategija in izvedljivost",
    img: "/images/dc-advisory.jpg",
    intro: "Vsaka investicija v podatkovni center se začne z jasnim načrtom. Skupaj z vami opredelimo zahteve, omejitve in cilje.",
    items: ["Analiza potreb in izvedljivosti", "Dimenzioniranje kapacitet in redundance", "Izbira stopnje TIER in arhitekture", "Okvirna ocena investicije"],
    benefit: "Odločate se z gotovostjo, ne z ugibanjem.",
  },
  {
    id: "design", title: "Projektiranje & inženiring", subtitle: "Tehnični projekt in načrti",
    img: "/images/dc-engineering.jpg",
    intro: "Projekt, ki ga dejansko lahko zgradite. Pokrivamo celoten obseg inženiringa: projektiranje vseh faz, gradbeno obrtniška dela, električne in strojne instalacije, IT infrastruktura, tehnološka oprema, napredni nadzorni sistemi — vse usklajeno v enem dokumentu.",
    items: ["Projektna dokumentacija za pridobitev gradbenega dovoljenja", "Izvedbeni načrti elektro in strojnih instalacij ter tehnologije", "Dimenzioniranje celotne oskrbne infrastrukture", "Usklajenost med vsemi strokami"],
    benefit: "En tim, en projekt, brez vrzeli med izvajalci.",
  },
  {
    id: "delivery", title: "Izvedba & gradbeni nadzor", subtitle: "Kakovost na terenu",
    img: "/images/dc-pristop.png",
    intro: "Na terenu smo vaše oči in ušesa. Skrbimo, da se projekt gradi točno tako, kot je bil zasnovan — v roku, v okviru proračuna in brez kompromisov pri kakovosti.",
    items: ["Koordinacija gradbenih, elektro, strojnih in IT izvajalcev.", "Neodvisni nadzor kakovosti izvedbe", "Sprotno reševanje tehničnih kolizij", "Poročanje o napredku in tveganjih"],
    benefit: "Manj presenečenj. Več nadzora.",
  },
  {
    id: "commissioning", title: "Zagon & prevzem", subtitle: "Testiranje in komisioning",
    img: "/images/dc-monitoring.jpg",
    intro: "Pred predajo preverimo vsak sistem — ločeno in v celoti. Dokumentirano, ponovljivo, brez improvizacij.",
    items: ["FAT in SAT testiranja po standardnih metodologijah", "Funkcionalno preverjanje napajanja, hlajenja in nadzornih sistemov", "Tehnična dokumentacija in PID načrti", "Usposabljanje operativnega osebja"],
    benefit: "Sistem, ki deluje od prvega dne.",
  },
  {
    id: "support", title: "Dolgoročna podpora & SLA", subtitle: "Vzdrževanje in monitoring",
    img: "/images/dc-ups.jpg",
    intro: "Infrastruktura, ki jo zgradimo, jo tudi vzdržujemo. Preventivni pregledi, hiter odziv in energijska optimizacija skozi celotno življenjsko dobo.",
    items: ["Preventivni servisni pregledi skladno pravilom stroke", "24/7 monitoring z eskalacijskimi postopki", "SLA pogodba z definiranimi odzivnimi časi", "Periodična analiza PUE in priporočila za optimizacijo"],
    benefit: "Infrastruktura, ki se z leti ne slabša, ampak izboljšuje.",
  },
],
EN: [
  {
    id: "advisory", title: "Advisory & planning", subtitle: "Strategy and feasibility",
    img: "/images/dc-advisory.jpg",
    intro: "Every data center investment begins with a clear plan. Together we define the requirements, constraints and goals.",
    items: ["Needs and feasibility analysis", "Capacity and redundancy sizing", "TIER level and architecture selection", "Indicative investment estimate"],
    benefit: "You decide with certainty, not guesswork.",
  },
  {
    id: "design", title: "Design & engineering", subtitle: "Technical design and plans",
    img: "/images/dc-engineering.jpg",
    intro: "A project you can actually build. We cover the full engineering scope: design across all phases, construction works, electrical and mechanical installations, IT infrastructure, technological equipment, advanced monitoring systems — all coordinated in one document.",
    items: ["Project documentation for obtaining the building permit", "Construction plans for electrical, mechanical and technology installations", "Sizing of the entire supply infrastructure", "Coordination across all disciplines"],
    benefit: "One team, one project, no gaps between contractors.",
  },
  {
    id: "delivery", title: "Execution & supervision", subtitle: "Quality on site",
    img: "/images/dc-pristop.png",
    intro: "On site we are your eyes and ears. We make sure the project is built exactly as designed — on time, on budget and with no compromise on quality.",
    items: ["Coordination of construction, electrical, mechanical and IT contractors.", "Independent quality control of execution", "On-the-fly resolution of technical clashes", "Reporting on progress and risks"],
    benefit: "Fewer surprises. More control.",
  },
  {
    id: "commissioning", title: "Commissioning & handover", subtitle: "Testing and commissioning",
    img: "/images/dc-monitoring.jpg",
    intro: "Before handover we test every system — individually and as a whole. Documented, repeatable, no improvisation.",
    items: ["FAT and SAT testing using standard methodologies", "Functional verification of power, cooling and monitoring systems", "Technical documentation and P&ID drawings", "Training of operational staff"],
    benefit: "A system that works from day one.",
  },
  {
    id: "support", title: "Long-term support & SLA", subtitle: "Maintenance and monitoring",
    img: "/images/dc-ups.jpg",
    intro: "The infrastructure we build, we also maintain. Preventive inspections, fast response and energy optimisation throughout its entire life cycle.",
    items: ["Preventive service inspections in line with professional standards", "24/7 monitoring with escalation procedures", "SLA contract with defined response times", "Periodic PUE analysis and optimisation recommendations"],
    benefit: "Infrastructure that improves with the years, rather than degrading.",
  },
],
DE: [
  {
    id: "advisory", title: "Beratung & Planung", subtitle: "Strategie und Machbarkeit",
    img: "/images/dc-advisory.jpg",
    intro: "Jede Investition in ein Rechenzentrum beginnt mit einem klaren Plan. Gemeinsam mit Ihnen definieren wir Anforderungen, Einschränkungen und Ziele.",
    items: ["Bedarfs- und Machbarkeitsanalyse", "Dimensionierung von Kapazität und Redundanz", "Auswahl von TIER-Stufe und Architektur", "Grobe Investitionsschätzung"],
    benefit: "Sie entscheiden mit Gewissheit, nicht mit Vermutungen.",
  },
  {
    id: "design", title: "Planung & Engineering", subtitle: "Technisches Projekt und Pläne",
    img: "/images/dc-engineering.jpg",
    intro: "Ein Projekt, das Sie tatsächlich bauen können. Wir decken den gesamten Engineering-Umfang ab: Planung aller Phasen, Bauarbeiten, elektrische und mechanische Installationen, IT-Infrastruktur, technologische Ausstattung, fortschrittliche Überwachungssysteme — alles abgestimmt in einem Dokument.",
    items: ["Projektdokumentation für die Baugenehmigung", "Ausführungspläne für Elektro-, Maschinen- und Technologieinstallationen", "Dimensionierung der gesamten Versorgungsinfrastruktur", "Abstimmung über alle Fachbereiche hinweg"],
    benefit: "Ein Team, ein Projekt, keine Lücken zwischen den Auftragnehmern.",
  },
  {
    id: "delivery", title: "Ausführung & Bauüberwachung", subtitle: "Qualität vor Ort",
    img: "/images/dc-pristop.png",
    intro: "Vor Ort sind wir Ihre Augen und Ohren. Wir sorgen dafür, dass das Projekt genau wie geplant gebaut wird — termingerecht, im Budget und ohne Qualitätskompromisse.",
    items: ["Koordination von Bau-, Elektro-, Maschinen- und IT-Auftragnehmern.", "Unabhängige Qualitätskontrolle der Ausführung", "Laufende Lösung technischer Kollisionen", "Berichterstattung über Fortschritt und Risiken"],
    benefit: "Weniger Überraschungen. Mehr Kontrolle.",
  },
  {
    id: "commissioning", title: "Inbetriebnahme & Übergabe", subtitle: "Tests und Commissioning",
    img: "/images/dc-monitoring.jpg",
    intro: "Vor der Übergabe prüfen wir jedes System — einzeln und im Ganzen. Dokumentiert, wiederholbar, ohne Improvisation.",
    items: ["FAT- und SAT-Tests nach Standardmethoden", "Funktionsprüfung von Strom, Kühlung und Überwachungssystemen", "Technische Dokumentation und R&I-Pläne", "Schulung des Betriebspersonals"],
    benefit: "Ein System, das vom ersten Tag an funktioniert.",
  },
  {
    id: "support", title: "Langfristiger Support & SLA", subtitle: "Wartung und Monitoring",
    img: "/images/dc-ups.jpg",
    intro: "Die Infrastruktur, die wir bauen, warten wir auch. Präventive Inspektionen, schnelle Reaktion und Energieoptimierung über den gesamten Lebenszyklus.",
    items: ["Präventive Serviceinspektionen nach den Regeln der Technik", "24/7-Monitoring mit Eskalationsverfahren", "SLA-Vertrag mit definierten Reaktionszeiten", "Periodische PUE-Analyse und Optimierungsempfehlungen"],
    benefit: "Infrastruktur, die sich über die Jahre verbessert, statt sich zu verschlechtern.",
  },
],
};
const DC_HOME_SUBS = DC_HOME_SUBS_ALL[(document.body && document.body.dataset && document.body.dataset.lang) || "SI"] || DC_HOME_SUBS_ALL.SI;

function DCHomeAccordion() {
  const lang = useContext(LangContext);
  const benefitsLabel = { SI: "PREDNOSTI", EN: "BENEFITS", DE: "VORTEILE" }[lang] || "PREDNOSTI";
  const [active, setActive] = React.useState(null);
  const [visibleImg, setVisibleImg] = React.useState(0);

  const switchTo = (i) => {
    if (i === active) { setActive(null); return; }
    setVisibleImg(i);
    setActive(i);
  };

  return (
    <div className="srv-layers__grid dc-home-accordion">
      {/* STICKY IMAGE */}
      <div className="srv-layers__visual">
        <div className="srv-layers__img-wrap">
          {DC_HOME_SUBS.map((sub, i) => (
            <img
              key={sub.img}
              src={sub.img}
              alt=""
              className={"srv-layers__img" + (i === visibleImg ? " is-active" : "")}
            />
          ))}
        </div>
      </div>
      {/* ACCORDION */}
      <div className="srv-layers__accordion">
        {DC_HOME_SUBS.map((sub, i) => {
          const isOpen = active === i;
          return (
            <div key={sub.id} className={"srv-layers__item" + (isOpen ? " is-open" : "")}>
              <button className="srv-layers__trigger" onClick={() => switchTo(i)}>
                <span className="srv-layers__trigger-num mono">{String(i + 1).padStart(2, "0")}</span>
                <span className="srv-layers__trigger-title">{sub.title}</span>
                <span className="srv-layers__trigger-icon" aria-hidden="true">
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.25">
                    <path d="M2 7h10M7 2v10" />
                    <path d="M2 7h10" />
                  </svg>
                </span>
              </button>
              <div className="srv-layers__body">
                <div className="srv-layers__body-inner">
                  <img src={sub.img} alt="" className="srv-layers__body-img" />
                  <p className="srv-layers__entry-intro">{sub.intro}</p>
                  <ul className="srv-layers__entry-list">
                    {sub.items.map((it, j) => <li key={j}>{it}</li>)}
                  </ul>
                  <div className="srv-layers__entry-benefit">
                    <span className="mono">{benefitsLabel}</span>
                    <span>{sub.benefit}</span>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DataCenters() {
  const lang = useContext(LangContext);
  const td = T[lang].dc;

  const kpis = td.kpis || [
    ["15+ LET", "življenjska doba"],
    ["≤ 1.3", "ciljni PUE"],
    ["TIER I-IV", "topologija"],
    ["24/7", "monitoring & SLA"],
  ];

  return (
    <section id="dc" className="dc-section">
      <div className="container">
        <div className="dc-section__head">
          <div className="dc-section__lead">
            <div className="sec-head__index">
              <span className="num">02</span><span>GLAVNA DEJAVNOST</span>
            </div>
            <h2 className="dc-section__h">
              <span>Podatkovni centri</span>
              <em>od koncepta do dolgoročnega partnerstva.</em>
            </h2>
          </div>
          <div className="dc-section__intro">
            <p>{td.lede}</p>
            <a href={T[lang].routes.dc} className="btn btn--primary dc-section__cta">
              {td.cta} <Arrow className="arrow" />
            </a>
          </div>
        </div>

        {/* KPI STRIP */}
        <div className="dc-section__kpis">
          {kpis.map(([n, l], i) => (
            <div className="dc-section__kpi" key={i}>
              <div className="dc-section__kpi-num">{n}</div>
              <div className="dc-section__kpi-lbl">{l}</div>
            </div>
          ))}
        </div>

        {/* ACCORDION + STICKY IMAGE */}
        <DCHomeAccordion />
      </div>
    </section>);

}

/* ===== TRUST / LOGOS ===== */
function Trust() {
  const lang = useContext(LangContext);
  const tt = T[lang].trust;
  const cells = tt.clients || [
  ["Krka", "PHARMA"], ["Lek", "PHARMA"], ["NLB", "FINANCE"],
  ["SID Banka", "FINANCE"], ["Triglav", "INSURANCE"], ["Petrol", "ENERGY"],
  ["Pošta Slovenije", "PUBLIC"], ["DARS", "PUBLIC"],
  ["Iskratel", "TELCO"], ["UKC Ljubljana", "HEALTH"]];

  // duplicate for seamless loop
  const marqueeItems = [...cells, ...cells];

  return (
    <section>
      <div className="container">
        <div className="sec-head">
          <div className="sec-head__left">
            <div className="sec-head__index"><span className="num">03</span><span>{tt.idx}</span></div>
            <h2>{tt.h2}</h2>
          </div>
          <div className="sec-head__right"></div>
        </div>
      </div>
      <div className="logos-marquee">
        <div className="logos-marquee__track">
          {marqueeItems.map(([n, k], i) =>
          <div className="logos-marquee__item" key={i}>
              <span className="logos-marquee__name">{n}</span>
              <span className="logos-marquee__cat mono">/{k}</span>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ===== PROCESS, editorial collage ===== */
function Process() {
  const lang = useContext(LangContext);
  const sectionRef = React.useRef(null);
  const [scrollY, setScrollY] = React.useState(0);
  const [revealed, setRevealed] = React.useState(false);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;

    const onScroll = () => {
      const rect = section.getBoundingClientRect();
      const rel = -rect.top;
      setScrollY(rel);
      if (rect.top < window.innerHeight * 0.75) setRevealed(true);
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // parallax: each image gets translateY + slight rotate drift
  const transform = (speed, rotSpeed, baseRot) =>
  `translateY(${scrollY * speed}px) rotate(${baseRot + scrollY * rotSpeed}deg)`;

  // Left images drift UP, right images drift DOWN — intentional "curtain opening" parallax
  const images = [
  // 1. Large portrait — left top, drifts UP slowly
  { src: "/images/data-centers/_ABP7614.webp",
    w: 500, aspect: "3/4", top: "0%", left: "-2%", rot: -1.5, speed: -0.13, rotSpeed: 0.0005, z: 1 },

  // 2. Landscape — left bottom, drifts UP faster
  { src: "/images/dc-engineering.jpg",
    w: 310, aspect: "4/3", bottom: "2%", left: "3%", rot: 1.8, speed: -0.22, rotSpeed: -0.0006, z: 2 },

  // 3. Small portrait — right center, drifts DOWN
  { src: "/images/dc-monitoring.jpg",
    w: 235, aspect: "3/4", top: "30%", right: "3%", rot: 2.2, speed: 0.24, rotSpeed: 0.0006, z: 3 },

  // 4. Wide landscape — right top, drifts DOWN slowly
  { src: "/images/dc-pristop.png",
    w: 470, aspect: "16/10", top: "0%", right: "-1%", rot: 1.2, speed: 0.13, rotSpeed: -0.0005, z: 1 },

  // 5. Medium — right bottom, drifts DOWN
  { src: "/images/data-centers/_ABP7570.webp",
    w: 370, aspect: "4/3", bottom: "1%", right: "2%", rot: -1.5, speed: 0.19, rotSpeed: 0.0006, z: 2 }];


  return (
    <section ref={sectionRef} className={"collab-section" + (revealed ? " is-revealed" : "")}>

      {/* background graphic */}
      <div className="collab-bg" aria-hidden="true">
        <svg className="collab-bg__grid" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
          <defs>
            <pattern id="collab-grid" x="0" y="0" width="60" height="60" patternUnits="userSpaceOnUse">
              <path d="M 60 0 L 0 0 0 60" fill="none" stroke="currentColor" strokeWidth="0.5"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#collab-grid)" />
        </svg>
        <div className="collab-bg__glow" />
      </div>

      {/* floating images */}
      {images.map((img, i) => {
        const posStyle = {
          width: img.w,
          aspectRatio: img.aspect,
          ...(img.top !== undefined && { top: img.top }),
          ...(img.bottom !== undefined && { bottom: img.bottom }),
          ...(img.left !== undefined && { left: img.left }),
          ...(img.right !== undefined && { right: img.right }),
          transform: transform(img.speed, img.rotSpeed, img.rot),
          zIndex: img.z,
          '--reveal-delay': `${i * 120}ms`
        };
        return (
          <div key={i} className="collab-img" style={posStyle}>
            <img src={img.src} alt="" loading="lazy" />
          </div>);

      })}

      {/* centre statement */}
      <div className="collab-center">
        <p className="collab-statement">
          {T[lang].collab.line1}<br />
          <em>{T[lang].collab.line2}</em>
        </p>
        <a href="#contact" className="collab-cta" onClick={(e) => { e.preventDefault(); window.__openContactModal && window.__openContactModal(); }}>
          {T[lang].collab.cta} <Arrow size={13} className="arrow" />
        </a>
      </div>
    </section>);

}

/* ===== PROCESS PARALLAX ===== */
function ProcessParallax() {
  const lang = useContext(LangContext);
  const sectionRef = React.useRef(null);
  const [offset, setOffset] = React.useState(0);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    const onScroll = () => {
      const rect = section.getBoundingClientRect();
      setOffset(-rect.top * 0.28);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section ref={sectionRef} className="proc-par">
      <div className="proc-par__bg" style={{ transform: `translateY(${offset}px)` }} />
      <div className="proc-par__scrim" />
      <div className="container proc-par__inner">
        <div className="proc-par__statement">
          <p>
            {T[lang].collab.line1}<br />
            <em>{T[lang].collab.line2}</em>
          </p>
          <a href="#contact" className="collab-cta proc-par__cta"
            onClick={e => { e.preventDefault(); window.__openContactModal && window.__openContactModal(); }}>
            {T[lang].collab.cta} <Arrow size={13} className="arrow" />
          </a>
        </div>
      </div>
    </section>
  );
}

/* ===== REFERENCES PREVIEW ===== */
function References() {
  const lang = useContext(LangContext);
  const tr = T[lang].refs;
  const refsRef = React.useRef(null);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const el = refsRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => {entries.forEach((e) => {if (e.isIntersecting) {setVisible(true);obs.disconnect();}});},
      { threshold: 0.15 }
    );
    obs.observe(el);
    const fallback = setTimeout(() => {
      const rect = el.getBoundingClientRect();
      if (rect.top < window.innerHeight + 100) {setVisible(true);}
    }, 400);
    return () => {obs.disconnect();clearTimeout(fallback);};
  }, []);

  const projects = tr.items;

  return (
    <section id="refs">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head__left">
            <div className="sec-head__index"><span className="num">04</span><span>{tr.idx}</span></div>
            <h2>{tr.h2}</h2>
          </div>
          <div className="sec-head__right"></div>
        </div>
        <div className={"refs refs--reveal" + (visible ? " is-visible" : "")} ref={refsRef}>
          {projects.map(([n, t, m, y], i) =>
          <a href="#" className="ref-row" key={n} style={{ "--ref-i": i }}>
              <div className="ref-row__num">{n}</div>
              <div className="ref-row__title">{t}</div>
              <div className="ref-row__meta">{m}</div>
              <div className="ref-row__year">{y}</div>
              <Arrow size={12} className="ref-row__arrow" />
            </a>
          )}
        </div>
        <div style={{ marginTop: 40 }}>
          <a href={T[lang].routes.references} className="btn">{tr.cta} <Arrow className="arrow" /></a>
        </div>
      </div>
    </section>);
}

/* ===== CONTACT (multi-step) ===== */
/* Shared submit → WP endpoint (antispam + email to support@svsdev.com).
   Rejects with an Error carrying the server message so callers can show it. */
function submitContactForm(payload) {
  if (!window.AdvantWP || !window.AdvantWP.wpSubmit) {
    return Promise.reject(new Error("Obrazec trenutno ni na voljo. Poskusite kasneje."));
  }
  return window.AdvantWP.wpSubmit("contact", payload);
}

function Contact({ idx = "05" }) {
  const lang = useContext(LangContext);
  const tc = T[lang].contact;
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    area: "",
    name: "",
    company: "",
    email: "",
    phone: "",
    message: "",
    hp: "" // honeypot (bots fill this; humans never see it)
  });
  const [sending, setSending] = useState(false);
  const [submitErr, setSubmitErr] = useState("");
  const mountedAt = useRef(Date.now()); // antispam: min dwell time

  const total = 3;
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const canNext = step === 1 ? !!data.area :
  step === 2 ? data.name && data.company && data.email && data.message :
  true;

  const submitContact = () => {
    if (sending) return;
    setSubmitErr("");
    // Client-side honeypot short-circuit (real check is server-side too)
    if (data.hp) { setStep(4); return; }
    setSending(true);
    submitContactForm({
      form: "contact",
      area: areas.find((a) => a.id === data.area)?.name || data.area,
      name: data.name, company: data.company, email: data.email,
      phone: data.phone, message: data.message,
      website: data.hp, t: mountedAt.current, lang,
      source: typeof location !== "undefined" ? location.pathname : ""
    }).then(() => { setSending(false); setStep(4); })
      .catch((err) => { setSending(false); setSubmitErr(err.message || tc.sendErr); });
  };

  const areas = tc.areas;


  return (
    <section id="contact">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head__left">
            <div className="sec-head__index"><span className="num">{idx}</span><span>{tc.idx}</span></div>
            <h2>{tc.h2[0]}<br />{tc.h2[1]}</h2>
          </div>
          <div className="sec-head__right">{tc.desc}</div>
        </div>
        <div className="contact">
          <div className="contact__aside">
            <div className="contact__aside-meta">
              <div className="contact__meta-row">
                <span className="label">{tc.meta.email}</span>
                <a href={"mailto:" + tc.meta.emailVal} className="val contact__meta-link">{tc.meta.emailVal}</a>
              </div>
              <div className="contact__meta-row">
                <span className="label">{tc.meta.phone}</span>
                <a href={"tel:" + tc.meta.phoneVal.replace(/\s/g, "")} className="val contact__meta-link">{tc.meta.phoneVal}</a>
              </div>
              <div className="contact__meta-row">
                <span className="label">{tc.meta.fax}</span>
                <span className="val">{tc.meta.faxVal}</span>
              </div>
              <div className="contact__meta-row">
                <span className="label">{tc.meta.address}</span>
                <a href={tc.meta.mapsUrl} target="_blank" rel="noopener" className="val contact__meta-link">{tc.meta.addressVal}</a>
              </div>
              <div className="contact__meta-row">
                <span className="label">Pisarne</span>
                <span className="val">{tc.meta.hoursVal || <>Pon–Pet: 8:00–16:00<br />Sob, ned, prazniki: zaprto</>}</span>
              </div>
              <div className="contact__meta-row">
                <span className="label">Skladišče</span>
                <span className="val">Pon–Pet: 7:00–15:00<br />Sob, ned, prazniki: zaprto</span>
              </div>
              <div className="contact__meta-row">
                <span className="label">{tc.meta.response}</span>
                <span className="val">{tc.meta.responseVal}</span>
              </div>
            </div>
          </div>

          <div className="form">
            <div className="form__progress">
              <span className="form__step-label">
                {step <= total && <span className="dot" />}
                {step <= total ? `Korak ${step} / ${total}` : "Poslano"}
              </span>
              <div className="form__progress-track">
                <div className="form__progress-fill" style={{ width: `${Math.min(step, total) / total * 100}%` }} />
              </div>
              <span>{
                step === 1 ? "Področje" :
                step === 2 ? "Sporočilo" :
                step === 3 ? "Pregled" : "-"
                }</span>
            </div>

            {step === 1 &&
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <div>
                  <h3>{tc.step1h}</h3><p className="form__hint">{tc.step1sub}</p>
                </div>
                <div className="choices">
                  {areas.map((a) =>
                <button
                  key={a.id}
                  className={"choice " + (data.area === a.id ? "is-active" : "")}
                  onClick={() => set("area", a.id)}>
                  
                      {a.name}
                      <span className="meta">{a.code}</span>
                    </button>
                )}
                </div>
              </div>
            }

            {step === 2 &&
            <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
                <div>
                  <h3>{tc.step2h}</h3><p className="form__hint">{tc.step2sub}</p>
                </div>
                <div className="field">
                  <label>{tc.fields.msg}</label>
                  <textarea
                  placeholder={tc.ph.msg}
                  value={data.message}
                  onChange={(e) => set("message", e.target.value)} />

                </div>
                <div className="field-grid">
                  <div className="field">
                    <label>{tc.fields.name}</label>
                    <input type="text" value={data.name} onChange={(e) => set("name", e.target.value)} placeholder={tc.ph.name} />
                  </div>
                  <div className="field">
                    <label>{tc.fields.company}</label>
                    <input type="text" value={data.company} onChange={(e) => set("company", e.target.value)} placeholder={tc.ph.company} />
                  </div>
                  <div className="field">
                    <label>{tc.fields.email}</label>
                    <input type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder={tc.ph.email} />
                  </div>
                  <div className="field">
                    <label>{tc.fields.phone}</label>
                    <input type="tel" value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder={tc.ph.phone} />
                  </div>
                </div>
                {/* honeypot — skrito polje za bote, ljudje ga ne vidijo */}
                <input type="text" tabIndex={-1} autoComplete="off" aria-hidden="true"
                  value={data.hp} onChange={(e) => set("hp", e.target.value)}
                  style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
              </div>
            }

            {step === 3 &&
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <div>
                  <h3>{tc.step3h}</h3><p className="form__hint">{tc.step3sub}</p>
                </div>
                <div className="summary">
                  <div className="summary__row"><span className="k">{tc.summary.area}</span><span className="v">{areas.find((a) => a.id === data.area)?.name || "-"}</span></div>
                  <div className="summary__row"><span className="k">{tc.summary.contact}</span><span className="v">{data.name} · {data.company}</span></div>
                  <div className="summary__row"><span className="k">{tc.summary.email}</span><span className="v">{data.email}</span></div>
                  {data.phone && <div className="summary__row"><span className="k">{tc.summary.phone}</span><span className="v">{data.phone}</span></div>}
                  <div className="summary__row"><span className="k">{tc.summary.msg}</span><span className="v">{data.message}</span></div>
                </div>
              </div>
            }

            {step === 4 &&
            <div className="form__success">
                <div className="form__success-mark" />
                <h3>{tc.successTitle}</h3>
                <p>{tc.successSub[0]}<strong>{areas.find((a) => a.id === data.area)?.name}</strong>{tc.successSub[1]}<strong>{data.email}</strong>{tc.successSub[2]}</p>
              </div>
            }

            {step <= total &&
            <>
              {submitErr && <p className="form__hint" style={{ color: "#e5484d", marginBottom: 8 }}>{submitErr}</p>}
              <div className="form__actions">
                <button className="link-btn" disabled={step === 1 || sending} onClick={() => setStep((s) => Math.max(1, s - 1))}>{tc.back}</button>
                {step < total ?
              <button className="btn btn--primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? "pointer" : "not-allowed" }} onClick={() => canNext && setStep((s) => s + 1)}>{tc.next} <Arrow className="arrow" /></button> :

              <button className="btn btn--primary" disabled={sending} style={{ opacity: sending ? 0.5 : 1, cursor: sending ? "wait" : "pointer" }} onClick={submitContact}>{sending ? tc.sending : tc.send} <Arrow className="arrow" /></button>
              }
              </div>
            </>
            }
          </div>
        </div>
      </div>
    </section>);

}

/* ===== FOOTER ===== */
function Footer() {
  const lang = useContext(LangContext);
  const tf = T[lang].footer;
  return (
    <footer>
      <div className="container">
        <div className="foot-wordmark" aria-hidden="true">
          <div className="foot-wordmark__track">
            {[...Array(6)].map((_, i) =>
            <span key={i} className="foot-wordmark__item">advant</span>
            )}
          </div>
        </div>
        <div className="foot">
          <div className="foot__brand">
            <div className="logo" aria-label="Advant">
              <img src="/assets/advant-logo-hires.png" alt="Advant" />
            </div>
            <p>{tf.desc}</p>
            <div className="mono" style={{ color: "var(--ink-4)", fontSize: 11 }}>
              SI · LJUBLJANA · EST.&nbsp;1998
            </div>
          </div>
          <div className="foot__col">
            <h5>{tf.services}</h5>
            <a href={T[lang].routes.dc}>{tf.links.dc}</a>
            <a href={T[lang].routes.ro}>{tf.links.kab}</a>
            <a href={T[lang].routes.bz}>{tf.links.wifi}</a>
            <a href={T[lang].routes.dp}>{tf.links.pod}</a>
          </div>
          <div className="foot__col">
            <h5>{tf.company}</h5>
            <a href={T[lang].routes.about}>{tf.links.about}</a>
            <a href={T[lang].routes.references}>{tf.links.ref}</a>
            <a href={T[lang].routes.news}>{tf.links.news}</a>
            {/* Kariera začasno skrita iz footerja */}
            {/* <a href={T[lang].routes.careers}>{tf.links.career}</a> */}
          </div>
          <div className="foot__col">
            <h5>{tf.contact}</h5>
            <a href="#contact" onClick={(e) => { e.preventDefault(); window.__openContactModal && window.__openContactModal(); }}>{tf.links.contactLink}</a>
            <a href={"mailto:" + tf.emailVal}>{tf.emailVal}</a>
            <a href={"tel:" + (tf.phoneVal || "").replace(/\s/g, "")}>{tf.phoneVal}</a>
          </div>
        </div>
        <div className="foot__bottom">
          <span>© 2026 Advant d.o.o.</span>
          <span>Izvedba <a href="https://svs-digital.com" target="_blank" rel="noopener noreferrer" style={{ color: "var(--hot)" }}>SVS Digital</a></span>
        </div>
      </div>
    </footer>);

}

/* ===== CONTACT MODAL ===== */
function ContactModal({ open, onClose, initialArea = "" }) {
  const lang = useContext(LangContext) || "SI";
  const tc = T[lang] ? T[lang].contact : T["SI"].contact;
  const [step, setStep] = useState(1);
  const [data, setData] = useState({ area: initialArea, name: "", company: "", email: "", phone: "", message: "", hp: "" });
  const [sending, setSending] = useState(false);
  const [submitErr, setSubmitErr] = useState("");
  const mountedAt = useRef(Date.now());
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const total = 3;
  const areas = tc.areas;
  const canNext = step === 1 ? !!data.area : step === 2 ? data.name && data.company && data.email && data.message : true;

  const submitContact = () => {
    if (sending) return;
    setSubmitErr("");
    if (data.hp) { setStep(4); return; }
    setSending(true);
    submitContactForm({
      form: "contact",
      area: areas.find((a) => a.id === data.area)?.name || data.area,
      name: data.name, company: data.company, email: data.email,
      phone: data.phone, message: data.message,
      website: data.hp, t: mountedAt.current, lang,
      source: typeof location !== "undefined" ? location.pathname : ""
    }).then(() => { setSending(false); setStep(4); })
      .catch((err) => { setSending(false); setSubmitErr(err.message || tc.sendErr); });
  };

  // reset form (keep initialArea) each time modal opens
  useEffect(() => {
    if (open) {
      setStep(1);
      setData({ area: initialArea, name: "", company: "", email: "", phone: "", message: "", hp: "" });
      setSending(false);
      setSubmitErr("");
      mountedAt.current = Date.now();
    }
  }, [open]);

  // lock body scroll when open
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => {document.body.style.overflow = "";};
  }, [open]);

  // close on Escape
  useEffect(() => {
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div className="cmodal-backdrop" onClick={onClose}>
      <div className="cmodal" onClick={(e) => e.stopPropagation()}>
        {/* close btn */}
        <button className="cmodal__close" onClick={onClose} aria-label="Zapri">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.25">
            <path d="M2 2l10 10M12 2L2 12" />
          </svg>
        </button>

        {/* progress */}
        <div className="cmodal__progress">
          <span className="cmodal__step-label mono">
            {step <= total ? <><span className="dot" />Korak {step} / {total}</> : "Poslano"}
          </span>
          <div className="cmodal__progress-track">
            <div className="cmodal__progress-fill" style={{ width: `${Math.min(step, total) / total * 100}%` }} />
          </div>
        </div>

        {/* STEP 1 */}
        {step === 1 &&
        <div className="cmodal__body">
            <h2 className="cmodal__h">{tc.step1h}</h2>
            <p className="cmodal__sub">{tc.step1sub}</p>
            <div className="cmodal__choices">
              {areas.map((a) =>
            <button key={a.id}
            className={"cmodal__choice" + (data.area === a.id ? " is-active" : "")}
            onClick={() => set("area", a.id)}>
                  {a.name}<span className="mono">{a.code}</span>
                </button>
            )}
            </div>
          </div>
        }

        {/* STEP 2 */}
        {step === 2 &&
        <div className="cmodal__body">
            <h2 className="cmodal__h">{tc.step2h}</h2>
            <p className="cmodal__sub">{tc.step2sub}</p>
            <div className="cmodal__field">
              <label>{tc.fields.msg}</label>
              <textarea placeholder={tc.ph.msgShort} value={data.message} onChange={(e) => set("message", e.target.value)} rows={3} />
            </div>
            <div className="cmodal__grid">
              <div className="cmodal__field"><label>{tc.fields.name}</label><input type="text" value={data.name} onChange={(e) => set("name", e.target.value)} placeholder={tc.ph.name} /></div>
              <div className="cmodal__field"><label>{tc.fields.company}</label><input type="text" value={data.company} onChange={(e) => set("company", e.target.value)} placeholder={tc.ph.company} /></div>
              <div className="cmodal__field"><label>{tc.fields.email}</label><input type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder={tc.ph.email} /></div>
              <div className="cmodal__field"><label>{tc.fields.phone}</label><input type="tel" value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder={tc.ph.phone} /></div>
            </div>
            {/* honeypot — skrito polje za bote */}
            <input type="text" tabIndex={-1} autoComplete="off" aria-hidden="true"
              value={data.hp} onChange={(e) => set("hp", e.target.value)}
              style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
          </div>
        }

        {/* STEP 3 */}
        {step === 3 &&
        <div className="cmodal__body">
            <h2 className="cmodal__h">{tc.step3h}</h2>
            <p className="cmodal__sub">{tc.step3sub}</p>
            <div className="cmodal__summary">
              {[[tc.summary.area, areas.find((a) => a.id === data.area)?.name || "-"], [tc.summary.contact, `${data.name} · ${data.company}`], [tc.summary.email, data.email], data.phone && [tc.summary.phone, data.phone], [tc.summary.msg, data.message]].filter(Boolean).map(([k, v]) =>
            <div className="cmodal__summary-row" key={k}><span className="k mono">{k}</span><span className="v">{v}</span></div>
            )}
            </div>
          </div>
        }

        {/* STEP 4, success */}
        {step === 4 &&
        <div className="cmodal__body cmodal__success">
            <div className="cmodal__success-mark" />
            <h2 className="cmodal__h">{tc.successTitle}</h2>
            <p className="cmodal__sub">{tc.successSub[0]}<strong>{areas.find((a) => a.id === data.area)?.name}</strong>{tc.successSub[1]}<strong>{data.email}</strong>{tc.successSub[2]}</p>
          </div>
        }

        {/* actions */}
        {step <= total &&
        <div className="cmodal__actions" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
            {submitErr && <p className="cmodal__sub" style={{ color: "#e5484d", margin: 0 }}>{submitErr}</p>}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
            <button className="link-btn" disabled={step === 1 || sending} onClick={() => setStep((s) => Math.max(1, s - 1))}>{tc.back}</button>
            {step < total ?
          <button className="btn btn--primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? "pointer" : "not-allowed" }} onClick={() => canNext && setStep((s) => s + 1)}>{tc.next} <Arrow className="arrow" /></button> :
          <button className="btn btn--primary" disabled={sending} style={{ opacity: sending ? 0.5 : 1, cursor: sending ? "wait" : "pointer" }} onClick={submitContact}>{sending ? tc.sending : tc.send} <Arrow className="arrow" /></button>
          }
            </div>
          </div>
        }
      </div>
    </div>);

}

/* shared hook to open contact modal from anywhere */
window.__openContactModal = null;
function AmbientOrb() {
  const orbRef = React.useRef(null);
  React.useEffect(() => {
    const el = orbRef.current;
    if (!el) return;
    el.style.left = '50%';
    el.style.top = '40%';
    const onMove = (e) => {
      el.style.left = e.clientX + 'px';
      el.style.top = e.clientY + 'px';
    };
    el.classList.add('is-active');
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => {
      window.removeEventListener('mousemove', onMove);
    };
  }, []);
  return <div className="ambient-orb" ref={orbRef} aria-hidden="true" />;
}

function ScrollProgress() {
  const fillRef = React.useRef(null);
  React.useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      const pct = max > 0 ? h.scrollTop / max * 100 : 0;
      if (fillRef.current) fillRef.current.style.width = pct + "%";
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);
  return (
    <div className="scroll-progress" aria-hidden="true">
      <div className="scroll-progress__fill" ref={fillRef} />
    </div>);

}

function App() {
  const [lang, setLang] = useState((document.body && document.body.dataset.lang) || "SI");
  const [modalOpen, setModalOpen] = useState(false);
  const [_wpTick, setWpTick] = useState(0); // bump to trigger re-render after WP data loaded

  /* ── Load WP content on mount ───────────────────────────────────── */
  useEffect(() => {
    const { wpOptions, wpPosts, gs, rep, repF, decode } = window.AdvantWP || {};
    if (!wpOptions) return;

    Promise.all([wpOptions('global'), wpOptions('homepage')])
      .then(([g, hp]) => {
        /* Helper: apply a field if non-empty */
        const set = (obj, key, val) => { if (val) obj[key] = decode(val); };
        /* Helper: apply a field even when empty (WP-authoritative → "" means "").
           Only skipped when the field is absent (WP not loaded / key missing). */
        const setRaw = (obj, key, src, srcKey) => {
          const v = src ? src[srcKey] : undefined;
          if (v !== undefined && v !== null) obj[key] = decode(String(v));
        };

        ['SI', 'EN', 'DE'].forEach(LANG => {
          const l = LANG.toLowerCase();
          const tl = T[LANG];

          /* ── Global: nav ── */
          set(tl.nav, 'resitve',   gs(g, `g_nav_resitve_${l}`));
          set(tl.nav, 'opodjetju', gs(g, `g_nav_opodjetju_${l}`));
          set(tl.nav, 'reference', gs(g, `g_nav_reference_${l}`));
          set(tl.nav, 'novice',    gs(g, `g_nav_novice_${l}`));
          set(tl.nav, 'kontakt',   gs(g, `g_nav_kontakt_${l}`));

          /* ── Global: mega meni (Rešitve dropdown) — empty allowed ── */
          setRaw(tl.nav, 'featEyebrow', g, `g_mega_feat_eyebrow_${l}`);
          setRaw(tl.nav, 'featTitle',   g, `g_mega_feat_title_${l}`);
          setRaw(tl.nav, 'featDesc',    g, `g_mega_feat_desc_${l}`);
          setRaw(tl.nav, 'megaSubDc',   g, `g_mega_sub_dc_${l}`);
          setRaw(tl.nav, 'megaSubRo',   g, `g_mega_sub_ro_${l}`);
          setRaw(tl.nav, 'megaSubWf',   g, `g_mega_sub_wf_${l}`);
          setRaw(tl.nav, 'megaSubDp',   g, `g_mega_sub_dp_${l}`);

          /* ── Global: contact info (shared across all pages) ── */
          set(tl.contact.meta, 'emailVal',   gs(g, `g_contact_email_${l}`));
          set(tl.contact.meta, 'phoneVal',   gs(g, `g_contact_phone_${l}`));
          set(tl.contact.meta, 'faxVal',     gs(g, `g_contact_fax_${l}`));
          set(tl.contact.meta, 'addressVal', gs(g, `g_contact_address_${l}`));
          set(tl.contact.meta, 'mapsUrl',    gs(g, `g_contact_maps_${l}`));
          set(tl.contact.meta, 'hoursVal',   gs(g, `g_contact_hours_${l}`));
          set(tl.footer,       'emailVal',   gs(g, `g_contact_email_${l}`));
          set(tl.footer,       'phoneVal',   gs(g, `g_contact_phone_${l}`));

          /* ── Global: footer labels ── */
          set(tl.footer, 'desc',    gs(g, `g_footer_desc_${l}`));
          set(tl.footer.links, 'dc',          gs(g, `g_footer_link_dc_${l}`));
          set(tl.footer.links, 'kab',         gs(g, `g_footer_link_kab_${l}`));
          set(tl.footer.links, 'wifi',        gs(g, `g_footer_link_wifi_${l}`));
          set(tl.footer.links, 'pod',         gs(g, `g_footer_link_pod_${l}`));
          set(tl.footer.links, 'about',       gs(g, `g_footer_link_about_${l}`));
          set(tl.footer.links, 'ref',         gs(g, `g_footer_link_ref_${l}`));
          set(tl.footer.links, 'news',        gs(g, `g_footer_link_news_${l}`));
          set(tl.footer.links, 'career',      gs(g, `g_footer_link_career_${l}`));
          set(tl.footer.links, 'contactLink', gs(g, `g_footer_link_contact_${l}`));
          set(tl.footer.links, 'privacy',     gs(g, `g_footer_link_privacy_${l}`));
          set(tl.footer.links, 'cookies',     gs(g, `g_footer_link_cookies_${l}`));
          set(tl.footer.links, 'legal',       gs(g, `g_footer_link_legal_${l}`));

          /* ── Homepage: hero ── */
          set(tl.hero, 'yearsNum',   gs(hp, `hp_hero_years_num_${l}`));
          set(tl.hero, 'years',      gs(hp, `hp_hero_years_label_${l}`));
          set(tl.hero, 'est',        gs(hp, `hp_hero_est_${l}`));
          set(tl.hero, 'coords',     gs(hp, `hp_hero_coords_${l}`));
          set(tl.hero, 'city',       gs(hp, `hp_hero_city_${l}`));
          set(tl.hero, 'h1Lead',     gs(hp, `hp_hero_h1_1_${l}`));
          set(tl.hero, 'h1Tail',     gs(hp, `hp_hero_h1_2_${l}`));
          set(tl.hero, 'sub',        gs(hp, `hp_hero_sub_${l}`));
          set(tl.hero, 'rotateLead', gs(hp, `hp_hero_rotate_lead_${l}`));
          set(tl.hero, 'cta',        gs(hp, `hp_hero_cta_${l}`));
          const rotWords = repF(hp, `hp_${l}_hero_rotate`, 'word');
          if (rotWords.length) tl.hero.rotateWords = rotWords;

          /* ── Homepage: solutions section ── */
          set(tl.solutions, 'idx',      gs(hp, `hp_sol_kicker_${l}`));
          set(tl.solutions, 'h2full',   gs(hp, `hp_sol_h2_${l}`));
          set(tl.solutions, 'descText', gs(hp, `hp_sol_desc_${l}`));
          for (let i = 1; i <= 4; i++) {
            const it = tl.solutions.items[i - 1];
            if (!it) continue;
            set(it, 't',   gs(hp, `hp_sol${i}_title_${l}`));
            set(it, 'd',   gs(hp, `hp_sol${i}_desc_${l}`));
            set(it, 'tag', gs(hp, `hp_sol${i}_tag_${l}`));
            const img = gs(hp, `hp_sol${i}_img_${l}`);
            if (img) IMG[`sol${i}`] = img;
          }

          /* ── Homepage: trust section ── */
          set(tl.trust, 'idx', gs(hp, `hp_trust_kicker_${l}`));
          set(tl.trust, 'h2',  gs(hp, `hp_trust_title_${l}`));
          const clients = rep(hp, `hp_${l}_trust_clients`);
          if (clients.length) {
            tl.trust.clients = clients.map(c => [c.name || '', (c.category || '').toUpperCase()]);
          }

          /* ── Homepage: DC section ── */
          set(tl.dc, 'lede', gs(hp, `hp_dc_lede_${l}`));
          set(tl.dc, 'cta',  gs(hp, `hp_dc_cta_${l}`));

          /* ── Homepage: references preview ── */
          set(tl.refs, 'idx', gs(hp, `hp_refs_kicker_${l}`));
          set(tl.refs, 'h2',  gs(hp, `hp_refs_h2_${l}`));
          set(tl.refs, 'cta', gs(hp, `hp_refs_cta_${l}`));

          /* ── Homepage: collab / process parallax ── */
          set(tl.collab, 'line1', gs(hp, `hp_collab_title_1_${l}`));
          set(tl.collab, 'line2', gs(hp, `hp_collab_title_2_${l}`));
          set(tl.collab, 'cta',   gs(hp, `hp_collab_cta_${l}`));
        });

        /* ── Homepage: DC KPIs (lang-independent display values) ── */
        ['SI','EN','DE'].forEach(LANG => {
          const l = LANG.toLowerCase();
          const kpisWP = [];
          for (let i = 1; i <= 4; i++) {
            const n = gs(hp, `hp_dc_kpi${i}_num_${l}`);
            const lb = gs(hp, `hp_dc_kpi${i}_label_${l}`);
            if (n && lb) kpisWP.push([n, lb]);
          }
          if (kpisWP.length === 4) T[LANG].dc.kpis = kpisWP;
        });

        /* ── DC process accordion (for homepage DataCenters + DC service page) ── */
        const procRows = rep(hp, 'hp_si_dc_process') /* fallback: try dc options below */;
        /* We'll update DC_HOME_SUBS via the dc options fetch instead (done in storitev.jsx) */

        setWpTick(t => t + 1);
      })
      .catch(e => {
        console.warn('[AdvantWP] homepage load failed, using fallback data.', e);
        window.AdvantWP && window.AdvantWP.hidePreloader();
      });
  }, []);

  useEffect(() => {
    if (_wpTick > 0) window.AdvantWP && window.AdvantWP.hidePreloader();
  }, [_wpTick]);

  /* Fallback: hide preloader after 5 s even if WP never responds */
  useEffect(() => {
    const t = setTimeout(() => window.AdvantWP && window.AdvantWP.hidePreloader(), 3000);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    window.__openContactModal = () => setModalOpen(true);
    return () => {window.__openContactModal = null;};
  }, []);

  useEffect(() => {
    const setHeroH = () => {
      const hero = document.querySelector('.hero');
      if (hero) {
        document.documentElement.style.setProperty('--hero-h', hero.offsetHeight + 'px');
      }
    };
    setHeroH();
    window.addEventListener('resize', setHeroH, { passive: true });
    return () => window.removeEventListener('resize', setHeroH);
  }, []);

  return (
    <LangContext.Provider value={lang}>
      <ScrollProgress />
      <AmbientOrb />
      <div className="ambient-texture" aria-hidden="true" />
      <Header />
      <Hero />
      <Solutions />
      <Trust />
      {/* <Process /> */}
      <ProcessParallax />
      {/* <References /> */}
      <Contact />
      <Footer />
      <ContactModal open={modalOpen} onClose={() => setModalOpen(false)} />
    </LangContext.Provider>);

}

// Expose for other pages
Object.assign(window, { Arrow, Header, Footer, AmbientOrb, ContactModal, LangContext, T });

class ErrorBoundary extends React.Component {
  constructor(p) { super(p); this.state = { err: null }; }
  static getDerivedStateFromError(e) { return { err: e }; }
  componentDidCatch(e) {
    window.AdvantWP && window.AdvantWP.hidePreloader();
    console.error("[Advant] React render error:", e);
  }
  render() {
    if (this.state.err) return (
      <div style={{padding:40,color:"#fff",fontFamily:"monospace",background:"#111",minHeight:"100vh"}}>
        <b>Render error — check console:</b><br/><pre style={{whiteSpace:"pre-wrap",fontSize:12}}>{String(this.state.err)}</pre>
      </div>
    );
    return this.props.children;
  }
}

if (document.body.dataset.page === "home") {
  ReactDOM.createRoot(document.getElementById("root")).render(
    <ErrorBoundary><App /></ErrorBoundary>
  );
}