// SOLCOM Website-Abnahme · Feedbacks — geteilter Stream aller Tester.
// Jeder sieht alle Feedbacks (mit Namensvermerk); bearbeiten/löschen nur die eigenen.
(function () {
  const DS = window.AdessoPlaybooksDesignSystem_29634e;
  const { Button, Badge } = DS;

  const PRIO_TONE = { Niedrig: "var(--ink-400)", Mittel: "var(--blue-500)", Hoch: "var(--warning)", Kritisch: "var(--danger)" };
  const MONO = { fontFamily: "var(--font-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-500)" };

  function fmtDate(ts) {
    if (!ts) return "";
    try { return new Date(ts).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" }); }
    catch (e) { return ""; }
  }

  function PrioChips({ value, priorities, onChange }) {
    const list = priorities || ["Niedrig", "Mittel", "Hoch", "Kritisch"];
    return (
      <div style={{ display: "inline-flex", gap: 6, flexWrap: "wrap" }}>
        {list.map((p) => {
          const active = p === value;
          return (
            <button key={p} onClick={() => onChange(p)}
              style={{
                cursor: "pointer", font: "inherit", fontSize: 12, padding: "4px 10px",
                borderRadius: "var(--radius-full)", border: "1px solid",
                borderColor: active ? PRIO_TONE[p] : "var(--ink-200)",
                background: active ? PRIO_TONE[p] : "#fff",
                color: active ? "#fff" : "var(--ink-600)",
                transition: "all .12s ease",
              }}>
              {p}
            </button>
          );
        })}
      </div>
    );
  }

  function PrioDot({ p }) {
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: PRIO_TONE[p] || "var(--ink-500)" }}>
        <i className="ph-fill ph-circle" style={{ fontSize: 9 }} /> {p}
      </span>
    );
  }

  // Eigenes Feedback: bearbeiten (Text + Priorität) und löschen.
  function MyEntryCard({ f, priorities, onEdit, onDelete }) {
    const [text, setText] = React.useState(f.text);
    const [priority, setPriority] = React.useState(f.priority);

    return (
      <div style={{ background: "#fff", border: "1px solid var(--blue-200, var(--ink-200))", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-1)", padding: "14px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10, flexWrap: "wrap" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, color: "var(--ink-900)" }}>
            <i className="ph-fill ph-user-circle" style={{ fontSize: 16, color: "var(--blue-500)" }} /> {f.authorName}
          </span>
          <Badge tone="blue">Du</Badge>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-400)" }}>{fmtDate(f.updatedAt)}</span>
          <button onClick={() => onDelete(f.id)} title="Feedback löschen"
            style={{ marginLeft: "auto", cursor: "pointer", border: "none", background: "none", color: "var(--ink-400)", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, font: "inherit", padding: 4 }}
            onMouseEnter={(e) => { e.currentTarget.style.color = "var(--danger)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = "var(--ink-400)"; }}>
            <i className="ph ph-trash" style={{ fontSize: 15 }} /> Löschen
          </button>
        </div>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          onBlur={() => { if (text !== f.text) onEdit(f.id, { text }); }}
          rows={3}
          style={{
            width: "100%", boxSizing: "border-box", resize: "vertical",
            fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.55, color: "var(--ink-900)",
            padding: "11px 13px", borderRadius: "var(--radius-md)", background: "var(--ink-50)",
            border: "1.5px solid var(--ink-200)", outline: "none",
          }}
          onFocus={(e) => { e.target.style.borderColor = "var(--blue-500)"; }}
        />
        <div style={{ marginTop: 10 }}>
          <PrioChips value={priority} priorities={priorities} onChange={(p) => { setPriority(p); onEdit(f.id, { priority: p }); }} />
        </div>
      </div>
    );
  }

  // Fremdes Feedback: read-only.
  function OtherEntryCard({ f }) {
    return (
      <div style={{ background: "var(--ink-50)", border: "1px solid var(--ink-200)", borderRadius: "var(--radius-lg)", padding: "14px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, flexWrap: "wrap" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, color: "var(--ink-800)" }}>
            <i className="ph-fill ph-user-circle" style={{ fontSize: 16, color: "var(--ink-400)" }} /> {f.authorName}
          </span>
          <PrioDot p={f.priority} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-400)", marginLeft: "auto" }}>{fmtDate(f.updatedAt)}</span>
        </div>
        <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-800)", whiteSpace: "pre-wrap" }}>{f.text}</div>
      </div>
    );
  }

  // Reinen Text aus HTML ableiten, um leere Eingaben zu erkennen.
  function htmlToText(html) {
    const tmp = document.createElement("div");
    tmp.innerHTML = html || "";
    return (tmp.textContent || tmp.innerText || "").replace(/ /g, " ").trim();
  }

  // Gerenderter HTML-Inhalt mit sinnvollen Resets für p/ul/ol/li/strong/em.
  function RichContent({ html }) {
    return (
      <div
        className="sc-richcontent"
        style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-800)" }}
        dangerouslySetInnerHTML={{ __html: html || "" }}
      />
    );
  }

  // Eigenständiger WYSIWYG-Editor (contentEditable + execCommand-Toolbar).
  function RichTextEditor({ valueHtml, onChangeHtml }) {
    const ref = React.useRef(null);
    const seeded = React.useRef(false);
    const [focused, setFocused] = React.useState(false);

    React.useEffect(() => {
      const el = ref.current;
      if (el && !seeded.current) {
        el.innerHTML = valueHtml || "";
        seeded.current = true;
      }
    }, []);

    const exec = (cmd) => {
      const el = ref.current;
      if (el) el.focus();
      try { document.execCommand(cmd, false, null); } catch (e) { /* ignore */ }
      if (el && onChangeHtml) onChangeHtml(el.innerHTML);
    };

    const ToolBtn = ({ cmd, icon, title }) => (
      <button type="button" title={title} onMouseDown={(e) => { e.preventDefault(); exec(cmd); }}
        style={{
          cursor: "pointer", border: "1px solid var(--ink-200)", background: "#fff",
          width: 32, height: 30, borderRadius: "var(--radius-md)", color: "var(--ink-600)",
          display: "inline-flex", alignItems: "center", justifyContent: "center", font: "inherit",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = "var(--ink-100)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = "#fff"; }}>
        <i className={icon} style={{ fontSize: 16 }} />
      </button>
    );

    return (
      <div>
        <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
          <ToolBtn cmd="bold" icon="ph-bold ph-text-b" title="Fett" />
          <ToolBtn cmd="italic" icon="ph-bold ph-text-italic" title="Kursiv" />
          <ToolBtn cmd="insertUnorderedList" icon="ph-bold ph-list-bullets" title="Aufzählung" />
          <ToolBtn cmd="insertOrderedList" icon="ph-bold ph-list-numbers" title="Nummerierte Liste" />
        </div>
        <div
          ref={ref}
          contentEditable
          suppressContentEditableWarning
          data-placeholder="Beschreibe dein Feedback…"
          onInput={(e) => { if (onChangeHtml) onChangeHtml(e.currentTarget.innerHTML); }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          className="sc-richeditor sc-richcontent"
          style={{
            minHeight: 140, width: "100%", boxSizing: "border-box",
            padding: "11px 13px", borderRadius: "var(--radius-md)", background: "#fff",
            border: "1.5px solid " + (focused ? "var(--blue-500)" : "var(--ink-200)"),
            outline: "none", fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.55,
            color: "var(--ink-900)", overflowY: "auto",
          }}
        />
      </div>
    );
  }

  // Modal zum Erstellen/Bearbeiten von allgemeinem Feedback.
  function GeneralFeedbackModal({ initialHtml, initialPriority, mode, onSubmit, onClose }) {
    const [html, setHtml] = React.useState(initialHtml || "");
    const [priority, setPriority] = React.useState(initialPriority || "Mittel");
    const isEdit = mode === "edit";
    const empty = htmlToText(html) === "";

    React.useEffect(() => {
      const onKey = (e) => { if (e.key === "Escape") onClose(); };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, []);

    const submit = () => { if (!empty) onSubmit(html, priority); };

    return (
      <div onClick={onClose}
        style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.45)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
        <div onClick={(e) => e.stopPropagation()}
          style={{ background: "#fff", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-2)", width: "100%", maxWidth: 620, maxHeight: "calc(100vh - 40px)", overflowY: "auto", padding: "24px 26px" }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12, marginBottom: 16 }}>
            <span style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--blue-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <i className="ph-duotone ph-chat-circle-dots" style={{ fontSize: 20, color: "var(--blue-500)" }} />
            </span>
            <div style={{ flex: 1 }}>
              <h2 style={{ fontFamily: "var(--font-cond)", fontSize: 24, fontWeight: 500, margin: 0, color: "var(--ink-1000)" }}>{isEdit ? "Feedback bearbeiten" : "Feedback melden"}</h2>
              <p style={{ margin: "4px 0 0", fontSize: 13.5, color: "var(--ink-600)" }}>Allgemeines, testfall-unabhängiges Feedback. Landet in der Kategorie „Allgemein".</p>
            </div>
            <button onClick={onClose} title="Schließen"
              style={{ cursor: "pointer", border: "none", background: "none", color: "var(--ink-400)", display: "inline-flex", padding: 4 }}>
              <i className="ph ph-x" style={{ fontSize: 18 }} />
            </button>
          </div>

          <RichTextEditor valueHtml={initialHtml || ""} onChangeHtml={setHtml} />

          <div style={{ marginTop: 16 }}>
            <div style={{ ...MONO, marginBottom: 8 }}>Priorität</div>
            <PrioChips value={priority} priorities={["Niedrig", "Mittel", "Hoch", "Kritisch"]} onChange={setPriority} />
          </div>

          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 22 }}>
            <Button variant="ghost" size="sm" onClick={onClose}>Abbrechen</Button>
            <Button size="sm" icon={isEdit ? "ph-bold ph-check" : "ph-bold ph-paper-plane-tilt"} disabled={empty} onClick={submit}>{isEdit ? "Speichern" : "Senden"}</Button>
          </div>
        </div>
      </div>
    );
  }

  // Allgemein-Eintrag: eigener (bearbeiten/löschen) oder fremder (read-only).
  function GeneralEntryCard({ f, mine, onEditClick, onDelete }) {
    return (
      <div style={{ background: mine ? "#fff" : "var(--ink-50)", border: "1px solid " + (mine ? "var(--blue-200, var(--ink-200))" : "var(--ink-200)"), borderRadius: "var(--radius-lg)", boxShadow: mine ? "var(--shadow-1)" : "none", padding: "14px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, flexWrap: "wrap" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, color: mine ? "var(--ink-900)" : "var(--ink-800)" }}>
            <i className="ph-fill ph-user-circle" style={{ fontSize: 16, color: mine ? "var(--blue-500)" : "var(--ink-400)" }} /> {f.authorName}
          </span>
          {mine ? <Badge tone="blue">Du</Badge> : null}
          <PrioDot p={f.priority} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-400)", marginLeft: "auto" }}>{fmtDate(f.updatedAt || f.createdAt)}</span>
        </div>
        <RichContent html={f.text} />
        {mine ? (
          <div style={{ display: "flex", gap: 14, marginTop: 12 }}>
            <button onClick={onEditClick} title="Feedback bearbeiten"
              style={{ cursor: "pointer", border: "none", background: "none", color: "var(--ink-500)", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, font: "inherit", padding: 0 }}
              onMouseEnter={(e) => { e.currentTarget.style.color = "var(--blue-500)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = "var(--ink-500)"; }}>
              <i className="ph ph-pencil-simple" style={{ fontSize: 15 }} /> Bearbeiten
            </button>
            <button onClick={() => onDelete(f.id)} title="Feedback löschen"
              style={{ cursor: "pointer", border: "none", background: "none", color: "var(--ink-500)", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, font: "inherit", padding: 0 }}
              onMouseEnter={(e) => { e.currentTarget.style.color = "var(--danger)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = "var(--ink-500)"; }}>
              <i className="ph ph-trash" style={{ fontSize: 15 }} /> Löschen
            </button>
          </div>
        ) : null}
      </div>
    );
  }

  function FeedbackScreen({ me, feedback, priorities, onBack, onEdit, onDelete, onReportGeneral }) {
    const S = window.SOLCOM;
    const myEmail = me && me.email;
    const { isMobile } = window.SC_useViewport();
    const [onlyMine, setOnlyMine] = React.useState(false);
    const [modal, setModal] = React.useState(null); // null | { mode:"create" } | { mode:"edit", entry }

    // Styles für gerenderten HTML-Inhalt + Editor-Placeholder (einmalig).
    React.useEffect(() => {
      if (document.getElementById("sc-richtext-style")) return;
      const st = document.createElement("style");
      st.id = "sc-richtext-style";
      st.textContent =
        ".sc-richcontent p{margin:0 0 8px}.sc-richcontent p:last-child{margin-bottom:0}" +
        ".sc-richcontent ul,.sc-richcontent ol{margin:0 0 8px;padding-left:22px}" +
        ".sc-richcontent li{margin:2px 0}.sc-richcontent strong{font-weight:600}.sc-richcontent em{font-style:italic}" +
        ".sc-richeditor:empty:before{content:attr(data-placeholder);color:var(--ink-400)}";
      document.head.appendChild(st);
    }, []);

    const all = feedback || [];
    const filtered = onlyMine ? all.filter((f) => f.authorEmail === myEmail) : all;
    const testerCount = new Set(all.map((f) => f.authorEmail)).size;

    // Allgemeines Feedback separat (nicht in window.SOLCOM.areas), neueste zuerst.
    const generalAll = filtered.filter((f) => f.kind === "general").sort((a, b) => b.createdAt - a.createdAt);

    // Nach Bereich → Testfall gruppieren, in Content-Reihenfolge (ohne Allgemein-Einträge).
    const byArea = [];
    (S && S.areas ? S.areas : []).forEach((a) => {
      const cases = [];
      a.cases.forEach((c) => {
        const entries = filtered.filter((f) => f.kind !== "general" && f.caseId === c.id).sort((x, y) => x.createdAt - y.createdAt);
        if (entries.length) cases.push({ c, entries });
      });
      if (cases.length) byArea.push({ a, cases });
    });

    const hasContent = generalAll.length > 0 || byArea.length > 0;

    const FilterBtn = ({ active, onClick, children }) => (
      <button onClick={onClick} style={{
        cursor: "pointer", font: "inherit", fontSize: 13, fontWeight: 500, padding: "6px 14px",
        borderRadius: "var(--radius-full)", border: "1px solid " + (active ? "var(--blue-500)" : "var(--ink-200)"),
        background: active ? "var(--blue-500)" : "#fff", color: active ? "#fff" : "var(--ink-600)",
      }}>{children}</button>
    );

    return (
      <div style={{ background: "var(--ink-50)", minHeight: 560 }}>
        <div style={{ maxWidth: 900, margin: "0 auto", padding: isMobile ? "0 18px 56px" : "0 40px 64px" }}>
          <div style={{ paddingTop: 28 }}>
            <Button variant="ghost" size="sm" icon="ph-bold ph-arrow-left" onClick={onBack} style={{ background: "#fff" }}>Zum Dashboard</Button>
          </div>

          <div style={{ padding: "22px 0 22px", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 260 }}>
              <h1 style={{ fontFamily: "var(--font-cond)", fontSize: isMobile ? 30 : 42, fontWeight: 500, letterSpacing: "-.015em", lineHeight: 1.04, margin: 0, color: "var(--ink-1000)" }}>Feedbacks</h1>
              <p style={{ margin: "12px 0 0", fontSize: 16, color: "var(--ink-600)", maxWidth: "62ch" }}>
                Gemeinsam gesammeltes Feedback aller Tester — nach Bereich und Testfall. Du siehst alles; bearbeiten und löschen kannst du nur deine eigenen Einträge.
              </p>
            </div>
            <Button size="sm" icon="ph-bold ph-lightbulb" onClick={() => setModal({ mode: "create" })} style={{ marginTop: 6, flexShrink: 0 }}>Allgemeines Feedback melden</Button>
          </div>

          {/* summary + filter */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "14px 20px", background: "#fff", border: "1px solid var(--ink-200)", borderRadius: "var(--radius-xl)", marginBottom: 22, flexWrap: "wrap" }}>
            <span style={{ fontSize: 14.5, color: "var(--ink-700)" }}>
              <b style={{ color: "var(--ink-1000)" }}>{all.length}</b> {all.length === 1 ? "Feedback" : "Feedbacks"} · <b style={{ color: "var(--ink-1000)" }}>{testerCount}</b> {testerCount === 1 ? "Tester" : "Tester"}
            </span>
            <div style={{ display: "flex", gap: 8 }}>
              <FilterBtn active={!onlyMine} onClick={() => setOnlyMine(false)}>Alle</FilterBtn>
              <FilterBtn active={onlyMine} onClick={() => setOnlyMine(true)}>Nur meine</FilterBtn>
            </div>
          </div>

          {!hasContent ? (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, padding: "64px 24px", background: "#fff", border: "1px dashed var(--ink-300)", borderRadius: "var(--radius-xl)", textAlign: "center" }}>
              <i className="ph-duotone ph-chat-circle-text" style={{ fontSize: 44, color: "var(--ink-400)" }} />
              <div style={{ fontFamily: "var(--font-cond)", fontSize: 24, fontWeight: 500, color: "var(--ink-900)" }}>{onlyMine ? "Noch kein eigenes Feedback" : "Noch kein Feedback"}</div>
              <p style={{ margin: 0, fontSize: 14.5, color: "var(--ink-600)", maxWidth: "46ch" }}>
                Feedback entsteht in den Bereichen: einen Testfall öffnen, bewerten und im Feld „Mein Feedback" beschreiben. Allgemeines Feedback meldest du oben über „Feedback melden".
              </p>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 34 }}>
              {generalAll.length > 0 ? (
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
                    <span style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--blue-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                      <i className="ph-duotone ph-chat-circle-dots" style={{ fontSize: 20, color: "var(--blue-500)" }} />
                    </span>
                    <h2 style={{ fontFamily: "var(--font-cond)", fontSize: 24, fontWeight: 500, margin: 0, color: "var(--ink-1000)" }}>Allgemein</h2>
                    <span style={{ ...MONO, marginLeft: 4 }}>{generalAll.length}</span>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    {generalAll.map((f) => (
                      <GeneralEntryCard
                        key={f.id}
                        f={f}
                        mine={f.authorEmail === myEmail}
                        onEditClick={() => setModal({ mode: "edit", entry: f })}
                        onDelete={onDelete}
                      />
                    ))}
                  </div>
                </div>
              ) : null}

              {byArea.map(({ a, cases }) => (
                <div key={a.id}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
                    <span style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--blue-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                      <i className={a.icon} style={{ fontSize: 20, color: "var(--blue-500)" }} />
                    </span>
                    <h2 style={{ fontFamily: "var(--font-cond)", fontSize: 24, fontWeight: 500, margin: 0, color: "var(--ink-1000)" }}>{a.name}</h2>
                  </div>

                  <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
                    {cases.map(({ c, entries }) => (
                      <div key={c.id}>
                        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                          <i className="ph ph-list-checks" style={{ fontSize: 15, color: "var(--ink-400)" }} />
                          <span style={{ fontSize: 15, fontWeight: 600, color: "var(--ink-900)" }}>{c.title}</span>
                          <span style={{ ...MONO, marginLeft: 4 }}>{entries.length}</span>
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                          {entries.map((f) => (
                            f.authorEmail === myEmail
                              ? <MyEntryCard key={f.id} f={f} priorities={priorities} onEdit={onEdit} onDelete={onDelete} />
                              : <OtherEntryCard key={f.id} f={f} />
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {modal ? (
          <GeneralFeedbackModal
            mode={modal.mode}
            initialHtml={modal.mode === "edit" ? modal.entry.text : ""}
            initialPriority={modal.mode === "edit" ? modal.entry.priority : "Mittel"}
            onClose={() => setModal(null)}
            onSubmit={(html, priority) => {
              if (modal.mode === "edit") onEdit(modal.entry.id, { text: html, priority });
              else onReportGeneral(html, priority);
              setModal(null);
            }}
          />
        ) : null}
      </div>
    );
  }

  window.SC_FeedbackScreen = FeedbackScreen;
})();
