/* global React, useLang */
const { useMemo } = React;
// ============ About us / Empresa ============

const FOUNDERS = [
  { name: "Adrián Samartín", roleKey: "about.found.role", url: "https://www.linkedin.com/in/adriansamartin/", img: "assets/founders/founder_adrian_samartin_bw.png" },
  { name: "Ignacio de León", roleKey: "about.found.role", url: "https://www.linkedin.com/in/ignacio-de-leon-sorhuet-43733725/", img: "assets/founders/founder_ignacio_deleon_bw.png" },
  { name: "Guillermo de León", roleKey: "about.found.role", url: "https://www.linkedin.com/in/guillermo-de-le%C3%B3n-sorhuet-89402959/", img: "assets/founders/founder_guillermo_deleon_bw.png" }
];

function useTimeline() {
  const { t } = useLang();
  return useMemo(() =>
    Array.from({ length: 10 }, (_, i) => ({
      year: t(`about.tl.${i}.year`),
      title: t(`about.tl.${i}.title`),
      desc: t(`about.tl.${i}.desc`)
    })), [t]);
}

function useChallenges() {
  const { t } = useLang();
  return useMemo(() =>
    ["1", "2", "3", "4"].map((n) => ({
      num: n.padStart(2, "0"),
      title: t(`about.ch.${n}.title`),
      desc: t(`about.ch.${n}.desc`)
    })), [t]);
}

