/* global React */
const { useState: useHomeState } = React;

/* ======================================================================
   HOME SERVICES — derived from pages.home (intro_ai_section,
   custom_software_section, ecommerce_section) + servizi top-level blocks.
   ====================================================================== */
window.HomeServices = function HomeServices({ lang }) {
  const items = lang === "it" ? [
    {
      icon: "cpu", tag: "Soluzioni AI",
      title: "L'Intelligenza Artificiale al servizio del tuo business",
      body: "Soluzioni AI che vanno dal machine learning all'elaborazione del linguaggio naturale, con integrazioni fluide e performanti con i sistemi esistenti.",
      href: "servizi.html#ai",
    },
    {
      icon: "code", tag: "Sviluppo custom",
      title: "Sviluppo applicazioni custom",
      body: "Progettiamo e sviluppiamo applicazioni personalizzate su tecnologie Microsoft, Java, PHP e Mobile Native — dalla prima idea alla distribuzione.",
      href: "servizi.html#custom",
    },
    {
      icon: "box", tag: "E-Commerce",
      title: "E-Commerce con Adobe Magento",
      body: "Esperienze di acquisto digitali fluide e performanti, con integrazione di Magento con CRM, ERP ed altre tecnologie.",
      href: "servizi.html#ecommerce",
    },
  ] : [
    {
      icon: "cpu", tag: "AI Solutions",
      title: "Artificial Intelligence at the service of your business",
      body: "AI solutions ranging from machine learning to natural language processing, with smooth and performant integrations into existing systems.",
      href: "servizi.html#ai",
    },
    {
      icon: "code", tag: "Custom development",
      title: "Custom application development",
      body: "We design and develop tailored applications on Microsoft, Java, PHP and Mobile Native technologies — from the first idea to deployment.",
      href: "servizi.html#custom",
    },
    {
      icon: "box", tag: "E-Commerce",
      title: "E-Commerce with Adobe Magento",
      body: "Smooth, performant digital shopping experiences, with Magento integrated with CRM, ERP and other technologies.",
      href: "servizi.html#ecommerce",
    },
  ];
  return (
    <window.Section id="Servizi">
      <window.Container>
        <div style={{ maxWidth: 760, marginBottom: 56 }}>
          <window.Eyebrow>{lang === "it" ? "Cosa facciamo" : "What we do"}</window.Eyebrow>
          <h2 style={{ fontSize: "clamp(32px,4vw,52px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, margin: 0 }}>
            {lang === "it" ? "Soluzioni AI custom per il tuo business." : "Custom AI solutions for your business."}
          </h2>
          <p style={{ fontSize: 18, color: "var(--fg-2)", marginTop: 18 }}>
            {lang === "it"
              ? "Tecnologie all'avanguardia integrate con i sistemi enterprise più diffusi: Magento, Salesforce, Microsoft Power Platform."
              : "Cutting-edge technologies integrated with the most widely-used enterprise systems: Magento, Salesforce, Microsoft Power Platform."}
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 18 }}>
          {items.map((it, i) => <ServiceCard key={i} {...it} lang={lang} />)}
        </div>
      </window.Container>
    </window.Section>
  );
};

