/* global React */

// Termine block — renders the public-facing course cards.
// Data flows from the Admin page via localStorage (`konzentriert.termine`)
// with a fallback to window.TERMINE_DEFAULTS shipped in Onepager.html.
//
// Two card variants:
//   "a" — list-style (DateColumn with weekdays)
//   "b" — stamp-style (big day-month stamp + compact date list)

const STORAGE_KEY = "konzentriert.termine";

function HeartIcon({ size = 18, color = "#FF616E" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M12 21s-7-4.5-9.5-9.5C.7 7.6 3.4 4 7 4c2 0 3.5 1 5 3 1.5-2 3-3 5-3 3.6 0 6.3 3.6 4.5 7.5C19 16.5 12 21 12 21z" />
    </svg>);

}

// ─── Data normalisation ─────────────────────────────────────────────────
// Accepts both the legacy { t1, t2, t3 } shape and the new { list: [...] }
// shape so existing TERMINE_DEFAULTS keep working.
function normalize(source) {
  if (!source || typeof source !== "object") source = {};
  const list = Array.isArray(source.list) ?
  source.list :
  ["t1", "t2", "t3"].map((k) => source[k]).filter(Boolean);
  return {
    variant: source.variant === "b" ? "b" : "a",
    email: source.email || "",
    list: list.map((x, i) => ({
      id: x.id || `k${i}`,
      title: x.title || "",
      dates: Array.isArray(x.dates) ? x.dates.filter(Boolean) : [],
      time: x.time || "",
      location: x.location || "",
      ageGroup: x.ageGroup || "",
      seats: x.seats || "",
      active: x.active !== false
    }))
  };
}

function loadData() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return normalize(JSON.parse(raw));
  } catch (e) {/* fall through */}
  return normalize(window.TERMINE_DEFAULTS || {});
}

// ─── Date helpers ───────────────────────────────────────────────────────
const parseDates = (raw) => Array.isArray(raw) ? raw.filter(Boolean) : [];
const parse = (iso) => {
  const d = new Date(iso + "T00:00:00");
  return isNaN(d) ? null : d;
};
const weekdayShort = (d) => d.toLocaleDateString("de-DE", { weekday: "short" }).replace(".", "");
const monthLong = (d) => d.toLocaleDateString("de-DE", { month: "long" });
const monthYear = (d) => d.toLocaleDateString("de-DE", { month: "long", year: "numeric" });
const compactDM = (d) => `${d.getDate()}.${d.getMonth() + 1}.`;

function groupByMonth(isoDates) {
  const dates = isoDates.map(parse).filter(Boolean).sort((a, b) => a - b);
  const groups = [];
  for (const d of dates) {
    const key = `${d.getFullYear()}-${d.getMonth()}`;
    let g = groups[groups.length - 1];
    if (!g || g.key !== key) {
      g = { key, monthLabel: monthYear(d), items: [] };
      groups.push(g);
    }
    g.items.push({
      date: d,
      weekday: weekdayShort(d),
      day: String(d.getDate()).padStart(2, "0"),
      dayMonth: compactDM(d)
    });
  }
  return groups;
}

function summariseDates(isoDates) {
  const dates = isoDates.map(parse).filter(Boolean).sort((a, b) => a - b);
  if (!dates.length) return "";
  const consecutive = dates.every((d, i) => {
    if (i === 0) return true;
    const diff = (d - dates[i - 1]) / 86400000;
    return diff === 1;
  });
  if (consecutive && dates.length >= 4) {
    const s = dates[0],e = dates[dates.length - 1];
    const sameMonth = s.getMonth() === e.getMonth();
    return sameMonth ?
    `${s.getDate()}. – ${e.getDate()}. ${monthLong(e)} ${e.getFullYear()}` :
    `${compactDM(s)} – ${e.getDate()}. ${monthLong(e)} ${e.getFullYear()}`;
  }
  return dates.map((d) => `${weekdayShort(d)} ${compactDM(d)}`).join(" · ");
}

function renderTitle(title) {
  const parts = title.split("\\n");
  if (parts.length === 1) return title;
  return parts.map((p, i) => i === 0 ? p : [React.createElement("br", { key: i }), p]);
}

function mailtoLink(email, termin) {
  const summary = summariseDates(parseDates(termin.dates));
  const plainTitle = termin.title.replace(/\\n/g, " ");
  const subject = encodeURIComponent(`Anfrage: ${plainTitle} (${summary})`);
  const body = encodeURIComponent(
    `Liebe Julia, liebe Damaris,\n\n` +
    `ich interessiere mich für den Kurs:\n` +
    `· ${plainTitle}\n` +
    `· ${summary}\n` +
    `· ${termin.time || ""}\n\n` +
    `Mein Kind ist ___ Jahre alt.\n\n` +
    `Bitte melden Sie sich bei mir.\n\nViele Grüße,\n`
  );
  return `mailto:${email}?subject=${subject}&body=${body}`;
}

