/* global React */
const { useState, useEffect, useRef } = React;

/* All Softera customers — flattened from the Asiakkaat page, ordered by sector
 * (telco/fiber → waste & circular economy → energy & water → housing).
 * Display names are short, readable wordmarks (no logos). */
const HERO_CUSTOMERS = [
  // Telco & fiber
  "DNA",
  "Tieto",
  "Järvi-Suomen Valokuitu",
  "Kaisanet",
  "JNT",
  "MPY",
  "LPOnet",
  "Lounea",
  "Länsilinkki",
  "ElmoNet",
  "Vakka-Suomen Puhelin",
  "Karjaan Puhelin",
  "Paraisten Puhelin",
  "ICT Elmo",
  // Waste & circular economy
  "Napapiirin Energia ja Vesi",
  "Jätekukko",
  "Lounais-Suomen Jätehuolto",
  "Rosk'n Roll",
  "Kiertokaari",
  "Salpakierto",
  "Mustankorkea",
  "Metsäsairila",
  "Vestia",
  // Energy & water
  "Lahti Energia",
  "Porvoon Energia",
  "Seinäjoen Energia",
  "Keravan Energia",
  "Nivos",
  "Elvera",
  "Caverion",
  // Housing
  "Niiralan Kulma",
  "Jyväskylän Vuokra-asunnot",
  "Sivakka",
];

function HeroCustomerMarquee() {
  // Duplicate the list so the -50% translate loops seamlessly.
  const loop = HERO_CUSTOMERS.concat(HERO_CUSTOMERS);
  return (
    <div className="hero-marquee" aria-label="Softeran asiakkaat">
      <div className="hero-marquee__track">
        {loop.map((name, i) => (
          <span
            key={name + "-" + i}
            className="hero-marquee__item"
            aria-hidden={i >= HERO_CUSTOMERS.length}
          >
            {name}
          </span>
        ))}
      </div>
    </div>
  );
}


const HERO_VARIANTS = {
  t360: {
    tabId: "t360",
    tabLabel: "T360°",
    eyebrow: "Laajakaista · Softera T360°",
    h: ["Valokuituliiketoiminta ", { italic: "yhdellä kannalla" }, "."],
    sub: "Myynti, tilaukset, toimitukset, asiakaspalvelu ja laskutus samassa järjestelmässä. Rakennettu valokuituoperaattoreille.",
    Mock: () => <MockT360 />,
    // Callouts off for T360 — the new glass-stack mockup is a subtle backdrop,
    // not a feature, so we let it breathe behind the copy instead of pinning labels.
    callouts: [],
  },
  j360: {
    tabId: "j360",
    tabLabel: "J360°",
    eyebrow: "Jätehuolto · Softera J360°",
    h: ["Jätehuollon arki ", { italic: "yhdellä alustalla" }, "."],
    sub: "Rakennukset, reitit, jätehuoltomääräykset, asiakaslaskutus ja sähköinen asiointi samassa järjestelmässä. Rakennettu kunnallisille jäteyhtiöille.",
    Mock: () => <MockJ360 />,
    // Callouts off for J360 — same clean glass-cascade treatment as T360.
    callouts: [],
  },
  horizon: {
    tabId: "horizon",
    tabLabel: "Horizon",
    eyebrow: "Asiakaspalvelu · Softera Horizon",
    h: ["Kaikki kanavat ", { italic: "yhdellä työpöydällä" }, "."],
    sub: "Puhe, sähköposti, chat, some ja verkkolomakkeet samassa työpöydässä. Asiakas tunnistuu automaattisesti, taustajärjestelmät avautuvat välilehdiksi ja koko palveluhistoria on näkyvissä.",
    Mock: () => <MockHorizon />,
    // Callouts off — consistent with T360 and J360 glass-cascade treatment.
    callouts: [],
  },
};

const HERO_VARIANTS_EN = {
  t360: { ...HERO_VARIANTS.t360,
    tabLabel: "T360°",
    eyebrow: "Broadband · Softera T360°",
    h: ["Fiber business ", { italic: "in one place" }, "."],
    sub: "Sales, orders, provisioning, support and billing in one system. Built for fiber operators.",
  },
  j360: { ...HERO_VARIANTS.j360,
    tabLabel: "J360°",
    eyebrow: "Waste management · Softera J360°",
    h: ["Waste operations ", { italic: "on one platform" }, "."],
    sub: "Buildings, routes, waste regulations, billing and self-service in one system. Built for municipal waste companies.",
  },
  horizon: { ...HERO_VARIANTS.horizon,
    tabLabel: "Horizon",
    eyebrow: "Customer service · Softera Horizon",
    h: ["Every channel ", { italic: "on one desktop" }, "."],
    sub: "Voice, email, chat, social and web forms on one desktop. The customer is identified automatically, backend systems open as tabs and full service history is right there.",
  },
};

