/* global React */
const { useState: useStateStory, useEffect: useEffectStory } = React;

const STORIES = {
  fi: [
  {
    id: "jsv",
    eye: "Järvi-Suomen Valokuitu · Valokuituliiketoiminta",
    quote: "On ollut paras käyttöönottoprojekti missä olen koskaan ollut mukana. Kiitos Softeralle joustavuudesta, jota ilman tämä ei olisi onnistunut. Jatkamme hyvillä mielin seuraavien steppien kanssa eteenpäin.",
    who: "Jari Juvonen", role: "Tietoliikennepäällikkö, Järvi-Suomen Valokuitu Oy",
    av: "JJ",
    href: "referenssit/jarvi-suomen-valokuitu.html",
    cta: "Lue koko tarina",
    stats: [
    { num: "< 3 kk", lbl: "yhteydenotosta tuotantoon" },
    { num: "Avaimet käteen", lbl: "-toimitus" },
    { num: "T360°", lbl: "BSS-järjestelmä" }]

  },
  {
    id: "neve",
    eye: "Napapiirin Energia ja Vesi · Energia, vesi, kuitu",
    quote: "Asiakaspalvelu on tehostunut, kun asiakkaiden tiedot, tarjoukset, tilaukset, töiden tilanne sekä laskutus ovat samassa järjestelmässä myyjien käden ulottuvilla.",
    who: "Mikko Veima", role: "Asiakkuuspäällikkö, Napapiirin Energia ja Vesi",
    av: "MV",
    href: "referenssit/napapiirin-energia-ja-vesi.html",
    cta: "Lue koko tarina",
    stats: [
    { num: "60 000+", lbl: "asiakasta" },
    { num: "Sähkö · Vesi · Kuitu", lbl: "yhdellä alustalla" },
    { num: "T360°", lbl: "yhdistää prosessit" }]

  }],

  en: [
  {
    id: "jsv",
    eye: "Järvi-Suomen Valokuitu · Fiber broadband",
    quote: "The best go-live project I've ever been part of. Thanks to Softera for the flexibility — without it this wouldn't have worked. We're moving forward with confidence to the next steps.",
    who: "Jari Juvonen", role: "Telecom Manager, Järvi-Suomen Valokuitu Oy",
    av: "JJ",
    href: "referenssit/jarvi-suomen-valokuitu.html",
    cta: "Read the full story",
    stats: [
    { num: "< 3 mo", lbl: "from first contact to go-live" },
    { num: "Turnkey", lbl: "delivery" },
    { num: "T360°", lbl: "BSS system" }]
  },
  {
    id: "neve",
    eye: "Napapiirin Energia ja Vesi · Energy, water, fiber",
    quote: "Customer service became more efficient when customer data, quotes, orders, work status and billing all live in the same system — right at the reps' fingertips.",
    who: "Mikko Veima", role: "Account Manager, Napapiirin Energia ja Vesi",
    av: "MV",
    href: "referenssit/napapiirin-energia-ja-vesi.html",
    cta: "Read the full story",
    stats: [
    { num: "60,000+", lbl: "customers" },
    { num: "Power · Water · Fiber", lbl: "on one platform" },
    { num: "T360°", lbl: "unifies the processes" }]
  }]

};