// ─── Date column for variant A ──────────────────────────────────────────
function DateColumn({ dates }) {
  const groups = groupByMonth(dates);
  if (!groups.length) return null;
  return (
    <div className="t-card-a__date">
      {groups.map((g, gi) =>
      <div className="dc__group" key={gi}>
          <div className="dc__month">{g.monthLabel}</div>
          <ul className="dc__list">
            {g.items.map((it, i) =>
          <li className="dc__row" key={i}>
                <span className="dc__wd">{it.weekday}</span>
                <span className="dc__day">{it.day}.</span>
              </li>
          )}
          </ul>
        </div>
      )}
    </div>);

}

function TerminCardA({ termin, email }) {
  const dates = parseDates(termin.dates);
  return (
    <article className="t-card-a">
      <DateColumn dates={dates} />
      <div className="t-card-a__body">
        <h3>{renderTitle(termin.title)}</h3>
        <ul className="meta">
          <li>
            <span className="meta__icon" aria-hidden="true">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF616E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M16 3v4M8 3v4M3 10h18" /></svg>
            </span>
            <span>{summariseDates(dates)}</span>
          </li>
          {termin.time &&
          <li>
              <span className="meta__icon" aria-hidden="true">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF616E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>
              </span>
              <span>{termin.time}</span>
            </li>
          }
          {termin.location &&
          <li>
              <span className="meta__icon" aria-hidden="true">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF616E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s7-7.5 7-13a7 7 0 1 0-14 0c0 5.5 7 13 7 13z" /><circle cx="12" cy="9" r="2.5" /></svg>
              </span>
              <span>{termin.location}</span>
            </li>
          }
          {termin.ageGroup &&
          <li>
              <span className="meta__icon" aria-hidden="true">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF616E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5" /><path d="M2.5 20c.6-3.4 3.2-5.5 6.5-5.5s5.9 2.1 6.5 5.5" /><circle cx="17" cy="7" r="2.5" /><path d="M14.5 14.5c2-.3 4.5.8 5.5 3.5" /></svg>
              </span>
              <span>{termin.ageGroup}</span>
            </li>
          }
        </ul>
      </div>
      <div className="t-card-a__cta">
        <a className="btn btn-primary" href={mailtoLink(email, termin)}>Jetzt anfragen →</a>
        {termin.seats && <span className="seats">{termin.seats}</span>}
      </div>
    </article>);

}

function TerminCardB({ termin, email }) {
  const dates = parseDates(termin.dates);
  return (
    <article className="t-card-b">
      <h3 className="t-card-b__title">{renderTitle(termin.title)}</h3>
      <ul className="t-card-b__dates">
        {dates.map((iso, i) => {
          const d = parse(iso);
          if (!d) return null;
          return (
            <li key={i}>
              <span>{weekdayShort(d)}</span>
              <span>{compactDM(d)}</span>
            </li>);

        })}
      </ul>
      <p className="t-card-b__meta">
        {termin.time && <><strong>{termin.time}</strong><br /></>}
        {termin.location}{termin.location && termin.ageGroup ? " · " : ""}{termin.ageGroup}
      </p>
      <div className="t-card-b__spacer"></div>
      <div className="t-card-b__cta">
        <a className="btn btn-primary" href={mailtoLink(email, termin)}>Jetzt anfragen →</a>
        {termin.seats && <span className="t-card-b__seats">{termin.seats}</span>}
      </div>
    </article>);

}

function TermineSection() {
  const [data, setData] = React.useState(loadData);

  // Live-sync from admin tab via storage events. (Same-tab updates also
  // re-fire by listening to a custom 'konzentriert:termine' event.)
  React.useEffect(() => {
    const onStorage = (e) => {
      if (e.key === STORAGE_KEY) setData(loadData());
    };
    const onLocal = () => setData(loadData());
    window.addEventListener("storage", onStorage);
    window.addEventListener("konzentriert:termine", onLocal);
    return () => {
      window.removeEventListener("storage", onStorage);
      window.removeEventListener("konzentriert:termine", onLocal);
    };
  }, []);

  const Card = data.variant === "b" ? TerminCardB : TerminCardA;
  const GridClass = data.variant === "b" ? "t-grid-b" : "t-grid-a";
  const visible = data.list.filter((t) => t.active !== false);

  return (
    <section id="termine" className="termine" data-screen-label="Termine">
      <div className="container">
        <div className="termine__head">
          <div>
            <span className="eyebrow">Nächste Kurse</span>
            <h2>Feste Termine<br />Begrenzte Plätze</h2>
          </div>
          <p>Unsere Kurse finden in Kleingruppen statt. Wir freuen uns auf Ihre Anfrage.


          </p>
        </div>

        {visible.length > 0 ?
        <div className={GridClass}>
            {visible.map((termin) =>
          <Card key={termin.id} termin={termin} email={data.email} />
          )}
          </div> :

        <p className="termine__empty">
            Aktuell sind keine offenen Termine eingetragen. Bitte schauen Sie bald wieder vorbei —
            oder schreiben Sie uns direkt an <a href={`mailto:${data.email}`}>{data.email}</a>.
          </p>
        }

        <div className="termine__foot">
          <HeartIcon size={16} />
          <span><strong>Tipp:</strong> Bitte fragen Sie früh an, denn die Plätze sind begrenzt.</span>
        </div>
      </div>
    </section>);

}

window.TermineSection = TermineSection;