/* global React */
const { useState: useArtState, useEffect: useArtEffect } = React;

/* ============================================================
   Blog article — single article view
   - Reads ?slug from URL (or falls back to the first article)
   - Renders semantic <article> with proper headings hierarchy
   - SEO: JSON-LD Article schema injected into <head> at runtime
   - Share row: LinkedIn + Copy link
   - Bottom: sources, CTA, back to blog
   ============================================================ */

window.BlogArticleHero = function BlogArticleHero({ article, lang }) {
  const t = lang === "it" ? { by: "A cura di", min: "min di lettura", back: "Tutti gli articoli" } : { by: "By", min: "min read", back: "All articles" };
  return (
    <div style={{ position: "relative", overflow: "hidden", color: "#fff", paddingTop: 130, paddingBottom: 72 }}>
      <div style={{ position: "absolute", inset: 0, background: "var(--tl-gradient-mesh)", zIndex: 0 }} />
      <window.Container style={{ position: "relative", zIndex: 2, maxWidth: 880 }}>
        <a href="blog.html" style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, color: "rgba(255,255,255,.78)", fontWeight: 600, marginBottom: 28 }}>
          <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><window.Icon name="arrow" size={14} /></span> {t.back}
        </a>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "5px 12px", borderRadius: 999, background: "rgba(40,209,254,.12)", border: "1px solid rgba(40,209,254,.28)", marginBottom: 22 }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--tl-cyan)" }} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: "var(--tl-cyan-soft)", textTransform: "uppercase", letterSpacing: ".12em" }}>
            {article.category[lang]}
          </span>
        </div>
        <h1 style={{ fontSize: "clamp(30px, 4.4vw, 56px)", fontWeight: 800, lineHeight: 1.1, letterSpacing: "-0.025em", margin: 0, paddingBottom: "0.05em", color: "#fff" }}>
          {article.title[lang]}
        </h1>
        <p style={{ fontSize: "clamp(16px, 1.4vw, 21px)", lineHeight: 1.5, color: "rgba(255,255,255,0.82)", maxWidth: 720, marginTop: 22, fontWeight: 400 }}>
          {article.dek[lang]}
        </p>
        <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 32, fontSize: 13, color: "rgba(255,255,255,.7)", flexWrap: "wrap" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 999, background: "linear-gradient(135deg,#1E8BFF,#28D1FE)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13, color: "#fff" }}>T</div>
            <span><span style={{ opacity: 0.6 }}>{t.by} </span>{article.author[lang]}</span>
          </div>
          <span aria-hidden="true" style={{ opacity: 0.3 }}>·</span>
          <time dateTime={article.publishedISO} style={{ fontFamily: "var(--font-mono)" }}>{article.publishedLabel[lang]}</time>
          <span aria-hidden="true" style={{ opacity: 0.3 }}>·</span>
          <span style={{ fontFamily: "var(--font-mono)" }}>{article.readingMinutes} {t.min}</span>
        </div>
      </window.Container>
    </div>
  );
};

window.BlogArticleCoverImage = function BlogArticleCoverImage({ article, lang }) {
  if (!article.coverImage) return null;
  const t = lang === "it" ? { caption: "Illustrazione editoriale" } : { caption: "Editorial illustration" };
  return (
    <window.Section style={{ background: "var(--bg)", paddingTop: 0, paddingBottom: 0, marginTop: -36 }}>
      <window.Container style={{ maxWidth: 1080 }}>
        <figure style={{
          margin: 0,
          borderRadius: 20,
          overflow: "hidden",
          background: "#050E2B",
          boxShadow: "0 24px 64px -20px rgba(5,14,43,0.45), 0 8px 24px -10px rgba(5,14,43,0.25)",
          border: "1px solid var(--border)",
          position: "relative",
        }}>
          <img
            src={article.coverImage.src}
            alt={article.coverImage.alt[lang]}
            loading="eager"
            decoding="async"
            style={{
              display: "block",
              width: "100%",
              height: "auto",
              objectFit: "cover",
              objectPosition: article.coverImage.focal || "center",
            }}
          />
        </figure>
      </window.Container>
    </window.Section>
  );
};

