// Timeline — "SCL em movimento". Horizontal rail of events (done/upcoming),
// reusing the same carousel hook + nav buttons as Services/Videos, collapsible via a toggle.

// Maps the event's display month (en/pt/es, abbreviated or full — whatever the current locale's
// data happens to use) to a 0-based month index, so dia/mes/ano can be turned into a real Date
// for sorting and for the done/upcoming comparison below, independent of the display string.
const TIMELINE_MONTH_INDEX = {
  jan: 0, january: 0, janeiro: 0, enero: 0,
  feb: 1, february: 1, fevereiro: 1, febrero: 1,
  mar: 2, march: 2, "março": 2, marco: 2, marzo: 2,
  apr: 3, april: 3, abril: 3,
  may: 4, maio: 4, mayo: 4,
  jun: 5, june: 5, junho: 5, junio: 5,
  jul: 6, july: 6, julho: 6, julio: 6,
  aug: 7, august: 7, agosto: 7,
  sep: 8, sept: 8, september: 8, setembro: 8, septiembre: 8, setiembre: 8,
  oct: 9, october: 9, outubro: 9, octubre: 9,
  nov: 10, november: 10, novembro: 10, noviembre: 10,
  dec: 11, december: 11, dezembro: 11, diciembre: 11,
};

// Events without a specific day (dia: null/empty) are treated as the 1st of that month.
const timelineEventDate = (ev) => {
  const monthIndex = TIMELINE_MONTH_INDEX[(ev.mes || "").trim().toLowerCase()] ?? 0;
  const day = ev.dia ? parseInt(ev.dia, 10) : 1;
  const year = parseInt(ev.ano, 10);
  return new Date(year, monthIndex, day);
};

const Timeline = () => {
  const [open, setOpen] = React.useState(true);
  const statusLabels = t("timeline.statusLabels");

  // Sorted ascending by date, then re-stamped with a status computed from today's date rather
  // than whatever (if anything) the data had — "upcoming" when the event is today or later,
  // "done" when it's in the past. Memoized since t("timeline.items") is static for the page's
  // lifetime and this otherwise re-parses/re-sorts on every carousel scroll re-render.
  const events = React.useMemo(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return t("timeline.items")
      .map((ev) => ({ ev, date: timelineEventDate(ev) }))
      .sort((a, b) => a.date - b.date)
      .map(({ ev, date }) => ({ ...ev, status: date >= today ? "upcoming" : "done" }));
  }, []);
  const { trackRef, setCardRef, atStart, atEnd, edge, updateEdges, scrollByCard, scrollable } =
    window.useCardCarousel(events.length);

  return (
    <section id="agenda" className="scl-section scl-section--navy scl-timeline">
      <div className="scl-container">
        <div className="scl-section__head scl-section__head--inverse">
          <div>
            <div className="scl-eyebrow scl-eyebrow--light"><span className="scl-rule" /> {t("timeline.eyebrow")}</div>
            <h2 className="scl-h2" style={{ color: "var(--fg-inverse)" }}>{t("timeline.title")}</h2>
          </div>
          <div>
            <p className="scl-lead scl-section__head-sub">
              {t("timeline.sub")}
            </p>
            <button
              type="button"
              className="scl-btn scl-btn--ghost-light"
              style={{ marginTop: 16 }}
              onClick={() => setOpen(o => !o)}
              aria-expanded={open}
              aria-controls="scl-timeline-panel"
            >
              {open ? t("timeline.hideLabel") : t("timeline.showLabel")}
              <Icon name={open ? "chevron-up" : "chevron-down"} size={16} />
            </button>
          </div>
        </div>

        {open && (
          <div id="scl-timeline-panel">
            <div
              className={"scl-carousel-fade" + (atEnd ? " is-end" : "")}
              style={{ "--carousel-fade-color": "var(--scl-navy-deep)" }}
            >
              <div className="scl-timeline-scroll" ref={trackRef} onScroll={updateEdges}>
                <div className="scl-timeline-rail-track">
                  <div className="scl-timeline-rail" aria-hidden="true" />
                  {events.map((ev, i) => {
                    const isPrevEdge = i === edge.first && !atStart;
                    const isNextEdge = i === edge.last && !atEnd;
                    const isEdge = isPrevEdge || isNextEdge;
                    const handleClick = () => {
                      if (!isEdge) return;
                      scrollByCard(isPrevEdge ? -1 : 1);
                    };
                    const card = (
                      <div className={"scl-timeline-card scl-timeline-card--" + ev.status}>
                        <div className="scl-timeline-card__top">
                          <div className="scl-timeline-card__date">
                            {ev.dia && <span className="scl-timeline-card__day">{ev.dia}</span>}
                            <span className="scl-timeline-card__month">{ev.mes}</span>
                            <span className="scl-timeline-card__year">{ev.ano}</span>
                          </div>
                          <span className="scl-timeline-card__icon"><Icon name={ev.icone || 'users'} size={16} /></span>
                          <h3 className="scl-timeline-card__title">{ev.titulo}</h3>
                        </div>
                        <p className="scl-timeline-card__desc">{ev.descricao}</p>
                      </div>
                    );
                    return (
                      <div
                        key={i}
                        ref={setCardRef(i)}
                        className={"scl-timeline-item" + (isEdge ? " scl-carousel-card--edge" : "")}
                        onClick={isEdge ? handleClick : undefined}
                      >
                        <div className="scl-timeline-node-slot">
                          <span className={"scl-timeline-node scl-timeline-node--" + ev.status} />
                        </div>
                        <span className="scl-timeline-connector" aria-hidden="true" />
                        <span className={"scl-timeline-badge scl-timeline-badge--" + ev.status}>
                          {statusLabels[ev.status]}
                        </span>
                        {ev.link ? (
                          <a
                            href={ev.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="scl-timeline-card-link"
                          >
                            {card}
                          </a>
                        ) : card}
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

            {scrollable && (
              <div className="scl-carousel-nav scl-carousel-nav--below">
                <button
                  type="button"
                  className="scl-carousel-nav-btn"
                  onClick={() => scrollByCard(-1)}
                  disabled={atStart}
                  aria-label={t("timeline.prevAria")}
                >
                  <Icon name="chevron-left" size={18} />
                </button>
                <button
                  type="button"
                  className="scl-carousel-nav-btn scl-carousel-nav-btn--next"
                  onClick={() => scrollByCard(1)}
                  disabled={atEnd}
                  aria-label={t("timeline.nextAria")}
                >
                  <Icon name="chevron-right" size={20} />
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
};

window.Timeline = Timeline;
