/* global React, ReactDOM, SECTIONS, isSectionDone, isSectionBlockingSubmit */
const { useState, useEffect, useRef, useMemo } = React;

const WEBHOOK_URL = "https://hook.eu2.make.com/0cbamhy1kea4n6n4apht3yv6z8fy1cqv";

const INITIAL = {
  // unternehmen
  firmenname: "", branche: "",
  rechnungStrasse: "", rechnungPLZ: "", rechnungOrt: "", rechnungLand: "Deutschland",
  ustId: "",
  kontaktName: "", kontaktEmail: "", kontaktTelefon: "",
  hatWebsite: "", websiteUrl: "",
  // zielgruppe
  zielgruppe: "", problem: "",
  // angebot
  leistungen: "", usp: "",
  // tone
  anrede: "", toneVerspielt: 30, toneMutig: 60, toneTechnisch: 40,
  // visuell
  stil: "", hatFarbe: "", primaerfarbe: "", referenzen: "",
  // uploads
  uploadLogo: [], uploadBilder: [], uploadDocs: [],
  // ziel
  hauptziel: "", cta: "",
  // struktur
  unterseiten: [], anmerkungen: "",
  // technik (domain & hosting — kunde besitzt, wir richten ein)
  hatDomain: "", domain: "", domainAnbieter: "", wunschDomain: "",
  hatHosting: "", hostingAnbieter: "",
};

// ── Build a structured prompt summary string ───────────────────────────────
function describeSlider(value, leftLabel, rightLabel) {
  const v = Number(value ?? 50);
  if (v <= 20) return `sehr ${leftLabel.toLowerCase()}`;
  if (v <= 40) return `eher ${leftLabel.toLowerCase()}`;
  if (v < 60)  return "ausgewogen";
  if (v <= 80) return `eher ${rightLabel.toLowerCase()}`;
  return `sehr ${rightLabel.toLowerCase()}`;
}

const STIL_LABEL = {
  modern: "Modern & Minimalistisch (klar, viel Whitespace, schwarze Typografie)",
  warm: "Warm & Persönlich (sanfte Farben, runde Formen, organisch)",
  bold: "Mutig & Auffällig (starke Farben, große Typo, starke Kontraste)",
  premium: "Premium & Edel (dunkle Töne, Serifen-Akzente, viel Ruhe)",
  tech: "Tech & Modern-B2B (Blau-Töne, Grids, Daten-fokussiert)",
  neutral: "Stil offen — die KI darf passend zur Branche vorschlagen",
};

const ZIEL_LABEL = {
  leads: "Leads & Anfragen sammeln (Formular-Anfragen, Angebots-Anfragen)",
  termine: "Termine buchen (Beratungs-/Erstgespräche)",
  verkauf: "Direkt online verkaufen",
  info: "Informieren & Vertrauen aufbauen",
  recruiting: "Mitarbeitende gewinnen (Karriere-Fokus)",
};

