// SOLCOM Website-Abnahme · Bereichs-Detailansicht (mit Inline-Testfällen + Feedback)
// Hinweis: window.SOLCOM / window.SC_StatusBadge erst innerhalb der Render-
// funktionen referenzieren (Shell setzt window.SOLCOM nach dem Daten-Fetch).
(function () {
  const DS = window.AdessoPlaybooksDesignSystem_29634e;
  const { Breadcrumb, Button, MetaChip } = DS;

  // ---- große, klickbare Checkbox ----
  function StepCheck({ checked, onToggle, children }) {
    return (
      <label
        onClick={onToggle}
        style={{
          display: "flex", gap: 14, alignItems: "flex-start", cursor: "pointer",
          padding: "13px 16px", borderRadius: "var(--radius-lg)",
          background: checked ? "var(--blue-50)" : "transparent",
          transition: "background .12s ease",
        }}
        onMouseEnter={(e) => { if (!checked) e.currentTarget.style.background = "var(--ink-50)"; }}
        onMouseLeave={(e) => { if (!checked) e.currentTarget.style.background = "transparent"; }}
      >
        <span style={{
          width: 24, height: 24, flexShrink: 0, marginTop: 1, borderRadius: "var(--radius-md)",
          display: "flex", alignItems: "center", justifyContent: "center",
          background: checked ? "var(--blue-500)" : "#fff",
          border: checked ? "1.5px solid var(--blue-500)" : "1.5px solid var(--ink-300)",
          transition: "all .12s ease",
        }}>
          {checked ? <i className="ph-bold ph-check" style={{ fontSize: 14, color: "#fff" }} /> : null}
        </span>
        <span style={{ fontSize: 14.5, lineHeight: 1.5, color: checked ? "var(--ink-600)" : "var(--ink-900)", flex: 1, paddingTop: 1 }}>{children}</span>
      </label>
    );
  }

  // ---- Status-Umschalter: Funktioniert / Funktioniert nicht ----
  function StatusToggle({ works, onSet }) {
    const opt = (val, label, icon, activeBg, activeBorder) => {
      const active = works === val;
      return (
        <button
          onClick={() => onSet(active ? null : val)}
          style={{
            flex: 1, cursor: "pointer", font: "inherit",
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
            padding: "13px 16px", fontSize: 14.5, fontWeight: 500,
            borderRadius: "var(--radius-lg)", border: "1.5px solid",
            background: active ? activeBg : "#fff",
            borderColor: active ? activeBorder : "var(--ink-200)",
            color: active ? "#fff" : "var(--ink-700)",
            transition: "all .12s ease",
          }}
        >
          <i className={icon} style={{ fontSize: 17 }} />
          {label}
        </button>
      );
    };
    return (
      <div style={{ display: "flex", gap: 10 }}>
        {opt(true, "Funktioniert", "ph-bold ph-check-circle", "var(--success)", "var(--success)")}
        {opt(false, "Funktioniert nicht", "ph-bold ph-x-circle", "var(--danger)", "var(--danger)")}
      </div>
    );
  }

  // ---- Feedback-Panel (Pflichtfeld bei „Funktioniert nicht") ----
  function FeedbackPanel({ c, onChange }) {
    const required = c.works === false;
    const empty = !c.feedback || !c.feedback.trim();
    const invalid = required && empty;

    return (
      <div style={{ marginTop: 18 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: invalid ? "var(--danger)" : "var(--ink-500)" }}>
            Feedback {required ? <span style={{ color: "var(--danger)" }}>· Pflichtfeld</span> : <span style={{ color: "var(--ink-400)", textTransform: "none", letterSpacing: 0 }}>(optional)</span>}
          </span>
          {required && empty ? (
            <span style={{ fontSize: 12, color: "var(--danger)", display: "inline-flex", alignItems: "center", gap: 5 }}>
              <i className="ph-bold ph-warning-circle" style={{ fontSize: 13 }} /> Bitte Fehler beschreiben
            </span>
          ) : null}
        </div>
        <textarea
          value={c.feedback}
          onChange={(e) => onChange({ feedback: e.target.value })}
          placeholder={required ? "Was funktioniert nicht? Beschreiben Sie den Fehler so, dass er nachvollziehbar ist…" : "Optionale Anmerkungen, Hinweise oder Lob…"}
          rows={4}
          style={{
            width: "100%", boxSizing: "border-box", resize: "vertical",
            fontFamily: "var(--font-sans)", fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-900)",
            padding: "13px 15px", borderRadius: "var(--radius-lg)", background: invalid ? "color-mix(in oklch, var(--danger) 5%, #fff)" : "var(--ink-50)",
            border: "1.5px solid " + (invalid ? "var(--danger)" : "var(--ink-200)"), outline: "none",
          }}
          onFocus={(e) => { if (!invalid) e.target.style.borderColor = "var(--blue-500)"; }}
          onBlur={(e) => { if (!invalid) e.target.style.borderColor = "var(--ink-200)"; }}
        />
        {/* Screenshot-Anhang */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 12, flexWrap: "wrap" }}>
          {(c.attachments || []).map((name, i) => (
            <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 31, boxSizing: "border-box", padding: "0 12px", background: "#fff", border: "1px solid var(--ink-200)", borderRadius: "var(--radius-lg)", fontSize: 13, lineHeight: 1 }}>
              <i className="ph ph-image" style={{ fontSize: 15, color: "var(--blue-500)" }} />
              {name}
              <button onClick={() => onChange({ attachments: c.attachments.filter((_, j) => j !== i) })} style={{ cursor: "pointer", border: "none", background: "none", color: "var(--ink-400)", padding: 0, display: "flex" }}>
                <i className="ph-bold ph-x" style={{ fontSize: 12 }} />
              </button>
            </span>
          ))}
          <Button variant="ghost" size="sm" icon="ph ph-paperclip"
            onClick={() => onChange({ attachments: [...(c.attachments || []), `screenshot-${(c.attachments || []).length + 1}.png`] })}>
            Screenshot anhängen
          </Button>
        </div>
      </div>
    );
  }

  // ---- ein Testfall (klappt inline auf, kein Modal) ----
  function TestCaseRow({ c, expanded, onExpand, onChange, isMobile }) {
    const S = window.SOLCOM;
    const StatusBadge = window.SC_StatusBadge;
    const status = S.caseStatus(c);
    const checkedN = (c.checkedSteps || []).filter(Boolean).length;

    const toggleStep = (i) => {
      const next = (c.checkedSteps || []).slice();
      next[i] = !next[i];
      onChange({ checkedSteps: next });
    };

    return (
      <div style={{
        background: "#fff", border: "1px solid var(--ink-200)", borderRadius: "var(--radius-xl)",
        boxShadow: expanded ? "var(--shadow-2)" : "var(--shadow-1)", overflow: "hidden",
      }}>
        {/* header row — große Klickfläche */}
        <div
          role="button" tabIndex={0}
          onClick={onExpand}
          onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onExpand(); } }}
          style={{ width: "100%", textAlign: "left", cursor: "pointer", padding: isMobile ? "16px 18px" : "20px 24px", display: "flex", alignItems: "center", gap: isMobile ? 12 : 18 }}
        >
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 7, flexWrap: "wrap" }}>
              <h3 style={{ fontSize: 17, fontWeight: 600, lineHeight: 1.3, margin: 0, color: "var(--ink-1000)" }}>{c.title}</h3>
              <StatusBadge status={status} />
            </div>
            <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5, color: "var(--ink-600)", fontStyle: "italic" }}>{c.userStory}</p>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 16, flexShrink: 0 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-500)", whiteSpace: "nowrap" }}>{checkedN}/{c.steps.length} Schritte</span>
            <i className={"ph-bold " + (expanded ? "ph-caret-up" : "ph-caret-down")} style={{ fontSize: 16, color: "var(--ink-400)" }} />
          </div>
        </div>

        {/* expanded body */}
        {expanded ? (
          <div style={{ padding: isMobile ? "4px 18px 20px" : "4px 24px 24px" }}>
            <div style={{ borderTop: "1px solid var(--ink-100)", paddingTop: 18 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-500)", marginBottom: 6 }}>Prüfschritte</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 22 }}>
                {c.steps.map((st, i) => (
                  <StepCheck key={i} checked={!!(c.checkedSteps || [])[i]} onToggle={() => toggleStep(i)}>{st}</StepCheck>
                ))}
              </div>

              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-500)", marginBottom: 10 }}>Bewertung des Testfalls</div>
              <StatusToggle works={c.works} onSet={(v) => onChange({ works: v })} />

              {c.works !== null ? <FeedbackPanel c={c} onChange={onChange} /> : (
                <p style={{ margin: "14px 0 0", fontSize: 13, color: "var(--ink-500)", display: "flex", alignItems: "center", gap: 7 }}>
                  <i className="ph ph-info" style={{ fontSize: 15 }} /> Wählen Sie „Funktioniert" oder „Funktioniert nicht", um den Testfall abzuschließen.
                </p>
              )}
            </div>
          </div>
        ) : null}
      </div>
    );
  }

  function AreaDetailScreen({ area, onBack, onUpdateCase, onOpenTickets }) {
    const S = window.SOLCOM;
    const [expanded, setExpanded] = React.useState(() => {
      const firstOpen = area.cases.find((c) => c.works === null);
      return firstOpen ? firstOpen.id : (area.cases[0] ? area.cases[0].id : null);
    });
    const p = S.areaProgress(area);
    const { isMobile } = window.SC_useViewport();

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

          {/* area header */}
          <div style={{ padding: "22px 0 26px", borderBottom: "1px solid var(--ink-200)", display: "flex", flexDirection: isMobile ? "column" : "row", alignItems: isMobile ? "stretch" : "flex-start", justifyContent: "space-between", gap: isMobile ? 20 : 24 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <span style={{ width: 56, height: 56, borderRadius: "var(--radius-lg)", background: "var(--blue-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <i className={area.icon} style={{ fontSize: 30, color: "var(--blue-500)" }} />
              </span>
              <div>
                <h1 style={{ fontFamily: "var(--font-cond)", fontSize: isMobile ? 30 : 40, fontWeight: 500, letterSpacing: "-.015em", lineHeight: 1.04, margin: 0, color: "var(--ink-1000)" }}>{area.name}</h1>
                <div style={{ display: "flex", gap: 18, marginTop: 8, flexWrap: "wrap" }}>
                  <MetaChip icon="ph ph-list-checks">{p.total} Testfälle</MetaChip>
                  <MetaChip icon="ph-bold ph-check">{p.passed} abgenommen</MetaChip>
                  <MetaChip icon="ph-bold ph-warning">{p.failed} Fehler</MetaChip>
                </div>
              </div>
            </div>
            <div style={{ textAlign: isMobile ? "left" : "right", minWidth: isMobile ? "auto" : 150 }}>
              <div style={{ display: "flex", justifyContent: "flex-end", alignItems: "baseline", gap: 10, marginBottom: 8 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-500)" }}>{p.reviewed}/{p.total} geprüft</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 15, fontWeight: 600, color: "var(--blue-500)" }}>{p.pct}%</span>
              </div>
              <div style={{ height: 6, background: "var(--ink-200)", borderRadius: "var(--radius-full)", overflow: "hidden" }}>
                <span style={{ display: "block", height: "100%", width: p.pct + "%", background: "var(--blue-500)", transition: "width .3s ease" }} />
              </div>
            </div>
          </div>

          {/* test cases */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14, padding: "28px 0 40px" }}>
            {area.cases.map((c) => (
              <TestCaseRow
                key={c.id}
                c={c}
                expanded={expanded === c.id}
                onExpand={() => setExpanded(expanded === c.id ? null : c.id)}
                onChange={(patch) => onUpdateCase(area.id, c.id, patch)}
                isMobile={isMobile}
              />
            ))}
          </div>

          {p.failed > 0 ? (
            <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "18px 22px", margin: "0 0 56px", background: "color-mix(in oklch, var(--danger) 5%, #fff)", border: "1px solid color-mix(in oklch, var(--danger) 25%, #fff)", borderRadius: "var(--radius-xl)", flexWrap: "wrap" }}>
              <i className="ph-duotone ph-warning" style={{ fontSize: 24, color: "var(--danger)", flexShrink: 0 }} />
              <span style={{ fontSize: 14.5, color: "var(--ink-800)", flex: 1 }}>
                <b>{p.failed} Testfälle</b> in diesem Bereich sind als fehlerhaft markiert. Leiten Sie daraus Jira-Tickets ab.
              </span>
              <Button variant="primary" size="sm" iconRight="ph-bold ph-arrow-right" onClick={onOpenTickets}>Zur Ticket-Ableitung</Button>
            </div>
          ) : null}
        </div>
      </div>
    );
  }

  window.SC_AreaDetailScreen = AreaDetailScreen;
})();