function Story({ lang = "fi" }) {
  const [idx, setIdx] = useStateStory(0);
  const data = STORIES[lang];
  const cur = data[idx];

  useEffectStory(() => {if (window.lucide) lucide.createIcons();}, [idx, lang]);

  return (
    <section className="story" id="asiakkaat" data-screen-label="Asiakastarinat">
      <div className="story__inner">
        <div className="story__head">
          <div>
            <div className="eyebrow">{lang === "fi" ? "Asiakastarinat" : "Customer stories"}</div>
            <h2>{lang === "fi" ? "Tunnemme arkitarpeet — emme ole geneerinen ohjelmistotalo." : "We know the day-to-day — we're not a generic vendor."}</h2>
          </div>
          <div className="story__nav">
            <button className="story__nav-btn" onClick={() => setIdx((idx - 1 + data.length) % data.length)} aria-label="prev"><i data-lucide="arrow-left"></i></button>
            <button className="story__nav-btn" onClick={() => setIdx((idx + 1) % data.length)} aria-label="next"><i data-lucide="arrow-right"></i></button>
          </div>
        </div>

        <div className="story__track">
          <div>
            <div className="eyebrow" style={{ color: "var(--softera-mint)", marginBottom: 18 }}>{cur.eye}</div>
            <p className="story__quote">"{cur.quote}"</p>
            <div className="story__by">
              <div className="story__by-av">{cur.av}</div>
              <div>
                <div className="story__by-name">{cur.who}</div>
                <div className="story__by-role">{cur.role}</div>
              </div>
            </div>
            {cur.href && (
              <a className="link-arrow" href={cur.href} style={{ marginTop: 22, color: "var(--softera-mint)" }}>
                {cur.cta || (lang === "fi" ? "Lue koko tarina" : "Read the full story")} <i data-lucide="arrow-right"></i>
              </a>
            )}
          </div>
          <div className="story__stats">
            {cur.stats.map((s, i) =>
            <div key={i}>
                <div className="story__stat-num">{s.num}</div>
                <div className="story__stat-lbl">{s.lbl}</div>
              </div>
            )}
          </div>
        </div>

        <div className="story__dots">
          {data.map((_, i) =>
          <button key={i} className={"story__dot" + (i === idx ? " is-active" : "")} onClick={() => setIdx(i)} aria-label={`Story ${i + 1}`}></button>
          )}
        </div>
      </div>
    </section>);

}

const HS_PORTAL_ID = "147819803";
const HS_FORM_GUID = "00a01636-69af-4b28-ae06-85feac1f43d1";
const HS_ENDPOINT = `https://api.hsforms.com/submissions/v3/integration/submit/${HS_PORTAL_ID}/${HS_FORM_GUID}`;

const CONSENT_TEXT = {
  fi: "Hyväksyn, että Softera käsittelee yhteystietojani yhteydenottoa varten tietosuojaselosteen mukaisesti.",
  en: "I agree that Softera processes my contact details for the purpose of contacting me, in accordance with the privacy policy."
};

