// qa.jsx — QA workflow: required toggle, tester assignment, linked QA task,
// Pass/Fail actions, reopen tracking. Plus a reusable <QaBadge/> for rows.

// ── Helpers: workflow ──────────────────────────────────────────
//
// onMarkDone(task):
//   If qaRequired → move to "qa" status, create QA sub-task, notify tester.
//   Else → status "done".
//
// onQaPass(task, qaTask):
//   Original task → "done". QA task archived. No new counter.
//
// onQaFail(task, qaTask, notes):
//   Original task → "reopened". reopenCount++. qaNotes = notes.
//   QA task stays open (or cycles); a new QA run starts when dev
//   moves the task back to "qa".
//
// These helpers return the next state so callers can apply via setState.

function qaRunDoneTransition(task, project) {
  if (!task.qaRequired) {
    return { task: { ...task, status: "done", qaStatus: "passed" }, qaTask: null };
  }
  const tester = project?.testerId || "le";
  const qaTask = {
    id: `qa-${task.id}-${Date.now()}`,
    forTaskId: task.id,
    forTaskName: task.name,
    projectId: project?.id || "checkout",
    projectColor: project?.color || "var(--brand)",
    assignee: tester,
    reportedBy: task.owners?.[0] || "ay",
    status: "todo",
    prio: task.prio,
    due: task.due,
    createdAt: "just now",
    checklist: [
      { id: "c1", text: "Smoke test: feature works as described",  done: false },
      { id: "c2", text: "Edge cases covered",                       done: false },
      { id: "c3", text: "No regressions in related flows",         done: false },
      { id: "c4", text: "Accessibility & keyboard nav pass",       done: false },
    ],
  };
  return {
    task: { ...task, status: "qa", qaStatus: "pending" },
    qaTask,
  };
}

function qaRunPass(task) {
  return { ...task, status: "done", qaStatus: "passed" };
}

function qaRunFail(task, notes) {
  return {
    ...task,
    status: "reopened",
    qaStatus: "failed",
    reopenCount: (task.reopenCount || 0) + 1,
    qaNotes: notes || task.qaNotes || "",
  };
}

// ── Visual atoms ───────────────────────────────────────────────
function QaReopenBadge({ count, size = "md" }) {
  if (!count || count < 1) return null;
  return (
    <span className={`qa-reopen-badge ${size === "sm" ? "sm" : ""}`} title={`Reopened ${count}×`}>
      <Icons.ArrowUp style={{ transform: "rotate(-45deg)" }} size={10}/>
      {count}×
    </span>
  );
}

function QaChip({ status }) {
  if (!status) return null;
  const meta = QA_STATUS[status] || QA_STATUS.pending;
  const Ic = status === "passed" ? Icons.Check
           : status === "failed" ? Icons.Alert
           : Icons.Clock;
  return (
    <span className={`qa-chip tone-${meta.tone}`}>
      <Ic/>
      {meta.label}
    </span>
  );
}

function QaRequiredMark({ required }) {
  if (!required) return null;
  return (
    <span className="qa-required-mark" title="QA required">
      <Icons.Check size={11}/>
      QA
    </span>
  );
}