function buildPrompt(d) {
  const L = [];
  L.push("# Express-Website Briefing — Turm & Leufer (800 € Paket)");
  L.push("");
  L.push("Du erstellst eine erste optimierte Website-Version (Hauptseite + 2 Unterseiten) auf Basis dieses Briefings. Sprache: Deutsch.");
  L.push("");
  L.push("## 1. Unternehmen & Rechnung");
  L.push(`- Firma: ${d.firmenname || "—"}`);
  if (d.branche) L.push(`- Branche: ${d.branche}`);
  const addr = [d.rechnungStrasse, [d.rechnungPLZ, d.rechnungOrt].filter(Boolean).join(" "), d.rechnungLand].filter(Boolean).join(", ");
  if (addr) L.push(`- Rechnungsanschrift: ${addr}`);
  if (d.ustId) L.push(`- USt-IdNr.: ${d.ustId}`);
  L.push(`- Ansprechpartner:in: ${d.kontaktName || "—"} <${d.kontaktEmail || "—"}>${d.kontaktTelefon ? `, ${d.kontaktTelefon}` : ""}`);
  if (d.hatWebsite === "ja") {
    L.push(`- Bestehende Website: ${d.websiteUrl || "(URL nicht angegeben)"}`);
  } else if (d.hatWebsite === "nein") {
    L.push("- Bestehende Website: keine (Erstauftritt).");
  }
  L.push("");

  L.push("## 2. Zielgruppe & Problem");
  if (d.zielgruppe) L.push(`**Zielgruppe:** ${d.zielgruppe}`);
  if (d.problem)    L.push(`**Gelöstes Problem:** ${d.problem}`);
  L.push("");

  L.push("## 3. Angebot");
  if (d.leistungen) L.push("**Leistungen / Produkte:**\n" + d.leistungen.split("\n").map((s) => "  " + s).join("\n"));
  if (d.usp)        L.push(`\n**USP / Differenzierung:** ${d.usp}`);
  L.push("");

  L.push("## 4. Tone of Voice");
  L.push(`- Anrede: ${d.anrede === "du" ? "Du-Form (persönlich, modern)" : d.anrede === "sie" ? "Sie-Form (klassisch, formell)" : "—"}`);
  L.push(`- Tonalität: ${describeSlider(d.toneVerspielt, "Sachlich", "Verspielt")}, ${describeSlider(d.toneMutig, "Zurückhaltend", "Selbstbewusst")}, ${describeSlider(d.toneTechnisch, "Einfach", "Fachlich")}.`);
  L.push("");

  L.push("## 5. Visueller Stil");
  if (d.stil) L.push(`- Richtung: ${STIL_LABEL[d.stil] || d.stil}`);
  if (d.hatFarbe === "ja") {
    L.push(`- Markenfarbe (vorhanden): ${d.primaerfarbe || "(nicht angegeben)"}`);
  } else if (d.hatFarbe === "nein") {
    if (d.primaerfarbe) L.push(`- Markenfarbe-Wunsch: ${d.primaerfarbe} (Kund:in wählt aus Vorschlägen, finale Palette von uns)`);
    else                L.push("- Markenfarbe: noch offen — wir schlagen passend zur Branche vor.");
  }
  if (d.referenzen) {
    const refs = d.referenzen.split("\n").map((s) => s.trim()).filter(Boolean);
    if (refs.length) L.push(`- Referenzen (Look-and-Feel): ${refs.join(", ")}`);
  }
  L.push("");

  L.push("## 6. Material");
  const logoNames   = (d.uploadLogo   || []).map((f) => f.name);
  const bilderNames = (d.uploadBilder || []).map((f) => f.name);
  const docsNames   = (d.uploadDocs   || []).map((f) => f.name);
  L.push(`- Logo:       ${logoNames.length   ? logoNames.join(", ")   : "— (kein Upload)"}`);
  L.push(`- Bilder:     ${bilderNames.length ? bilderNames.join(", ") : "— (kein Upload)"}`);
  L.push(`- Dokumente:  ${docsNames.length   ? docsNames.join(", ")   : "— (kein Upload)"}`);
  L.push("");

  L.push("## 7. Hauptziel der Website");
  if (d.hauptziel) L.push(`- Primäres Ziel: ${ZIEL_LABEL[d.hauptziel] || d.hauptziel}`);
  if (d.cta)       L.push(`- Wichtigste Besucher-Handlung: „${d.cta}"`);
  L.push("");

  L.push("## 8. Seitenstruktur");
  L.push("- Hauptseite (Landingpage)");
  if (Array.isArray(d.unterseiten)) d.unterseiten.forEach((u) => L.push(`- Unterseite: ${u}`));
  L.push("- Impressum & Datenschutz (automatisch)");
  L.push("");

  L.push("## 9. Domain & Hosting");
  L.push("_Domain und Hosting laufen über den Kunden. Wir kümmern uns um Setup, DNS, SSL und Anbindung._");
  if (d.hatDomain === "ja") {
    L.push(`- Domain: vorhanden — ${d.domain || "(nicht angegeben)"}${d.domainAnbieter ? ` (Anbieter: ${d.domainAnbieter})` : ""}`);
  } else if (d.hatDomain === "nein") {
    L.push(`- Domain: noch nicht vorhanden${d.wunschDomain ? ` · Wunsch: ${d.wunschDomain}` : ""} → Anbieter empfehlen, gemeinsam registrieren.`);
  } else if (d.hatDomain === "unsicher") {
    L.push("- Domain: unklar — im Onboarding-Call klären.");
  }
  if (d.hatHosting === "ja") {
    L.push(`- Hosting: vorhanden${d.hostingAnbieter ? ` (Anbieter: ${d.hostingAnbieter})` : ""} → Eignung prüfen.`);
  } else if (d.hatHosting === "nein") {
    L.push("- Hosting: noch nicht vorhanden → Empfehlung aussprechen, einrichten.");
  } else if (d.hatHosting === "unsicher") {
    L.push("- Hosting: unklar — im Onboarding-Call klären.");
  }
  L.push("");

  if (d.anmerkungen) {
    L.push("## 10. Sonstige Anmerkungen");
    L.push(d.anmerkungen);
    L.push("");
  }

  L.push("---");
  L.push("Bitte erstelle eine erste, so optimierte wie mögliche Version. Konversions-fokussiert, DSGVO-konform, responsive, im Stil von Turm & Leufer (Webflow-Premium-Partner-Qualität).");
  return L.join("\n");
}