function CtaBanner({ lang = "fi" }) {
  const [form, setForm] = useStateStory({ name: "", email: "", company: "", industry: "", consent: false });
  const [status, setStatus] = useStateStory("idle"); // idle | loading | success | error
  const [errorMsg, setErrorMsg] = useStateStory("");

  useEffectStory(() => { if (window.lucide) lucide.createIcons(); }, [status, lang]);

  const update = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value }));

  async function handleSubmit(e) {
    e.preventDefault();
    if (!form.consent) return;
    setStatus("loading");
    setErrorMsg("");

    const trimmed = form.name.trim();
    const spaceIdx = trimmed.indexOf(" ");
    const firstname = spaceIdx > 0 ? trimmed.slice(0, spaceIdx) : trimmed;
    const lastname = spaceIdx > 0 ? trimmed.slice(spaceIdx + 1).trim() : "";

    const payload = {
      fields: [
        { objectTypeId: "0-1", name: "firstname", value: firstname },
        { objectTypeId: "0-1", name: "lastname", value: lastname },
        { objectTypeId: "0-1", name: "email", value: form.email },
        { objectTypeId: "0-1", name: "company", value: form.company },
        { objectTypeId: "0-1", name: "industry", value: form.industry }
      ],
      context: {
        pageUri: typeof window !== "undefined" ? window.location.href : "",
        pageName: typeof document !== "undefined" ? document.title : ""
      },
      legalConsentOptions: {
        consent: {
          consentToProcess: true,
          text: CONSENT_TEXT[lang]
        }
      }
    };

    try {
      const res = await fetch(HS_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        const msg = (data.errors && data.errors[0] && data.errors[0].message) || data.message || `HTTP ${res.status}`;
        throw new Error(msg);
      }
      setStatus("success");
      setForm({ name: "", email: "", company: "", industry: "", consent: false });
    } catch (err) {
      setStatus("error");
      setErrorMsg(err.message || "");
    }
  }

  return (
    <section className="cta-banner" id="yhteys" data-screen-label="Yhteydenotto">
      <div className="cta-banner__inner">
        <div>
          <h2 className="cta-banner__h">{lang === "fi" ? "Näytetään miten tämä toimii teidän arjessa." : "Let's show you how this works in your day-to-day."}</h2>
          <p className="cta-banner__sub">
            {lang === "fi" ?
            "Varaa 30 minuuttia, niin keskustellaan miten järjestelmämme voisivat tukea ja tehostaa työtänne. " :
            "Book 30 minutes. We'll show you exactly what the system does in your industry, with real screens — no pitch."}
          </p>
          <ul style={{ listStyle: "none", padding: 0, margin: "0 0 28px", display: "flex", flexDirection: "column", gap: 8 }}>
            <li style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 14.5 }}><i data-lucide="check" style={{ width: 16, height: 16, color: "var(--softera-mint)" }}></i>{lang === "fi" ? "Live-demo teidän liiketoimintaa vasten" : "Live demo against your business"}</li>
            <li style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 14.5 }}><i data-lucide="check" style={{ width: 16, height: 16, color: "var(--softera-mint)" }}></i>{lang === "fi" ? "Karkea kustannusarvio palaverissa" : "A ballpark cost in the meeting"}</li>
            <li style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 14.5 }}><i data-lucide="check" style={{ width: 16, height: 16, color: "var(--softera-mint)" }}></i>{lang === "fi" ? "Asiakaskontaktit referenssejä varten" : "Customer references on request"}</li>
          </ul>
          <div className="cta-banner__ctas">
            <a className="btn btn--ghost-light" href="mailto:contact@softera.fi">contact@softera.fi <i data-lucide="arrow-up-right" style={{ width: 14, height: 14 }}></i></a>
          </div>
        </div>
        {status === "success" ? (
          <div className="cta-banner__form" id="yhteys-form">
            <div className="cta-banner__success">
              <i data-lucide="check-circle-2" style={{ width: 36, height: 36, color: "var(--softera-mint)" }}></i>
              <div className="cta-banner__form-h" style={{ marginTop: 14 }}>{lang === "fi" ? "Kiitos — viesti lähti perille." : "Thanks — your message is on its way."}</div>
              <p style={{ fontSize: 14, lineHeight: 1.55, color: "rgba(255,255,255,0.78)", margin: "8px 0 16px" }}>
                {lang === "fi" ? "Olemme sinuun yhteydessä työpäivän kuluessa. Tiimimme katsoo viestin läpi ennen kuin palaa asiaan." : "We'll be in touch within one business day. Our team reviews every message before getting back to you."}
              </p>
              <button type="button" className="btn btn--ghost-light" onClick={() => setStatus("idle")}>{lang === "fi" ? "Lähetä uusi" : "Send another"}</button>
            </div>
          </div>
        ) : (
          <form className="cta-banner__form" id="yhteys-form" onSubmit={handleSubmit} noValidate>
            <div className="cta-banner__form-h">{lang === "fi" ? "Jätä yhteystietosi, palaamme työpäivän kuluessa." : "Leave your details — we reply within 1 business day."}</div>
            <input type="text" required aria-required="true" value={form.name} onChange={update("name")} placeholder={lang === "fi" ? "Etunimi Sukunimi *" : "First Last *"} />
            <input type="email" required aria-required="true" value={form.email} onChange={update("email")} placeholder={lang === "fi" ? "Työsähköposti *" : "Work email *"} />
            <input type="text" required aria-required="true" value={form.company} onChange={update("company")} placeholder={lang === "fi" ? "Yritys *" : "Company *"} />
            <select required aria-required="true" value={form.industry} onChange={update("industry")}>
              <option value="" disabled>{lang === "fi" ? "Toimiala *" : "Industry *"}</option>
              <option value="Jätehuolto">{lang === "fi" ? "Jätehuolto" : "Waste management"}</option>
              <option value="Laajakaista / Telco">{lang === "fi" ? "Laajakaista / Telco" : "Broadband / Telco"}</option>
              <option value="Energia">{lang === "fi" ? "Energia" : "Energy"}</option>
              <option value="Kiinteistövuokraus">{lang === "fi" ? "Kiinteistövuokraus" : "Property rental"}</option>
              <option value="Muu">{lang === "fi" ? "Muu" : "Other"}</option>
            </select>
            <label className="cta-banner__consent">
              <input type="checkbox" required aria-required="true" checked={form.consent} onChange={update("consent")} />
              <span>
                {lang === "fi" ? (
                  <>Hyväksyn, että Softera käsittelee yhteystietojani yhteydenottoa varten <a href="tietosuoja.html" target="_blank" rel="noopener">tietosuojaselosteen</a> mukaisesti. *</>
                ) : (
                  <>I agree that Softera processes my contact details for the purpose of contacting me, in accordance with the <a href="tietosuoja.html" target="_blank" rel="noopener">privacy policy</a>. *</>
                )}
              </span>
            </label>
            <div className="cta-banner__required-note">{lang === "fi" ? "* Pakolliset kentät" : "* Required fields"}</div>
            {status === "error" && (
              <div className="cta-banner__error">
                {lang === "fi" ? "Lähetys epäonnistui. " : "Submission failed. "}
                {errorMsg && <span style={{ opacity: 0.8 }}>{errorMsg}</span>}
              </div>
            )}
            <button type="submit" className="btn btn--accent" disabled={status === "loading"} style={{ width: "100%", justifyContent: "center" }}>
              {status === "loading" ? (lang === "fi" ? "Lähetetään…" : "Sending…") : (lang === "fi" ? "Pyydä yhteydenottoa" : "Request a call")}
            </button>
          </form>
        )}
      </div>
    </section>);

}