function CalloutPin({ c }) {
  return (
    <div className="callout" style={{ left: c.x, top: c.y }}>
      <span className="callout__dot"></span>
      {c.dir === "right" && (
        <React.Fragment>
          <span className="callout__line callout__line--h" style={{ width: c.lineW, left: 9, top: 4 }}></span>
          <span className="callout__pill" style={{ left: c.lineW + 18, top: -10 }}>{c.label}</span>
        </React.Fragment>
      )}
      {c.dir === "down" && (
        <React.Fragment>
          <span className="callout__line callout__line--v" style={{ height: c.lineH, top: 9, left: 4 }}></span>
          <span className="callout__line callout__line--h" style={{ width: c.lineW, top: c.lineH + 9, left: 4 }}></span>
          <span className="callout__pill" style={{ left: c.lineW + 12, top: c.lineH + 1 }}>{c.label}</span>
        </React.Fragment>
      )}
      {c.dir === "up" && (
        <React.Fragment>
          <span className="callout__line callout__line--v" style={{ height: c.lineH, top: -c.lineH, left: 4 }}></span>
          <span className="callout__line callout__line--h" style={{ width: c.lineW, top: -c.lineH, left: 4 }}></span>
          <span className="callout__pill" style={{ left: c.lineW + 12, top: -c.lineH - 13 }}>{c.label}</span>
        </React.Fragment>
      )}
    </div>
  );
}

function MultiHero({ animated = true, autoRotate = true, intervalMs = 5000, showCallouts = true, lang = "fi" }) {
  const [tab, setTab] = useState("t360");
  const [progress, setProgress] = useState(0);
  const [phase, setPhase] = useState("in");
  const tickRef = useRef();

  const VARIANTS = lang === "fi" ? HERO_VARIANTS : HERO_VARIANTS_EN;

  useEffect(() => {
    if (!autoRotate) { setProgress(0); return; }
    const order = ["t360", "j360", "horizon"];
    let lastSlot = 0;
    const start = Date.now();
    tickRef.current = setInterval(() => {
      const elapsed = Date.now() - start;
      const slot = Math.floor(elapsed / intervalMs);
      const p = (elapsed % intervalMs) / intervalMs;
      setProgress(p);
      if (slot !== lastSlot) {
        lastSlot = slot;
        setPhase("out");
        setTimeout(() => {
          setTab((cur) => order[(order.indexOf(cur) + 1) % order.length]);
          setPhase("in");
        }, 240);
      }
    }, 80);
    return () => clearInterval(tickRef.current);
  }, [autoRotate, intervalMs]);

  function manualSelect(t) {
    setPhase("out");
    setTimeout(() => { setTab(t); setPhase("in"); }, 240);
    setProgress(0);
  }

  useEffect(() => { if (window.lucide) lucide.createIcons(); }, [tab]);

  const v = VARIANTS[tab];
  const Mock = v.Mock;

  return (
    <section className={"hero" + (animated ? " is-animated" : "")} data-screen-label="Etusivu hero">
      <div className="hero__inner">
        <div className="hero__copy">
          <div className="hero__tabs" role="tablist">
            {Object.values(VARIANTS).map((it) => (
              <button key={it.tabId}
                className={"hero__tab" + (tab === it.tabId ? " is-active" : "")}
                onClick={() => manualSelect(it.tabId)}>
                {it.tabLabel}
              </button>
            ))}
          </div>
          <div className="hero__eyebrow">{v.eyebrow}</div>
          <h1 className="hero__h">
            {v.h.map((part, i) =>
              typeof part === "string"
                ? <React.Fragment key={i}>{part}</React.Fragment>
                : <em key={i}>{part.italic}</em>
            )}
          </h1>
          <p className="hero__sub">{v.sub}</p>
          <div className="hero__ctas">
            <a className="btn btn--primary" href="#yhteys">{lang === "fi" ? "Pyydä demo" : "Request a demo"}</a>
            <a className="btn btn--ghost-light" href="#tuotteet">{lang === "fi" ? "Tutustu tuotteisiin →" : "Explore products →"}</a>
          </div>
          <div className="hero__trust">
            <div className="hero__trust-label">{lang === "fi" ? "Asiakkaitamme" : "Trusted by"}</div>
            <HeroCustomerMarquee />
          </div>
        </div>
        <div className="hero__stage">
          <div className={"hero__stage-frame" + (phase === "out" ? " is-leaving" : "")} key={tab}>
            <Mock />
            {showCallouts && v.callouts.map((c, i) => (
              <CalloutPin key={tab + i} c={c} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

window.MultiHero = MultiHero;