// ── Submit logic ──────────────────────────────────────────────────────────
async function submitToWebhook(data) {
  const prompt = buildPrompt(data);
  const fd = new FormData();

  // strip file objects from the structured payload — we'll attach files separately
  const structured = { ...data };
  const fileMeta = {};
  ["uploadLogo", "uploadBilder", "uploadDocs"].forEach((k) => {
    const files = data[k] || [];
    fileMeta[k] = files.map((f) => ({ name: f.name, size: f.size, type: f.type }));
    delete structured[k];
  });

  const payload = {
    paket: {
      name: "Express",
      preis_eur: 800,
      dauer: "24 Stunden",
      umfang: "Hauptseite + 2 Unterseiten · Design + Aufbau + DSGVO-Setup · Domain & Hosting werden vom Kunden gestellt, wir richten ein",
    },
    submittedAt: new Date().toISOString(),
    data: structured,
    files: fileMeta,
    prompt,
  };

  fd.append("payload", JSON.stringify(payload));
  fd.append("prompt", prompt);
  fd.append("paket", "Express (800€ — Live in 24h)");
  // also append top-level fields for convenient extraction in Make
  Object.entries(structured).forEach(([k, v]) => {
    if (Array.isArray(v)) fd.append(k, v.join(", "));
    else fd.append(k, v == null ? "" : String(v));
  });
  // attach files
  (data.uploadLogo   || []).forEach((f) => fd.append("logo", f, f.name));
  (data.uploadBilder || []).forEach((f) => fd.append("bilder", f, f.name));
  (data.uploadDocs   || []).forEach((f) => fd.append("dokumente", f, f.name));

  const res = await fetch(WEBHOOK_URL, { method: "POST", body: fd });
  if (!res.ok) throw new Error(`Webhook ${res.status}`);
  return res;
}