function SiteFooter({ lang = "fi", homeHref = "Etusivu.html" }) {
  return (
    <footer className="site-footer" data-screen-label="Footer">
      <div className="site-footer__inner">
        <div className="site-footer__brand">
          <a href={homeHref} aria-label="Softera" className="site-footer__brand-link">
            <img src="assets/softera-logo-white.png" alt="" />
          </a>
          <div className="site-footer__contact">
            <span><i data-lucide="mail"></i>contact@softera.fi</span>
            <span><i data-lucide="phone"></i>+358 9 2310 2040</span>
            <span><i data-lucide="map-pin"></i>Sokerilinnantie 11 A (Sola Business Valley), 02600 Espoo</span>
          </div>
        </div>
        <div className="site-footer__side">
          <div className="site-footer__social-h">{lang === "fi" ? "Seuraa meitä" : "Follow us"}</div>
          <div className="site-footer__social">
            <a href="https://linkedin.com/company/softera-oy" target="_blank" rel="noopener" aria-label="Softera LinkedInissä" className="site-footer__sicon">
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.86 0-2.14 1.45-2.14 2.95v5.66H9.36V9h3.41v1.56h.05c.47-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 11-.001-4.121A2.06 2.06 0 015.34 7.43zM7.12 20.45H3.55V9h3.57v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z" />
              </svg>
            </a>
            <a href="https://instagram.com/softeraoy" target="_blank" rel="noopener" aria-label="Softera Instagramissa" className="site-footer__sicon">
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.72 3.72 0 01-1.38-.9 3.72 3.72 0 01-.9-1.38c-.16-.42-.36-1.06-.41-2.23C2.17 15.58 2.16 15.2 2.16 12s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16zM12 0C8.74 0 8.33.01 7.05.07 5.78.13 4.9.33 4.14.63a5.9 5.9 0 00-2.13 1.39A5.9 5.9 0 00.63 4.14C.33 4.9.13 5.78.07 7.05.01 8.33 0 8.74 0 12s.01 3.67.07 4.95c.06 1.27.26 2.15.56 2.91.31.79.73 1.46 1.39 2.13.66.66 1.34 1.08 2.13 1.39.76.3 1.64.5 2.91.56C8.33 23.99 8.74 24 12 24s3.67-.01 4.95-.07c1.27-.06 2.15-.26 2.91-.56a5.9 5.9 0 002.13-1.39 5.9 5.9 0 001.39-2.13c.3-.76.5-1.64.56-2.91.06-1.28.07-1.69.07-4.95s-.01-3.67-.07-4.95c-.06-1.27-.26-2.15-.56-2.91a5.9 5.9 0 00-1.39-2.13A5.9 5.9 0 0019.86.63C19.1.33 18.22.13 16.95.07 15.67.01 15.26 0 12 0zm0 5.84a6.16 6.16 0 100 12.32 6.16 6.16 0 000-12.32zm0 10.16a4 4 0 110-8 4 4 0 010 8zm7.84-10.4a1.44 1.44 0 11-2.88 0 1.44 1.44 0 012.88 0z" />
              </svg>
            </a>
          </div>
        </div>
      </div>
      <div className="site-footer__bottom">
        <span className="site-footer__copy">© 2026 Softera Oy — Y-tunnus 1524748-7</span>
        <a href="tietosuoja.html" className="site-footer__legal">{lang === "fi" ? "Tietosuojaseloste" : "Privacy policy"}</a>
        <span className="site-footer__spacer"></span>
      </div>
    </footer>);

}

window.Story = Story;
window.CtaBanner = CtaBanner;
window.SiteFooter = SiteFooter;