function ServiceCard({ icon, tag, title, body, href, lang }) {
  const [hover, setHover] = useHomeState(false);
  return (
    <a href={href} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{
      background: "#fff", border: "1px solid var(--border)", borderRadius: 18, padding: 26,
      transition: "all 220ms cubic-bezier(.22,1,.36,1)",
      transform: hover ? "translateY(-4px)" : "translateY(0)",
      boxShadow: hover ? "var(--shadow-lg)" : "var(--shadow-sm)",
      cursor: "pointer", position: "relative", overflow: "hidden", display: "block", textDecoration: "none",
    }}>
      <div style={{ position: "absolute", top: -40, right: -40, width: 160, height: 160, borderRadius: "50%", background: "radial-gradient(circle, rgba(40,209,254,.25) 0%, transparent 70%)", opacity: hover ? 1 : 0, transition: "opacity 320ms" }} />
      <div style={{ width: 44, height: 44, borderRadius: 12, background: "linear-gradient(135deg,#0228A3,#1E8BFF)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "#fff", marginBottom: 18, boxShadow: "0 6px 16px rgba(11,87,224,.32)" }}>
        <window.Icon name={icon} size={22} strokeWidth={1.6} />
      </div>
      <window.Tag color="cyan">{tag}</window.Tag>
      <h3 style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em", margin: "12px 0 8px", color: "var(--fg-1)", lineHeight: 1.25 }}>{title}</h3>
      <p style={{ fontSize: 14, color: "var(--fg-2)", lineHeight: 1.55, margin: 0 }}>{body}</p>
      <div style={{ marginTop: 20, display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, color: "var(--tl-blue-primary)", transform: hover ? "translateX(4px)" : "translateX(0)", transition: "transform 220ms" }}>
        {lang === "it" ? "Approfondisci" : "Read more"} <window.Icon name="arrow" size={14} />
      </div>
    </a>
  );
}

/* ======================================================================
   MARKETS GRID — pages.home.markets_grid (8 markets, real text from JSON)
   Renamed from "HomeFactory" to keep exports stable.
   ====================================================================== */
window.HomeFactory = function HomeMarkets({ lang }) {
  const markets = lang === "it" ? [
    { name: "Finance & Insurance", body: "Creiamo soluzioni su misura per efficienza e sicurezza. L'AI è al supporto nella gestione dei rischi, delle analisi predittive e della customer experience." },
    { name: "Retail & GDO", body: "Soluzioni AI per personalizzare l'esperienza cliente, gestire l'inventario e ottimizzare le vendite, migliorando l'analisi dei dati in tempo reale." },
    { name: "Industria", body: "Agevoliamo le industrie ad automatizzare ed ottimizzare i processi con soluzioni AI custom portando innovazione e competitività." },
    { name: "Healthcare", body: "Collaboriamo con le strutture sanitarie sviluppando applicazioni sicure ed affidabili, integrando l'AI per ottimizzare i dati, l'efficienza e il supporto decisionale." },
    { name: "E-Commerce", body: "Sviluppiamo soluzioni E-Commerce con Adobe Magento, integrando l'AI per i dati, l'analisi clienti e la personalizzazione tramite un'infrastruttura flessibile." },
    { name: "Pubblica Amministrazione", body: "Supportiamo gli enti pubblici nella modernizzazione, nel miglioramento dei servizi ai cittadini e nell'uso dell'AI per una gestione efficace ed efficiente." },
    { name: "Aeroportuale & Trasporti", body: "Soluzioni digitali per ottimizzare i canali di comunicazione, le infrastrutture complesse e l'esperienza dei passeggeri." },
    { name: "Telco / Telecomunicazioni", body: "Aiutiamo le telecomunicazioni nella trasformazione digitale con soluzioni AI per analisi avanzate, automazione e ottimizzazione dei servizi." },
  ] : [
    { name: "Finance & Insurance", body: "Tailored solutions for efficiency and security. AI supports risk management, predictive analytics and customer experience." },
    { name: "Retail & Large Distribution", body: "AI solutions to personalise customer experience, manage inventory and optimise sales, improving real-time data analysis." },
    { name: "Industry", body: "We help industries automate and optimise processes with custom AI solutions, bringing innovation and competitiveness." },
    { name: "Healthcare", body: "We work with healthcare facilities developing secure, reliable applications, integrating AI to optimise data, efficiency and decision support." },
    { name: "E-Commerce", body: "We build E-Commerce solutions with Adobe Magento, integrating AI for data, customer analysis and personalisation via a flexible infrastructure." },
    { name: "Public Administration", body: "We support public bodies in modernisation, improving services to citizens and using AI for effective, efficient management." },
    { name: "Airports & Transport", body: "Digital solutions to optimise communication channels, complex infrastructures and the passenger experience." },
    { name: "Telco / Telecommunications", body: "We support telecommunications in digital transformation with AI solutions for advanced analytics, automation and service optimisation." },
  ];

  return (
    <window.Section id="Mercati" dark style={{ overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 75% 30%, rgba(40,209,254,.15) 0%, transparent 50%)", pointerEvents: "none" }} />
      <window.Container style={{ position: "relative" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 20, marginBottom: 56 }}>
          <div style={{ maxWidth: 760 }}>
            <window.Eyebrow light>{lang === "it" ? "Mercati" : "Markets"}</window.Eyebrow>
            <h2 style={{ fontSize: "clamp(32px,4vw,52px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, margin: 0, color: "#fff" }}>
              {lang === "it" ? "I mercati in cui operiamo" : "The markets we operate in"}
            </h2>
            <p style={{ fontSize: 17, color: "rgba(255,255,255,.7)", marginTop: 18 }}>
              {lang === "it"
                ? "Da Telco alla Logistica, dal Retail alla Pubblica Amministrazione: competenze certificate e soluzioni su misura."
                : "From Telco to Logistics, from Retail to Public Administration: certified expertise and tailored solutions."}
            </p>
          </div>
          <window.Button variant="glass" href="servizi.html#mercati" icon={<window.Icon name="arrow" size={14} />}>
            {lang === "it" ? "Esplora i mercati" : "Explore markets"}
          </window.Button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 1, background: "rgba(255,255,255,.08)", borderRadius: 20, overflow: "hidden", border: "1px solid rgba(255,255,255,.10)" }}>
          {markets.map((m, i) => (
            <div key={i} style={{ background: "rgba(8,12,26,.6)", padding: 26, position: "relative", minHeight: 180 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--tl-cyan)", letterSpacing: ".1em", marginBottom: 14 }}>{String(i + 1).padStart(2, "0")}</div>
              <h3 style={{ fontSize: 18, fontWeight: 700, color: "#fff", margin: "0 0 10px", letterSpacing: "-0.01em", lineHeight: 1.25 }}>{m.name}</h3>
              <p style={{ fontSize: 13.5, color: "rgba(255,255,255,.65)", lineHeight: 1.55, margin: 0 }}>{m.body}</p>
            </div>
          ))}
        </div>
      </window.Container>
    </window.Section>
  );
};

/* ======================================================================
   CLIENTS PREVIEW — "Hanno scelto Tecnolife"
   Anteprima narrativa della lista clienti completa che vive su clienti.html.
   16 nomi reali (IT) raggruppati in 6 cluster, allineati 1:1 con
   page-clienti.jsx (single source of truth della pagina dedicata).
   Solo nomi: nessun progetto, nessuna metrica, nessuna descrizione tecnica.
   Approvazione cliente: confermata. Citazione del nome consentita.
   ====================================================================== */
window.HomeClients = function HomeClients({ lang }) {
  const t = lang === "it" ? {
    eyebrow: "Hanno scelto Tecnolife",
    title: "Aziende e istituzioni che si affidano a noi",
    subtitle:
      "Dal lusso del Made in Italy alle infrastrutture critiche del Paese, dai grandi gruppi energy alle eccellenze del retail. Una selezione di clienti che hanno scelto Tecnolife.",
    cta: "Vedi tutti i clienti",
    clusters: [
      { name: "Trasporti & Mobilità",              clients: ["ADR — Aeroporti di Roma", "SEA — Aeroporti di Milano", "ANAS"] },
      { name: "Difesa & Pubblica Amministrazione", clients: ["Presidenza del Consiglio", "Aeronautica Militare", "Corte dei Conti", "Sogei", "Rheinmetall"] },
      { name: "Lusso & Made in Italy",             clients: ["Bulgari", "Campari", "Cassina", "Cappellini", "Poltrone Frau"] },
      { name: "Energy, Industria & Telco",         clients: ["Enel", "Vodafone", "Sielte", "Nippon Gases"] },
      { name: "Retail & E-Commerce",               clients: ["Buffetti", "GLS", "Bricofer"] },
      { name: "Education",                         clients: ["LUISS Guido Carli", "Università UniMarconi"] },
    ],
  } : {
    eyebrow: "They chose Tecnolife",
    title: "Companies and institutions that trust us",
    subtitle:
      "From Italian luxury icons to critical national infrastructures, from major energy groups to retail excellence. A selection of clients who chose Tecnolife.",
    cta: "All clients",
    clusters: [
      { name: "Transport & Mobility",              clients: ["ADR — Rome Airports", "SEA — Milan Airports", "ANAS — Italian National Roads"] },
      { name: "Defence & Public Administration",   clients: ["Presidency of the Council of Ministers", "Italian Air Force", "Italian Court of Auditors", "Sogei", "Rheinmetall"] },
      { name: "Luxury & Made in Italy",            clients: ["Bulgari", "Campari", "Cassina", "Cappellini", "Poltrone Frau"] },
      { name: "Energy, Industry & Telco",          clients: ["Enel", "Vodafone", "Sielte", "Nippon Gases"] },
      { name: "Retail & E-Commerce",               clients: ["Buffetti", "GLS", "Bricofer"] },
      { name: "Education",                         clients: ["LUISS Guido Carli University", "UniMarconi University"] },
    ],
  };

  return (
    <window.Section id="Clienti" style={{ background: "var(--bg-subtle)" }}>
      <window.Container>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 20, marginBottom: 48 }}>
          <div style={{ maxWidth: 760 }}>
            <window.Eyebrow>{t.eyebrow}</window.Eyebrow>
            <h2 style={{ fontSize: "clamp(32px,4vw,52px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, margin: 0 }}>
              {t.title}
            </h2>
            <p style={{ fontSize: 18, color: "var(--fg-2)", marginTop: 18, lineHeight: 1.55 }}>
              {t.subtitle}
            </p>
          </div>
          <window.Button variant="secondary" href="clienti.html" icon={<window.Icon name="arrow" size={14} />}>
            {t.cta}
          </window.Button>
        </div>

        {/* TODO: switch to logo variant when assets/clients/*.svg are ready */}
        <div style={{ display: "grid", gap: 20 }}>
          {t.clusters.map((cluster, i) => (
            <div key={i} style={{
              background: "#fff",
              border: "1px solid var(--border)",
              borderRadius: 18,
              padding: "26px 30px",
              boxShadow: "var(--shadow-sm)",
            }}>
              <div style={{
                fontFamily: "var(--font-mono)",
                fontSize: 12,
                color: "var(--tl-blue-primary)",
                letterSpacing: ".1em",
                textTransform: "uppercase",
                fontWeight: 700,
                marginBottom: 18,
              }}>
                {String(i + 1).padStart(2, "0")} — {cluster.name}
              </div>
              <div style={{
                display: "flex",
                flexWrap: "wrap",
                gap: "14px 32px",
                alignItems: "baseline",
              }}>
                {cluster.clients.map((c, j) => (
                  <span key={j} style={{
                    fontSize: "clamp(18px, 1.8vw, 22px)",
                    fontWeight: 600,
                    letterSpacing: "-0.01em",
                    color: "var(--fg-1)",
                    lineHeight: 1.3,
                  }}>
                    {c}
                  </span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </window.Container>
    </window.Section>
  );
};

/* ======================================================================
   CASE HISTORIES — sezione rimossa in v0.7.0.
   La pagina dedicata casi-studio.html, il file js/page-casi.jsx e tutta la
   directory assets/cases/ sono stati cancellati. La narrazione "progetti"
   confluisce nelle testimonianze e nella sezione Clienti.
   ====================================================================== */

/* ======================================================================
   TESTIMONIALS — REAL quotes from pages.home.testimonials_section.items[]
   ====================================================================== */
window.HomeTestimonial = function HomeTestimonial({ lang }) {
  const [idx, setIdx] = useHomeState(0);
  // Real testimonials from JSON. Authors are anonymous on the live site;
  // we surface the inferred context only.
  const items = lang === "it" ? [
    {
      quote: "Grazie alla collaborazione con Tecnolife abbiamo potuto realizzare il sito eCommerce GLS Store per la vendita del servizio di spedizione GLS ai privati in Italia. Siamo stati guidati verso le giuste scelte tecnico/funzionali per raggiungere i nostri obiettivi di business, fornendo all'utente un'esperienza di acquisto moderna, frictionless e sicura.",
      ctx: "GLS Italy",
    },
    {
      quote: "Siamo estremamente soddisfatti della collaborazione con il team di Tecnolife, che si è dimostrato un partner tecnologico affidabile e strategico per lo sviluppo e la crescita del nostro e-commerce. Consigliamo vivamente Tecnolife a tutte le aziende che desiderano potenziare la propria presenza digitale e sviluppare progetti e-commerce di successo.",
      ctx: "Cliente E-commerce / Retail",
    },
    {
      quote: "Il progetto ha portato allo sviluppo di un gestionale innovativo per la creazione di pacchetti SCORM, essenziali per la gestione di corsi ed esami universitari. Il team di Tecnolife ha gestito il progetto con grande professionalità, garantendo un lavoro di alta qualità.",
      ctx: "Università UniMarconi",
    },
    {
      quote: "Siamo estremamente soddisfatti del supporto ricevuto da Tecnolife al nostro team di customer support. La risorsa assegnata ha dimostrato professionalità e dedizione, fornendo soluzioni tempestive ed efficaci e migliorando le nostre operazioni quotidiane.",
      ctx: "Cliente Customer Support",
    },
  ] : [
    {
      quote: "Thanks to the collaboration with Tecnolife we built the GLS Store eCommerce site to sell GLS shipping services to private customers in Italy. We were guided towards the right technical and functional choices to reach our business goals, giving users a modern, frictionless and secure shopping experience.",
      ctx: "GLS Italy",
    },
    {
      quote: "We are extremely satisfied with the collaboration with the Tecnolife team, who proved to be a reliable, strategic technology partner for the development and growth of our e-commerce. We strongly recommend Tecnolife to any company aiming to strengthen its digital presence.",
      ctx: "E-commerce / Retail client",
    },
    {
      quote: "The project led to an innovative platform for creating SCORM packages, essential for managing university courses and exams. Tecnolife's team handled the project with great professionalism, delivering high-quality work.",
      ctx: "UniMarconi University",
    },
    {
      quote: "We are extremely satisfied with the support Tecnolife provided to our customer-support team. The assigned resource showed professionalism and dedication, delivering timely and effective solutions and improving our daily operations.",
      ctx: "Customer Support client",
    },
  ];
  const t = items[idx];

  return (
    <window.Section style={{ background: "var(--bg)" }}>
      <window.Container>
        <div style={{ maxWidth: 980, margin: "0 auto", textAlign: "center" }}>
          <window.Eyebrow>{lang === "it" ? "Cosa dicono di noi" : "What they say about us"}</window.Eyebrow>
          <p style={{ fontSize: 17, color: "var(--fg-2)", margin: "0 auto 32px", maxWidth: 680 }}>
            {lang === "it"
              ? "Leggi le testimonianze di chi ha scelto Tecnolife e scopri come abbiamo fatto la differenza."
              : "Read the testimonials of those who chose Tecnolife and find out how we made the difference."}
          </p>
          <div style={{ color: "var(--tl-cyan)", display: "inline-flex", marginBottom: 22 }}>
            <window.Icon name="quote" size={42} strokeWidth={1.2} />
          </div>
          <p style={{ fontSize: "clamp(18px, 1.8vw, 24px)", lineHeight: 1.55, fontWeight: 500, letterSpacing: "-0.005em", color: "var(--fg-1)", margin: 0, minHeight: 180 }}>
            {t.quote}
          </p>
          <div style={{ marginTop: 28, fontSize: 13, color: "var(--fg-2)", letterSpacing: ".06em", textTransform: "uppercase", fontWeight: 600 }}>— {t.ctx}</div>
          <div style={{ display: "flex", justifyContent: "center", gap: 8, marginTop: 32 }}>
            {items.map((_, i) => (
              <button key={i} onClick={() => setIdx(i)} aria-label={`testimonial ${i + 1}`} style={{
                width: i === idx ? 28 : 8, height: 8, borderRadius: 999, border: 0,
                background: i === idx ? "var(--tl-blue-primary)" : "var(--tl-grey-300)",
                cursor: "pointer", transition: "all 220ms cubic-bezier(.22,1,.36,1)",
              }} />
            ))}
          </div>
        </div>
      </window.Container>
    </window.Section>
  );
};

/* ======================================================================
   CTA — pages.home.final_cta
   ====================================================================== */
window.HomeCTA = function HomeCTA({ lang }) {
  return (
    <window.Section style={{ background: "var(--bg)", paddingTop: 0 }}>
      <window.Container>
        <div style={{
          background: "linear-gradient(135deg, #050E2B 0%, #0228A3 50%, #0B57E0 100%)",
          borderRadius: 28, padding: "clamp(40px, 6vw, 80px)", color: "#fff",
          display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 56, alignItems: "center",
          position: "relative", overflow: "hidden",
        }} className="home-cta">
          <svg style={{ position: "absolute", inset: 0, opacity: 0.18 }} viewBox="0 0 600 300" preserveAspectRatio="none">
            <defs>
              <pattern id="ctagrid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M40 0H0V40" fill="none" stroke="#7EE3FF" strokeWidth="0.5" />
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#ctagrid)" />
          </svg>
          <div style={{ position: "absolute", top: 30, right: 60, width: 24, height: 24, borderRadius: 6, background: "linear-gradient(135deg,#1E8BFF,#28D1FE)", boxShadow: "0 8px 24px rgba(40,209,254,.5)" }} />
          <div style={{ position: "absolute", top: 90, right: 24, width: 16, height: 16, borderRadius: 4, background: "linear-gradient(135deg,#1E8BFF,#28D1FE)", opacity: 0.7 }} />
          <div style={{ position: "absolute", bottom: 36, right: 110, width: 12, height: 12, borderRadius: 3, background: "#28D1FE", opacity: 0.5 }} />

          <div style={{ position: "relative" }}>
            <window.Eyebrow light>{lang === "it" ? "Contatti" : "Contact"}</window.Eyebrow>
            <h2 style={{ fontSize: "clamp(32px,4vw,52px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, margin: 0, color: "#fff" }}>
              {lang === "it" ? "Parla con noi." : "Let's talk."}
            </h2>
            <p style={{ fontSize: 17, color: "rgba(255,255,255,.78)", marginTop: 18, lineHeight: 1.55, maxWidth: 480 }}>
              {lang === "it"
                ? "Tecnolife si trova nel cuore dell'EUR, a Roma. Contattaci e richiedi informazioni sui nostri servizi."
                : "Tecnolife sits in the heart of EUR, in Rome. Get in touch and ask us about our services."}
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, position: "relative" }}>
            <window.Button size="lg" variant="glass-light" href="contatti.html" icon={<window.Icon name="arrow" size={16} />}>
              {lang === "it" ? "Contattaci" : "Contact us"}
            </window.Button>
            <window.Button size="lg" variant="glass" href="clienti.html" icon={<window.Icon name="arrow-up-right" size={16} />}>
              {lang === "it" ? "Vedi tutti i clienti" : "All clients"}
            </window.Button>
          </div>
        </div>
        <style>{`
          @media (max-width: 820px) { .home-cta { grid-template-columns: 1fr !important; gap: 24px !important; } }
        `}</style>
      </window.Container>
    </window.Section>
  );
};