window.BlogArticleShare = function BlogArticleShare({ article, lang }) {
  const [copied, setCopied] = useArtState(false);
  const url = typeof window !== "undefined" ? window.location.href : "";
  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch (e) { /* no-op */ }
  };
  const linkedinHref = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`;
  const t = lang === "it" ? { share: "Condividi", linkedin: "LinkedIn", copy: "Copia link", copied: "Copiato!" } : { share: "Share", linkedin: "LinkedIn", copy: "Copy link", copied: "Copied!" };
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 12,
      flexWrap: "wrap",
      paddingTop: 28,
      marginTop: 28,
      borderTop: "1px solid var(--border)",
    }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".12em", marginRight: 6 }}>
        {t.share}
      </span>
      <a href={linkedinHref} target="_blank" rel="noopener noreferrer" style={shareBtn}>
        <window.Icon name="linkedin" size={14} /> {t.linkedin}
      </a>
      <button type="button" onClick={onCopy} style={{ ...shareBtn, cursor: "pointer", fontFamily: "inherit" }}>
        <window.Icon name={copied ? "check-simple" : "external"} size={14} /> {copied ? t.copied : t.copy}
      </button>
    </div>
  );
};
const shareBtn = {
  display: "inline-flex", alignItems: "center", gap: 8,
  padding: "8px 14px",
  borderRadius: 999,
  background: "var(--bg-subtle)",
  border: "1px solid var(--border)",
  color: "var(--fg-1)",
  fontSize: 13, fontWeight: 600,
  textDecoration: "none",
  transition: "background 160ms, border-color 160ms",
};

window.BlogArticleBodyWrap = function BlogArticleBodyWrap({ article, lang }) {
  return (
    <window.Section style={{ background: "var(--bg)", paddingTop: "clamp(40px, 5vw, 64px)", paddingBottom: "clamp(40px, 5vw, 64px)" }}>
      <window.Container style={{ maxWidth: 760 }}>
        <article>
          <window.BlogArticleBody id={article.body[lang] || article.body.it} />
          <window.BlogArticleShare article={article} lang={lang} />
        </article>
      </window.Container>
      {/* Editorial type styles scoped to .tl-prose */}
      <style>{`
        .tl-prose { color: var(--fg-1); font-size: 17px; line-height: 1.75; }
        .tl-prose .tl-lead { font-size: 19px; line-height: 1.6; color: var(--fg-1); }
        .tl-prose .tl-lead::first-letter {
          font-family: var(--font-sans);
          font-weight: 800;
          font-size: 56px;
          line-height: 0.95;
          float: left;
          margin: 6px 14px 0 0;
          color: var(--tl-blue-primary);
          letter-spacing: -0.02em;
        }
        .tl-prose p { margin: 0 0 22px 0; }
        .tl-prose strong { font-weight: 700; color: var(--fg-1); }
        .tl-prose em { font-style: italic; }
        .tl-prose h2 {
          font-size: clamp(22px, 2.4vw, 30px);
          font-weight: 700;
          letter-spacing: -0.02em;
          line-height: 1.2;
          margin: 48px 0 18px 0;
          color: var(--fg-1);
          position: relative;
          padding-left: 18px;
        }
        .tl-prose h2::before {
          content: "";
          position: absolute;
          left: 0; top: 0.32em; bottom: 0.32em;
          width: 4px;
          border-radius: 4px;
          background: linear-gradient(180deg, var(--tl-blue-primary), var(--tl-cyan));
        }
        .tl-prose blockquote {
          margin: 32px 0;
          padding: 22px 26px;
          background: var(--bg-subtle);
          border-left: 4px solid var(--tl-blue-primary);
          border-radius: 4px 12px 12px 4px;
          font-size: 18px;
          line-height: 1.65;
          color: var(--fg-1);
        }
        .tl-prose blockquote p:last-child { margin-bottom: 0; }
        .tl-prose a { color: var(--tl-blue-primary); text-decoration: underline; text-underline-offset: 3px; text-decoration-thickness: 1px; }
        .tl-prose a:hover { color: var(--tl-blue-deep); }
        @media (max-width: 640px) {
          .tl-prose { font-size: 16.5px; line-height: 1.7; }
          .tl-prose .tl-lead { font-size: 17.5px; }
          .tl-prose .tl-lead::first-letter { font-size: 44px; margin: 4px 10px 0 0; }
          .tl-prose h2 { margin: 36px 0 14px 0; padding-left: 14px; }
        }
      `}</style>
    </window.Section>
  );
};

window.BlogArticleSources = function BlogArticleSources({ article, lang }) {
  if (!article.sources || article.sources.length === 0) return null;
  const t = lang === "it" ? { eyebrow: "Fonti", title: "Riferimenti e letture" } : { eyebrow: "Sources", title: "References and reading" };
  return (
    <window.Section style={{ background: "var(--bg-subtle)", paddingTop: "clamp(48px, 6vw, 72px)", paddingBottom: "clamp(48px, 6vw, 72px)" }}>
      <window.Container style={{ maxWidth: 760 }}>
        <window.Eyebrow>{t.eyebrow}</window.Eyebrow>
        <h2 style={{ fontSize: "clamp(22px, 2.4vw, 30px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.2, margin: "0 0 28px 0" }}>{t.title}</h2>
        <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 0 }}>
          {article.sources.map((s, i) => (
            <li key={s.href} style={{
              display: "grid", gridTemplateColumns: "32px 1fr", gap: 14,
              alignItems: "start",
              padding: "14px 0",
              borderTop: i === 0 ? "1px solid var(--border)" : "none",
              borderBottom: "1px solid var(--border)",
            }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: "var(--tl-blue-primary)", letterSpacing: ".06em", paddingTop: 3 }}>
                {String(i + 1).padStart(2, "0")}
              </span>
              <a href={s.href} target="_blank" rel="noopener noreferrer" style={{ fontSize: 14.5, color: "var(--fg-1)", lineHeight: 1.55, textDecoration: "none" }}>
                <span style={{ fontWeight: 500 }}>{s.label}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 2, marginLeft: 8, color: "var(--tl-blue-primary)", verticalAlign: "middle" }}>
                  <window.Icon name="arrow-up-right" size={12} />
                </span>
              </a>
            </li>
          ))}
        </ol>
      </window.Container>
    </window.Section>
  );
};

window.BlogArticleEndCTA = function BlogArticleEndCTA({ lang }) {
  const t = lang === "it" ? {
    eyebrow: "Tecnolife",
    title: "Se ti riconosci nel modo di lavorare descritto in questo articolo, parliamone.",
    body: "Tecnolife è una digital company che lavora come Forward Deployed Team: entriamo nei processi reali, costruiamo soluzioni AI sostenibili e lasciamo sistemi che continuano a creare valore.",
    primary: "Contattaci",
    secondary: "Scopri come lavoriamo",
  } : {
    eyebrow: "Tecnolife",
    title: "If our way of working resonates, let's talk.",
    body: "Tecnolife is a digital company that operates as a Forward Deployed Team: we enter real processes, build sustainable AI solutions, and leave systems that keep creating value.",
    primary: "Contact us",
    secondary: "How we work",
  };
  return (
    <window.Section style={{ background: "var(--bg)", paddingTop: "clamp(48px, 6vw, 72px)" }}>
      <window.Container style={{ maxWidth: 880 }}>
        <div className="tl-blog-endcta" style={{
          background: "linear-gradient(135deg,#050E2B 0%,#0228A3 50%,#0B57E0 100%)",
          borderRadius: 24, padding: "clamp(32px, 4vw, 56px)", color: "#fff",
          display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 36, alignItems: "center",
          position: "relative", overflow: "hidden",
        }}>
          <svg style={{ position: "absolute", inset: 0, opacity: 0.16 }} viewBox="0 0 600 300" preserveAspectRatio="none">
            <defs><pattern id="endctapt" 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(#endctapt)" />
          </svg>
          <div style={{ position: "relative" }}>
            <window.Eyebrow light>{t.eyebrow}</window.Eyebrow>
            <h2 style={{ fontSize: "clamp(22px,2.6vw,32px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.2, margin: 0 }}>
              {t.title}
            </h2>
            <p style={{ fontSize: 15.5, color: "rgba(255,255,255,.78)", marginTop: 14, lineHeight: 1.55, maxWidth: 520 }}>
              {t.body}
            </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} />}>
              {t.primary}
            </window.Button>
            <window.Button size="lg" variant="glass" href="factory.html" icon={<window.Icon name="arrow-up-right" size={16} />}>
              {t.secondary}
            </window.Button>
          </div>
        </div>
        <style>{`
          @media (max-width: 820px) { .tl-blog-endcta { grid-template-columns: 1fr !important; gap: 22px !important; } }
        `}</style>
      </window.Container>
    </window.Section>
  );
};

/* JSON-LD schema injector — improves SEO; runs once on mount */
window.BlogArticleJsonLd = function BlogArticleJsonLd({ article, lang }) {
  useArtEffect(() => {
    if (typeof document === "undefined") return;
    const url = window.location.href;
    const schema = {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: article.title[lang],
      description: article.metaDescription[lang],
      datePublished: article.publishedISO,
      dateModified: article.publishedISO,
      inLanguage: lang === "it" ? "it-IT" : "en-US",
      author: { "@type": "Organization", name: "Tecnolife IT Consulting S.r.l.", url: "https://www.tecnolife.com" },
      publisher: {
        "@type": "Organization",
        name: "Tecnolife IT Consulting S.r.l.",
        logo: { "@type": "ImageObject", url: new URL("assets/Logo_Esteso_Blu.png", url).toString() },
      },
      mainEntityOfPage: { "@type": "WebPage", "@id": url },
      keywords: article.tags.join(", "),
    };
    if (article.coverImage && article.coverImage.src) {
      schema.image = new URL(article.coverImage.src, url).toString();
    }
    let el = document.getElementById("__tl_article_jsonld");
    if (!el) {
      el = document.createElement("script");
      el.type = "application/ld+json";
      el.id = "__tl_article_jsonld";
      document.head.appendChild(el);
    }
    el.textContent = JSON.stringify(schema);
    /* Update document title + meta description live based on chosen lang */
    document.title = `${article.title[lang]} · Tecnolife`;
    let md = document.querySelector('meta[name="description"]');
    if (!md) { md = document.createElement("meta"); md.setAttribute("name", "description"); document.head.appendChild(md); }
    md.setAttribute("content", article.metaDescription[lang]);
    /* OG/Twitter sync */
    const setMeta = (sel, attr, key, value) => {
      let m = document.querySelector(sel);
      if (!m) { m = document.createElement("meta"); m.setAttribute(attr, key); document.head.appendChild(m); }
      m.setAttribute("content", value);
    };
    setMeta('meta[property="og:title"]', "property", "og:title", article.title[lang]);
    setMeta('meta[property="og:description"]', "property", "og:description", article.metaDescription[lang]);
    setMeta('meta[property="og:type"]', "property", "og:type", "article");
    setMeta('meta[property="og:url"]', "property", "og:url", url);
    setMeta('meta[name="twitter:card"]', "name", "twitter:card", "summary_large_image");
    setMeta('meta[name="twitter:title"]', "name", "twitter:title", article.title[lang]);
    setMeta('meta[name="twitter:description"]', "name", "twitter:description", article.metaDescription[lang]);
    if (article.coverImage && article.coverImage.src) {
      const imgUrl = new URL(article.coverImage.src, url).toString();
      setMeta('meta[property="og:image"]', "property", "og:image", imgUrl);
      setMeta('meta[name="twitter:image"]', "name", "twitter:image", imgUrl);
    }
  }, [article, lang]);
  return null;
};