// ── QA section inside TaskDrawer ───────────────────────────────
function QaDrawerSection({ task, project, onUpdate, onOpenQaTask }) {
  const [failOpen, setFailOpen] = React.useState(false);
  const [failNote, setFailNote] = React.useState("");
  const linkedQa = (window.QA_TASKS || []).find(q => q.forTaskId === task.id);
  const tester = (PROJECTS.find(p => p.id === (project?.id || task.projectId || "checkout"))?.testerId) || project?.testerId;
  const testerPerson = PEOPLE.find(p => p.id === tester);

  function toggleQaRequired(on) {
    onUpdate && onUpdate({ ...task, qaRequired: on });
  }
  function markDone() {
    const proj = PROJECTS.find(p => p.id === (project?.id || task.projectId)) || project;
    const { task: nextTask, qaTask } = qaRunDoneTransition(task, proj);
    if (qaTask && typeof window.QA_TASKS !== "undefined") {
      window.QA_TASKS.push(qaTask);
    }
    onUpdate && onUpdate(nextTask);
  }
  function doPass() { onUpdate && onUpdate(qaRunPass(task)); }
  function doFail() {
    onUpdate && onUpdate(qaRunFail(task, failNote));
    setFailOpen(false);
    setFailNote("");
  }

  const isInQa   = task.status === "qa";
  const isPassed = task.qaStatus === "passed";
  const isFailed = task.qaStatus === "failed";
  const isReopened = task.status === "reopened";

  return (
    <section className="qa-section">
      <div className="qa-section-head">
        <span className="qa-section-title">
          <Icons.Check/> Quality Assurance
        </span>
        {task.qaRequired && <QaChip status={task.qaStatus || "pending"}/>}
      </div>

      <label className="qa-toggle">
        <input type="checkbox" checked={!!task.qaRequired}
               onChange={(e) => toggleQaRequired(e.target.checked)}/>
        <span><strong>QA required</strong> before closing</span>
        {task.qaRequired && testerPerson && (
          <small>Tester · {testerPerson.name.split(" ")[0]}</small>
        )}
      </label>

      {task.qaRequired && (
        <div className="qa-tester">
          <span className="qa-tester-label">Tester</span>
          <div>
            {testerPerson ? (
              <>
                <div className="qa-tester-person">
                  <Avatar person={testerPerson} size="sm"/>
                  {testerPerson.name}
                </div>
                <div className="qa-tester-meta">{testerPerson.title} · assigned from project settings</div>
              </>
            ) : (
              <div className="qa-tester-meta">No tester set for this project</div>
            )}
          </div>
        </div>
      )}

      {/* Reopen history */}
      {task.reopenCount > 0 && (
        <div className="qa-history">
          <Icons.Alert size={14}/>
          <span>
            Reopened <strong>{task.reopenCount}×</strong> after failing QA
            {task.qaNotes && <> · last note: "{task.qaNotes}"</>}
          </span>
        </div>
      )}

      {/* Linked QA task */}
      {task.qaRequired && isInQa && linkedQa && (
        <div className="qa-link-card" onClick={() => onOpenQaTask && onOpenQaTask(linkedQa)}>
          <div className="qa-link-card-ico"><Icons.Check size={15}/></div>
          <div>
            <div className="qa-link-card-title">
              <Icons.Link/> QA-{linkedQa.id.slice(-6).toUpperCase()}
              <span style={{ fontWeight: 500, color: "var(--ink-muted)", marginLeft: 2 }}>
                · {linkedQa.checklist.filter(c => c.done).length}/{linkedQa.checklist.length} checks
              </span>
            </div>
            <div className="qa-link-card-sub">
              Assigned to {PEOPLE.find(p => p.id === linkedQa.assignee)?.name.split(" ")[0]} · created {linkedQa.createdAt}
            </div>
          </div>
          <span className="qa-link-card-cta">Open QA →</span>
        </div>
      )}

      {/* Action row — depends on current state */}
      {!isInQa && task.status !== "done" && (
        <div className="qa-actions">
          <button className="qa-btn pass" onClick={markDone}>
            <Icons.Check size={14}/> {task.qaRequired ? "Done — send to QA" : "Mark done"}
          </button>
        </div>
      )}
      {isInQa && (
        <div className="qa-actions">
          <button className="qa-btn pass" onClick={doPass}>
            <Icons.Check size={14}/> Pass QA
          </button>
          <button className="qa-btn fail" onClick={() => setFailOpen(true)}>
            <Icons.Alert size={14}/> Fail — reopen
          </button>
        </div>
      )}
      {isPassed && !isInQa && task.status === "done" && (
        <div style={{ fontSize: 12, color: "#027447", fontWeight: 600, marginTop: 6, display: "flex", alignItems: "center", gap: 6 }}>
          <Icons.Check size={12}/> Passed QA — task closed
        </div>
      )}

      {/* Fail note modal */}
      {failOpen && (
        <div className="modal-backdrop" onClick={() => setFailOpen(false)}>
          <div className="modal" style={{ width: 460 }} onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <div>
                <h3>Fail QA & reopen task</h3>
                <p style={{ fontSize: 12, color: "var(--ink-muted)", margin: "4px 0 0" }}>
                  Leave a note for {PEOPLE.find(p => p.id === task.owners?.[0])?.name.split(" ")[0] || "the developer"} on what failed.
                </p>
              </div>
              <button className="icon-btn" onClick={() => setFailOpen(false)}><Icons.Plus style={{ transform: "rotate(45deg)" }}/></button>
            </div>
            <div className="modal-body">
              <div className="qa-fail-form">
                <label>What failed?</label>
                <textarea autoFocus
                  value={failNote}
                  onChange={(e) => setFailNote(e.target.value)}
                  placeholder="e.g. 3DS redirect loses session on Safari 17.4 — reproducible on staging build #182"/>
                <div style={{ fontSize: 11.5, color: "var(--ink-muted)", fontWeight: 500 }}>
                  This task will be marked <strong style={{ color: "#c2253a" }}>Reopened</strong> and reopen count will increment to{" "}
                  <strong>{(task.reopenCount || 0) + 1}</strong>.
                </div>
              </div>
            </div>
            <div className="modal-foot">
              <button className="btn" onClick={() => setFailOpen(false)}>Cancel</button>
              <button className="btn primary" style={{ background: "#e2445c", borderColor: "#e2445c" }}
                      onClick={doFail} disabled={!failNote.trim()}>
                Reopen task
              </button>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { QaDrawerSection, QaReopenBadge, QaChip, QaRequiredMark, qaRunDoneTransition, qaRunPass, qaRunFail });