function AboutHero() {
  const { t, lang } = useLang();
  const segments = useMemo(() => [
    { type: "text", value: t("about.typ.l1") },
    { type: "br" },
    { type: "text", value: t("about.typ.l2") },
    { type: "underline", value: t("about.typ.u") },
    { type: "text", value: t("about.typ.l3") }
  ], [lang, t]);
  return (
    <section className="hero" id="top">
      <div className="container">
        <div className="hero-grid" style={{ gridTemplateColumns: "1fr" }}>
          <div className="hero-lower-left" style={{ maxWidth: 1100 }}>
            <span className="kicker"><span className="dot" />{t("about.hero.kicker")}</span>
            <h1 className="hero-headline hero-headline-narrow" style={{ marginTop: 22 }}>
              <TypedHeadline key={lang} segments={segments} />
            </h1>
            <p className="hero-sub" style={{ maxWidth: "62ch", marginTop: 36 }}>
              {t("about.hero.sub")}
            </p>
            <div className="fp-toc" aria-label="Secciones de esta página">
              <a href="#clientes">{t("about.toc.clients")}</a>
              <a href="#historia">{t("about.toc.history")}</a>
              <a href="#hitos">{t("about.toc.milestones")}</a>
              <a href="#fundadores">{t("about.toc.founders")}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ClientBand() {
  const { t } = useLang();
  const logos = [
    { src: "assets/logos_landing/logo_crowder.png", alt: "Crowder" },
    { src: "assets/logos_landing/logo_emprelatam.png", alt: "Emprelatam" },
    { src: "assets/logos_landing/logo_google.png", alt: "Google" },
    { src: "assets/logos_landing/logo_pagodespues.png", alt: "Pago después" },
    { src: "assets/logos_landing/logo_paigo.png", alt: "Paigo" },
    { src: "assets/logos_landing/ort_cie_logo.png", alt: "ORT — CIE" }
  ];
  return (
    <section id="clientes" className="client-band">
      <div className="container">
        <span className="label">{t("about.clients.label")}</span>
        <div className="client-logos">
          {logos.map((logo, i) => (
            <div key={i} className="client-logo">
              <img src={logo.src} alt={logo.alt} loading="lazy" decoding="async" />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function History() {
  const { t } = useLang();
  const CHALLENGES = useChallenges();
  return (
    <section id="historia" className="on-paper">
      <div className="container">
        <div className="section-head" style={{ alignItems: "start" }}>
          <div>
            <span className="kicker"><span className="dot" />{t("about.history.kicker")}</span>
            <h2 className="section" style={{ marginTop: 18 }}>
              {t("about.history.h2a")}<span className="underline-mark">{t("about.history.h2u")}</span>{t("about.history.h2b")}
            </h2>
          </div>
          <p className="lead" style={{ alignSelf: "start" }}>
            {t("about.history.lead")}
          </p>
        </div>

        <p className="lead" style={{ marginTop: 48, maxWidth: "none" }}>
          <strong style={{ color: "var(--ink)" }}>{t("about.history.bold")}</strong>{" "}
          {t("about.history.tail")}
        </p>

        <div className="challenges">
          {CHALLENGES.map(c => (
            <div key={c.num} className="challenge">
              <div className="num">— {c.num} · {t("about.challenge.num")}</div>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Milestones() {
  const { t } = useLang();
  const TIMELINE = useTimeline();
  const ref = React.useRef(null);
  const [active, setActive] = React.useState(false);
  const [idx, setIdx] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const total = TIMELINE.length;
  const STEP_MS = 4200;

  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setActive(true);
          obs.disconnect();
        }
      });
    }, { threshold: 0.2 });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    if (!active || !playing) return;
    if (idx >= total - 1) return;
    const timer = setTimeout(() => setIdx(i => Math.min(i + 1, total - 1)), STEP_MS);
    return () => clearTimeout(timer);
  }, [active, playing, idx, total]);

  const handleDotClick = (i) => {
    setIdx(i);
    setPlaying(false);
  };

  const fillPct = total <= 1 ? 0 : (idx / (total - 1)) * 100;

  return (
    <section id="hitos" className="on-ink">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="kicker"><span className="dot" />{t("about.mil.kicker")}</span>
            <h2 className="section" style={{ marginTop: 18, color: "#fff" }}>
              {t("about.mil.h2l1")}<br />
              {t("about.mil.h2l2a")}<span style={{ color: "var(--accent)" }}>{t("about.mil.h2l2b")}</span>{t("about.mil.h2l2c")}
            </h2>
          </div>
          <p className="lead" style={{ alignSelf: "end" }}>
            {t("about.mil.lead")}
          </p>
        </div>

        <div ref={ref} className="tl-carousel" aria-label={t("about.mil.carousel")}>
          <div className="tl-stage">
            {TIMELINE.map((m, i) => {
              const cls = i === idx ? "is-current" : i < idx ? "is-past" : "";
              return (
                <article key={i} className={`tl-slide ${cls}`} aria-hidden={i !== idx}>
                  <div>
                    <div className="yr">{m.year}</div>
                    <div className="meta">{t("about.mil.meta")} {String(i + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}</div>
                  </div>
                  <div>
                    <h3>{m.title}</h3>
                    <p>{m.desc}</p>
                  </div>
                </article>
              );
            })}
          </div>

          <div className="tl-rail">
            <div className="tl-rail-line"></div>
            <div className="tl-rail-fill" style={{ width: `${fillPct}%` }} />
            <div className="tl-rail-dots">
              {TIMELINE.map((m, i) => (
                <button
                  key={i}
                  className={`tl-rail-dot ${i < idx ? "is-past" : ""} ${i === idx ? "is-current" : ""}`}
                  onClick={() => handleDotClick(i)}
                  aria-label={`${t("about.mil.aria")} ${i + 1}: ${m.title}`}
                >
                  {(i === 0 || i === total - 1 || i === idx) && (
                    <span className="yr-label">{m.year}</span>
                  )}
                </button>
              ))}
            </div>
          </div>

          <div className="tl-controls">
            <div className="tl-counter">
              <strong>{String(idx + 1).padStart(2, "0")}</strong> / {String(total).padStart(2, "0")} · {TIMELINE[idx].year}
            </div>
            <button className="tl-pp" onClick={() => {
              if (idx >= total - 1) { setIdx(0); setPlaying(true); }
              else setPlaying(p => !p);
            }}>
              {idx >= total - 1 ? t("about.mil.restart") : playing ? t("about.mil.pause") : t("about.mil.play")}
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function Founders() {
  const { t } = useLang();
  return (
    <section id="fundadores" className="on-paper">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="kicker"><span className="dot" />{t("about.found.kicker")}</span>
            <h2 className="section" style={{ marginTop: 18 }}>
              {t("about.found.h2a")}<span className="underline-mark">{t("about.found.h2u")}</span>{t("about.found.h2b")}
            </h2>
          </div>
          <p className="lead" style={{ alignSelf: "end" }}>
            {t("about.found.lead")}
          </p>
        </div>

        <div className="founders">
          {FOUNDERS.map(f => (
            <div key={f.name} className="founder">
              <div className="founder-photo">
                <img src={f.img} alt={f.name} loading="lazy" />
              </div>
              <h3>{f.name}</h3>
              <div className="role">{t(f.roleKey)}</div>
              <a className="linkedin" href={f.url} target="_blank" rel="noopener noreferrer">
                {t("about.found.linkedin")} <span className="arr">↗</span>
              </a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function AboutCTA() {
  return <PageDemoCTA />;
}

window.AboutHero = AboutHero;
window.ClientBand = ClientBand;
window.History = History;
window.Milestones = Milestones;
window.Founders = Founders;
window.AboutCTA = AboutCTA;