// ── Express banner ────────────────────────────────────────────────────────
function ExpressBanner() {
  return (
    <div className="banner">
      <div className="banner__pattern" />
      <div style={{ position: "relative", zIndex: 1 }}>
        <div className="banner__eyebrow">
          <span className="dot" />
          Dein Paket · Express
        </div>
        <h1>Deine Website. Live in 24 Stunden.</h1>
        <div className="banner__meta" style={{ display: "flex", gap: 8, marginTop: 18, flexWrap: "wrap" }}>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="16" height="5" rx="1.5"/><rect x="2" y="11" width="7" height="6" rx="1.5"/><rect x="11" y="11" width="7" height="6" rx="1.5"/></svg>
            Hauptseite + 2 Unterseiten
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="10" cy="10" r="7"/><path d="M3 10h14M10 3a14 14 0 010 14M10 3a14 14 0 000 14"/></svg>
            Domain & Hosting Setup
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 3v14M3 10h14"/><circle cx="10" cy="10" r="7"/><path d="M5 5l10 10"/></svg>
            Kein Abo
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="16" height="11" rx="2"/><path d="M6 17h8M10 14v3"/></svg>
            Moderne Landingpage
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="5" width="12" height="9" rx="1.5"/><rect x="14" y="8" width="5" height="6" rx="1"/><path d="M4 17h6"/><path d="M7 14v3"/></svg>
            Responsives Design
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#1E9CFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7l4 6 3-4 3 5 4-7"/></svg>
            Webflow Experten
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 3l1.2 3.6H18l-2.8 2 1.2 3.6L10 10 4.6 12.2l1.2-3.6L3 6.6h6.8z"/><path d="M7 15h6"/></svg>
            DSGVO-konform
          </div>
          <div className="banner__chip">
            <svg viewBox="0 0 20 20" fill="none" stroke="#1E9CFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 17l3-3m0 0l6-10a1.5 1.5 0 012 2L9 14m-2 0l2 2"/><path d="M14 3l3 3"/></svg>
            KI-Texterstellung
          </div>
        </div>
      </div>
      <div className="banner__price">
        <span className="label">Festpreis</span>
        <div className="value">800 €</div>
        <div className="meta">
          <div className="banner__chip" style={{ background: "rgba(30,156,255,.18)", borderColor: "rgba(30,156,255,.35)", color: "#BFE2FF" }}>
            <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="10" cy="10" r="7"/><path d="M10 6v4l3 2" strokeLinecap="round"/></svg>
            24 h Launch
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Section Card ──────────────────────────────────────────────────────────
function SectionCard({ section, index, data, set, isOpen, onToggle, sectionRef }) {
  const done = isSectionDone(section, data);
  const Component = section.Component;
  return (
    <div ref={sectionRef} className={`section-card${isOpen ? " is-open" : ""}${done ? " is-done" : ""}`} id={`sec-${section.id}`}>
      <button type="button" className="section-card__head" onClick={onToggle} aria-expanded={isOpen}>
        <div className="section-card__num">
          {done ? (
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M3 8l3 3 7-7" />
            </svg>
          ) : (
            String(index + 1).padStart(2, "0")
          )}
        </div>
        <div className="section-card__title">
          <h2>{section.title}</h2>
          <div className="sub">{section.sub}</div>
        </div>
        <div className={`section-card__badge${done ? " is-done" : ""}`}>
          {done ? "Fertig" : section.required.length > 0 ? "Erforderlich" : "Optional"}
        </div>
        <div className="section-card__chev">
          <svg viewBox="0 0 16 16"><path d="M3 6l5 5 5-5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
      </button>
      {isOpen ? (
        <div className="section-card__body">
          <Component d={data} set={set} />
        </div>
      ) : null}
    </div>
  );
}

// ── Sidebar ───────────────────────────────────────────────────────────────
function Sidebar({ data, openId, onJump, completion }) {
  return (
    <aside className="sidebar">
      <div className="sidebar__title">Onboarding</div>
      <div className="sidebar__list">
        {SECTIONS.map((s, i) => {
          const done = isSectionDone(s, data);
          const active = openId === s.id;
          return (
            <button
              key={s.id}
              className={`sidebar__item${active ? " is-active" : ""}${done ? " is-done" : ""}`}
              onClick={() => onJump(s.id)}
            >
              <span className="sidebar__num">
                {done ? (
                  <svg className="sidebar__check" viewBox="0 0 14 14"><path d="M3 7l3 3 5-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                ) : (
                  String(i + 1).padStart(2, "0")
                )}
              </span>
              <span className="sidebar__label">{s.title}</span>
            </button>
          );
        })}
      </div>
      <div className="sidebar__divider" />
      <div className="sidebar__meta">
        <div><b>Express-Paket</b> · 800 €</div>
        <div style={{ marginTop: 2 }}>Live in 24 Std. nach Briefing.</div>
        <div style={{ marginTop: 10, fontWeight: 600, color: "var(--tl-ink-900)" }}>
          {completion.done} / {completion.total} Sektionen
        </div>
      </div>

      <ContactCard />
    </aside>
  );
}

function ContactCard() {
  return (
    <div className="contact-card">
      <div className="contact-card__pattern" />
      <div className="contact-card__head">
        <div className="contact-card__avatar has-image">
          <img src="assets/til.jpg" alt="Til Leufer" className="contact-card__avatar-img" />
          <span className="contact-card__online" aria-hidden="true" />
        </div>
        <div className="contact-card__person">
          <span className="name">Til Kams</span>
          <span className="role">Gründer · Webflow Expert</span>
        </div>
      </div>
      <p className="contact-card__body">
        Noch Fragen zum Briefing oder zum Express-Paket? Sprich mich direkt an — ich helfe gerne.
      </p>
      <div className="contact-card__actions">
        <a href="https://cal.com/til-kams/15min" target="_blank" rel="noopener" className="contact-card__btn contact-card__btn--accent">
          <svg viewBox="0 0 20 20"><rect x="3" y="4" width="14" height="13" rx="2"/><path d="M3 8h14M7 2v4M13 2v4" strokeLinecap="round"/></svg>
          15-Min Call buchen
          <span className="arrow">→</span>
        </a>
        <a href="mailto:til@turmundleufer.de?subject=Frage%20zum%20Express-Paket" className="contact-card__btn">
          <svg viewBox="0 0 20 20"><rect x="2" y="4" width="16" height="12" rx="2"/><path d="M2 6l8 6 8-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          E-Mail schreiben
          <span className="arrow">→</span>
        </a>
      </div>
    </div>
  );
}

// ── Success screen ────────────────────────────────────────────────────────
function SuccessScreen({ data }) {
  const cal = "https://cal.com/til-kams/15min";
  return (
    <div className="success">
      <div className="success__icon">
        <svg viewBox="0 0 48 48" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 24l8 8 16-18" />
        </svg>
      </div>
      <div className="success__eyebrow">Briefing erhalten</div>
      <h1>Wir legen los, {data.kontaktName ? data.kontaktName.split(" ")[0] : "los geht's"}.</h1>
      <p className="lead">
        Deine Angaben sind angekommen — unsere Designer und unsere KI bauen jetzt die erste Version deiner Website. Buch dir gleich einen Slot für das Onboarding-Gespräch, damit wir die letzten Details klären.
      </p>

      <div className="success__card">
        <div className="pattern" />
        <div style={{ position: "relative" }}>
          <h3>Buche jetzt dein Onboarding-Gespräch</h3>
          <p>30 Minuten, Video-Call. Wir besprechen Inhalte, klären offene Fragen und du hast deine Website morgen live.</p>
          <div className="success__cta-row" style={{ justifyContent: "flex-start", marginTop: 8 }}>
            <a href={cal} target="_blank" rel="noopener" className="btn btn--primary">
              Termin auswählen
              <span className="ico">→</span>
            </a>
            <a href={`mailto:hello@turmundleufer.de?subject=Express-Briefing%20${encodeURIComponent(data.firmenname || "")}`} className="btn btn--ghost">
              Lieber per Mail
            </a>
          </div>
        </div>
      </div>

      <div className="success__steps">
        <div className="success__step">
          <div className="num">Schritt 1 · Jetzt</div>
          <h4>Onboarding-Call</h4>
          <p>15 min Video-Call. Inhalte abstimmen, Domain & Logins klären.</p>
        </div>
        <div className="success__step">
          <div className="num">Schritt 2 · 24h</div>
          <h4>Erste Version</h4>
          <p>Wir bauen mit KI-Unterstützung deine Hauptseite + 2 Unterseiten.</p>
        </div>
        <div className="success__step">
          <div className="num">Schritt 3 · Launch</div>
          <h4>Setup & live</h4>
          <p>Wir verbinden deine Domain, richten Hosting & SSL ein — du gehst live.</p>
        </div>
      </div>
    </div>
  );
}

// ── App ───────────────────────────────────────────────────────────────────
function App() {
  const [data, setData] = useState(INITIAL);
  const [openId, setOpenId] = useState(SECTIONS[0].id);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState(null);

  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  const completion = useMemo(() => {
    const done = SECTIONS.filter((s) => isSectionDone(s, data)).length;
    return { done, total: SECTIONS.length };
  }, [data]);

  const blockingOpen = SECTIONS.filter((s) => isSectionBlockingSubmit(s, data));
  const allRequiredOk = blockingOpen.length === 0;
  const progressPct = Math.round((completion.done / completion.total) * 100);

  const cardRefs = useRef({});

  const toggleSection = (id) => {
    setOpenId((curr) => (curr === id ? null : id));
  };

  const jumpTo = (id) => {
    setOpenId(id);
    requestAnimationFrame(() => {
      const el = cardRefs.current[id];
      if (el) {
        const top = el.getBoundingClientRect().top + window.scrollY - 84;
        window.scrollTo({ top, behavior: "smooth" });
      }
    });
  };

  const handleSubmit = async () => {
    setError(null);
    if (!allRequiredOk) {
      // open the first section that still has unfilled required fields
      const first = blockingOpen[0];
      if (first) jumpTo(first.id);
      setError("Bitte fülle noch die Pflichtfelder der hervorgehobenen Sektion aus.");
      return;
    }
    setSubmitting(true);
    try {
      await submitToWebhook(data);
      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (e) {
      setError("Da ist etwas schiefgelaufen. Bitte versuche es erneut oder schreib uns direkt: hello@turmundleufer.de");
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="app">
        <header className="app-bar">
          <div className="app-bar__inner">
            <div className="app-bar__brand">
              <img src="assets/Logo.svg" alt="Turm & Leufer" />
            </div>
            <div className="app-bar__crumbs">
              <span>Express-Paket</span>
              <span className="sep">·</span>
              <strong>Briefing eingereicht</strong>
            </div>
          </div>
        </header>
        <SuccessScreen data={data} />
      </div>
    );
  }

  return (
    <div className="app">
      <header className="app-bar">
        <div className="app-bar__inner">
          <div className="app-bar__brand">
            <img src="assets/Logo.svg" alt="Turm & Leufer" />
          </div>
          <div className="app-bar__crumbs">
            <span>Express-Paket</span>
            <span className="sep">·</span>
            <strong>Onboarding</strong>
          </div>
          <div className="app-bar__progress">
            <div className="app-bar__progress-text">{progressPct}%</div>
            <div className="app-bar__progress-bar">
              <div className="app-bar__progress-fill" style={{ width: `${progressPct}%` }} />
            </div>
          </div>
        </div>
      </header>

      <div className="shell">
        <Sidebar data={data} openId={openId} onJump={jumpTo} completion={completion} />

        <main className="content">
          <ExpressBanner />

          {SECTIONS.map((s, i) => (
            <SectionCard
              key={s.id}
              section={s}
              index={i}
              data={data}
              set={set}
              isOpen={openId === s.id}
              onToggle={() => toggleSection(s.id)}
              sectionRef={(el) => { if (el) cardRefs.current[s.id] = el; }}
            />
          ))}

          <div className="submit-row">
            <div className="submit-row__status">
              {allRequiredOk ? (
                <>
                  <span className="check">✓ Alles fertig</span>
                  <span>— Briefing kann abgeschickt werden.</span>
                </>
              ) : (
                <>
                  <span className="warn">⚠ Noch {blockingOpen.length} Sektion{blockingOpen.length === 1 ? "" : "en"}</span>
                  <span>mit Pflichtfeldern offen.</span>
                </>
              )}
            </div>
            <div className="submit-row__buttons">
              <a href="https://cal.com/til-kams/15min" target="_blank" rel="noopener" className="btn btn--ghost">Sprich direkt mit uns</a>
              <button
                type="button"
                className="btn btn--primary"
                onClick={handleSubmit}
                disabled={submitting}
              >
                {submitting ? (<><span className="spinner" /> Wird gesendet …</>) : (<>Briefing absenden <span className="ico">→</span></>)}
              </button>
            </div>
          </div>
          {error ? <div className="error-banner">⚠ {error}</div> : null}
        </main>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
