// Detail panel – tabs: Overview / Diff tour / Chat. Plus dismiss dialog.

const { useState: useStateD } = React;

const DiffTour = ({ tour }) => {
  const [step, setStep] = useStateD(0);
  if (!tour || tour.length === 0) {
    return (
      <div style={{ padding: 14, textAlign: "center", color: "#8a8d99", fontSize: 12, background: "#ffffff", border: "1px dashed #e8e3d5", borderRadius: 6 }}>
        Diff tour not yet generated for this solution.
      </div>
    );
  }
  const t = tour[step];
  const adds = t.hunk.filter(h => h.t === "+").length;
  const dels = t.hunk.filter(h => h.t === "-").length;
  return (
    <div>
      <div className="tour-strip">
        <button className="nav-btn" disabled={step === 0} onClick={() => setStep(s => Math.max(0, s - 1))}>‹</button>
        <span className="step">step {step + 1} / {tour.length}</span>
        {tour.map((_, i) => (
          <span key={i} className={"dot" + (i === step ? " active" : "")} onClick={() => setStep(i)} style={{ cursor: "pointer" }} />
        ))}
        <button className="nav-btn" disabled={step === tour.length - 1} onClick={() => setStep(s => Math.min(tour.length - 1, s + 1))}>›</button>
      </div>
      <div className="tour-card">
        <div className="tour-narration">
          <div className="hh-ico">🦔</div>
          <div>{t.summary}</div>
        </div>
        <div className="tour-file">
          <span>📄</span>
          <span className="fileln">{t.file}</span>
          <span style={{ color: "#8a8d99" }}>:{t.start}</span>
          <span className="stats"><span className="add">+{adds}</span> <span className="del">−{dels}</span></span>
        </div>
        <pre className="diff-pre">
          {t.hunk.map((h, i) => (
            <div key={i} className={"diff-line " + (h.t === "+" ? "add" : h.t === "-" ? "del" : "context")}>
              <span className="diff-marker">{h.t === "+" ? "+" : h.t === "-" ? "−" : " "}</span>
              <span className="diff-lineno">{t.start + i}</span>
              <span>{h.line}</span>
            </div>
          ))}
        </pre>
      </div>
    </div>
  );
};

const ReviewerCard = ({ handle, primary, reasoning }) => {
  const u = TEAMMATES[handle];
  return (
    <div className="rev-card">
      <Avatar user={handle} size={28} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="rev-name">{u.name} <span style={{ color: "#8a8d99", fontWeight: 400, fontSize: 11.5 }}>@{u.handle}</span></div>
        {primary && reasoning && <div className="rev-reason">{reasoning}</div>}
      </div>
      {primary && <span className="rev-badge">primary</span>}
    </div>
  );
};

const TrustStrip = ({ s }) => (
  <div className="trust-strip">
    <span className="item"><span className="ok">✓ CI passed</span></span>
    <span className="div" />
    <span className="item">{s.checks?.tests || "–"} tests</span>
    <span className="div" />
    <span className="item">lint {s.checks?.lint || "clean"}</span>
    <span className="div" />
    <span className="item">
      <a href="#" title="Open the PostHog Code session that produced this PR">Open agent session ↗</a>
    </span>
    <span className="div" />
    <span className="item">
      <a href="#">PR description with full provenance ↗</a>
    </span>
  </div>
);

const ChatMessage = ({ m }) => {
  const isUser = m.agent === "user";
  return (
    <div className={"chat-msg " + (isUser ? "user" : "agent")}>
      <div className={"chat-avatar " + (isUser ? "user" : "agent")}>
        {isUser ? "Y" : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M12 8V4H8"></path>
            <rect width="16" height="12" x="4" y="8" rx="2"></rect>
            <path d="M2 14h2"></path>
            <path d="M20 14h2"></path>
            <path d="M15 13v2"></path>
            <path d="M9 13v2"></path>
          </svg>
        )}
      </div>
      <div className="chat-body">
        <div className="chat-meta">
          <span className="chat-name">{isUser ? "You" : "Inbox agent"}</span>
          <span>·</span>
          <span>{m.at}</span>
        </div>
        <div className="chat-text">{m.text}</div>
      </div>
    </div>
  );
};

const ChatThread = ({ chat }) => {
  const [draft, setDraft] = useStateD("");
  const [items, setItems] = useStateD(chat || []);
  const send = () => {
    if (!draft.trim()) return;
    setItems(it => [...it, { agent: "user", at: "just now", text: draft }]);
    setDraft("");
    setTimeout(() => {
      setItems(it => [...it, {
        agent: "agent",
        at: "just now",
        text: "Got it. Let me re-check the signals and adjust if needed – I'll be back shortly.",
      }]);
    }, 800);
  };
  return (
    <div>
      <div className="chat-list">
        {items.map((m, i) => <ChatMessage key={i} m={m} />)}
      </div>
      <div className="chat-composer">
        <textarea
          placeholder="Reply to the agent – ask for more evidence, push back on the call, or request a revision…"
          value={draft}
          onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(); }}}
        />
        <div className="chat-toolbar">
          <span style={{ flex: 1 }} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "#8a8d99" }}>⌘↵ to send</span>
          <button className="t-btn" style={{ background: "#b88800", color: "#1a1200", borderColor: "transparent" }} onClick={send} disabled={!draft.trim()}>Send</button>
        </div>
      </div>
    </div>
  );
};

const DismissDialog = ({ item, onClose, onConfirm }) => {
  const [reason, setReason] = useStateD(null);
  const [note, setNote] = useStateD("");
  const reasons = [
    "Already fixed elsewhere",
    "Not actually a problem – agent misread the signal",
    "Won't fix (intentional behavior)",
    "Wrong reviewer for me",
    "Lower priority than the agent thinks",
    "Other",
  ];
  return (
    <div className="dismiss-overlay" onClick={onClose}>
      <div className="dismiss-card" onClick={e => e.stopPropagation()}>
        <h3>Dismiss "{item.title.slice(0, 60)}{item.title.length > 60 ? "…" : ""}"</h3>
        <div className="sub">Why isn't this relevant? Your reason trains the research agent so we send fewer of these.</div>
        <div className="dismiss-reasons">
          {reasons.map(r => (
            <div key={r} className={"dismiss-reason" + (reason === r ? " selected" : "")} onClick={() => setReason(r)}>
              <span className="marker" />{r}
            </div>
          ))}
        </div>
        <textarea placeholder="Optional: add detail (the agent reads this)" value={note} onChange={e => setNote(e.target.value)} />
        <div className="dismiss-actions">
          <button className="t-btn ghost" onClick={onClose}>Cancel</button>
          <button className="t-btn" onClick={() => onConfirm(reason, note)} disabled={!reason} style={reason ? { background: "#b88800", color: "#1a1200", borderColor: "transparent" } : {}}>Dismiss & teach the agent</button>
        </div>
      </div>
    </div>
  );
};

const SolutionDetail = ({ s, scene, onClose, onMerge, merged, onDismiss }) => {
  const [tab, setTab] = useStateD("overview");

  if (!s) {
    return (
      <div className={"detail" + (scene ? " scene" : "")}>
        <div className="detail-empty">
          <img src="assets/zen-hedgehog.png" alt="" />
          <h3>Pick something to dig into</h3>
          <p>The agent surfaces solutions where you're the suggested reviewer. Open one to see evidence, the tour, and reviewers.</p>
        </div>
      </div>
    );
  }

  const isReady = s.kind === "ready";
  const isReview = s.kind === "review";

  return (
    <div className={"detail" + (scene ? " scene" : "")}>
      <div className="dt-head">
        <div className="dt-eyebrow">
          <PriorityWithWhy p={s.priority} reasoning={
            <>
              <p><strong>{s.priority}</strong> reflects how much pain this is causing, weighted by the volume + diversity of signals.</p>
              <ul>
                {(s.signals || []).slice(0, 3).map((sig, i) => (
                  <li key={i}>{sig.title} – <em>{sig.source}</em>{sig.count ? `, ${typeof sig.count === "number" ? sig.count.toLocaleString() : sig.count}` : ""}</li>
                ))}
              </ul>
              {s.impact && <p><strong>Impact:</strong> {s.impact}</p>}
            </>
          } />
          <span className="dt-id">{s.repo}#{s.pr}</span>
          <span style={{ color: "#d4ccb8" }}>·</span>
          <ActionabilityWithWhy
            label={isReady ? "Ready to merge" : "Review before merging"}
            color={isReady ? "#2f9e44" : "#b88800"}
            reasoning={isReady ? (
              <>
                <p>The agent rated this <strong>actionable</strong> – high confidence, no open questions.</p>
                <ul>
                  <li>Confidence: <strong>{Math.round((s.confidence || 0) * 100)}%</strong></li>
                  <li>CI passed; {s.checks?.tests || "–"} tests; lint {s.checks?.lint || "clean"}.</li>
                  <li>Scope: {s.files} file{s.files === 1 ? "" : "s"}, +{s.additions} −{s.deletions}.</li>
                </ul>
                <p>You can merge directly – or open the diff tour first.</p>
              </>
            ) : (
              <>
                <p>The agent rated this <strong>needs your input</strong>. It went ahead and drafted a PR, but flagged it for review because:</p>
                <ul>
                  <li>Confidence: <strong>{Math.round((s.confidence || 0) * 100)}%</strong> – below the auto-ship threshold.</li>
                  {s.questions && s.questions.length > 0 && <li>{s.questions.length} open question{s.questions.length === 1 ? "" : "s"} you need to answer.</li>}
                  <li>Scope: {s.files} file{s.files === 1 ? "" : "s"}, +{s.additions} −{s.deletions}.</li>
                </ul>
              </>
            )}
          />
          {!scene && (
            <>
              <span style={{ flex: 1 }} />
              <button className="t-btn ghost" onClick={onClose} title="Close">✕</button>
            </>
          )}
        </div>
        <h2 className="dt-title">{s.title}</h2>
        <div className="dt-meta">
          <span className="branch">⎇ {s.branch}</span>
          <span className="sep">·</span>
          <span>{s.files} files</span>
          <span className="sep">·</span>
          <span><span style={{ color: "#2f9e44" }}>+{s.additions}</span> <span style={{ color: "#d8503a" }}>−{s.deletions}</span></span>
          <span className="sep">·</span>
          <span>{s.age}</span>
          {s.origin && <OriginChip origin={s.origin} />}
        </div>
        <div className="dt-actions">
          <MergeButton merged={merged} onMerge={(mode) => onMerge && onMerge(mode)} size="lg" />
          <button className="t-btn">Open in GitHub ↗</button>
          <span style={{ flex: 1 }} />
          <button className="t-btn ghost" onClick={() => onDismiss(s)}>Dismiss</button>
        </div>
      </div>

      <div className="dt-tabs">
        <button className={"dt-tab" + (tab === "overview" ? " active" : "")} onClick={() => setTab("overview")}>
          Overview
        </button>
        <button className={"dt-tab" + (tab === "diff" ? " active" : "")} onClick={() => setTab("diff")}>
          Diff tour <span className="badge">{s.tour?.length || 0}</span>
        </button>
        <button className={"dt-tab" + (tab === "chat" ? " active" : "")} onClick={() => setTab("chat")}>
          Chat <span className="badge">{s.chat?.length || 0}</span>
          {isReview && <span className="nudge" title="The agent has open questions" />}
        </button>
      </div>

      <div className="dt-body">
        {tab === "overview" && (
          <>
            <div className="dt-section">
              <div className="dt-section-head"><span className="num">1</span> Summary</div>
              <div className="dt-section-body">
                <p>{s.summary}</p>
                {s.impact && <p style={{ color: "#6b6e7a" }}><strong style={{ color: "#3a3d4a" }}>Impact:</strong> {s.impact}</p>}
                {s.problem && <p style={{ color: "#6b6e7a" }}><strong style={{ color: "#3a3d4a" }}>Problem:</strong> {s.problem}</p>}
                {s.solution && <p style={{ color: "#6b6e7a" }}><strong style={{ color: "#3a3d4a" }}>Solution:</strong> {s.solution}</p>}
              </div>
            </div>

            <div className="dt-section">
              <div className="dt-section-head"><span className="num">2</span> Trust &amp; provenance</div>
              <div className="dt-section-body">
                <TrustStrip s={s} />
              </div>
            </div>

            <div className="dt-section">
              <div className="dt-section-head">
                <span className="num">3</span> Evidence
                <span style={{ flex: 1 }} />
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "#8a8d99", textTransform: "none", letterSpacing: 0 }}>
                  {s.signals.length} {s.signals.length === 1 ? "signal" : "signals"}
                </span>
              </div>
              <div className="dt-section-body">
                <div className="evidence-list">{s.signals.map((ev, i) => <Evidence key={i} ev={ev} />)}</div>
              </div>
            </div>

            {isReview && s.questions && (
              <div className="dt-section">
                <div className="dt-section-head"><span className="num">4</span> Open questions for you</div>
                <div className="dt-section-body">
                  <ul style={{ margin: 0, paddingLeft: 18, lineHeight: 1.7 }}>
                    {s.questions.map((q, i) => <li key={i} style={{ color: "#3a3d4a" }}>{q}</li>)}
                  </ul>
                  <div style={{ marginTop: 10 }}>
                    <button className="t-btn" onClick={() => setTab("chat")} style={{ background: "#fff4d6", color: "#b88800", borderColor: "rgba(248,190,42,0.3)" }}>
                      Answer in chat →
                    </button>
                  </div>
                </div>
              </div>
            )}

            <div className="dt-section">
              <div className="dt-section-head"><span className="num">{isReview ? "5" : "4"}</span> Suggested reviewers</div>
              <div className="dt-section-body">
                <div className="rev-row">
                  {s.reviewers.map(h => (
                    <ReviewerCard key={h} handle={h} primary={h === s.primaryReviewer} reasoning={h === s.primaryReviewer ? s.reasoning : null} />
                  ))}
                </div>
              </div>
            </div>
          </>
        )}

        {tab === "diff" && (
          <div className="dt-section">
            <div className="dt-section-head">
              <span className="num">▦</span> Diff tour
              <span style={{ flex: 1 }} />
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "#8a8d99", textTransform: "none", letterSpacing: 0 }}>
                narrated by the agent
              </span>
            </div>
            <div className="dt-section-body">
              <DiffTour tour={s.tour} />
            </div>
          </div>
        )}

        {tab === "chat" && (
          <div className="dt-section">
            <div className="dt-section-head">
              <span className="num">💬</span> Continue the thread
              <span style={{ flex: 1 }} />
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "#8a8d99", textTransform: "none", letterSpacing: 0 }}>
                with the inbox agent
              </span>
            </div>
            <div className="dt-section-body">
              <ChatThread chat={s.chat} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

const REPORT_STATUS_LABEL = {
  "researching": "Researching",
  "needs-input": "Needs your input",
  "ready": "Ready for your call",
  "failed": "Failed",
  "non-actionable": "Non-actionable",
};

const ReportDetail = ({ r, scene, onClose, onDismiss }) => {
  const [tab, setTab] = useStateD("overview");
  return (
    <div className={"detail" + (scene ? " scene" : "")}>
      <div className="dt-head">
        <div className="dt-eyebrow">
          <PriorityWithWhy p={r.priority} reasoning={
            <>
              <p><strong>{r.priority}</strong> reflects how much pain this is causing, weighted by the volume + diversity of signals.</p>
              <ul>
                {(r.signals || []).slice(0, 3).map((sig, i) => (
                  <li key={i}>{sig.title} – <em>{sig.source}</em>{sig.count ? `, ${typeof sig.count === "number" ? sig.count.toLocaleString() : sig.count}` : ""}</li>
                ))}
              </ul>
            </>
          } />
          <span style={{ color: "#d4ccb8" }}>·</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span className={"report-status " + r.status}>{REPORT_STATUS_LABEL[r.status] || r.status}</span>
            <WhyPopover title="Why this actionability?">
              {r.status === "ready" && (
                <>
                  <p>The agent calls this <strong>actionable</strong>. It has a recommendation and is ready to draft a PR if you sign off.</p>
                  <p>{r.summary}</p>
                </>
              )}
              {r.status === "researching" && (
                <>
                  <p>The agent is <strong>still investigating</strong>. It hasn't called actionability yet.</p>
                  {typeof r.progress === "number" && <p>Progress: <strong>{Math.round(r.progress * 100)}%</strong>.</p>}
                </>
              )}
              {r.status === "needs-input" && (
                <>
                  <p>The agent rated this <strong>needs your input</strong>. It got stuck on:</p>
                  <ul>{(r.blockers || []).map((b, i) => <li key={i}>{b}</li>)}</ul>
                </>
              )}
              {r.status === "failed" && (
                <>
                  <p>The agent <strong>tried and failed</strong>. It needs more from you to make progress:</p>
                  <ul>{(r.blockers || []).map((b, i) => <li key={i}>{b}</li>)}</ul>
                </>
              )}
              {r.status === "non-actionable" && (
                <>
                  <p>The agent rated this <strong>not actionable</strong> – investigated, but no fix possible without changing a contract.</p>
                  <p>{r.summary}</p>
                  <p style={{ color: "#8a8d99" }}>Disagree? Override in chat.</p>
                </>
              )}
            </WhyPopover>
          </span>
          {!scene && (
            <>
              <span style={{ flex: 1 }} />
              <button className="t-btn ghost" onClick={onClose} title="Close">✕</button>
            </>
          )}
        </div>
        <h2 className="dt-title">{r.title}</h2>
        <div className="dt-meta">
          <span>{r.age}</span>
          {r.origin && <OriginChip origin={r.origin} />}
        </div>
        <div className="dt-actions">
          {r.status === "needs-input" && (
            <button className="dt-feedback" onClick={() => setTab("chat")}>Reply to agent</button>
          )}
          <CopyLinkButton id={r.id} variant="labelled" />
          <span style={{ flex: 1 }} />
          <button className="t-btn ghost" onClick={() => onDismiss(r)}>Dismiss</button>
        </div>
      </div>
      <div className="dt-tabs">
        <button className={"dt-tab" + (tab === "overview" ? " active" : "")} onClick={() => setTab("overview")}>Overview</button>
        <button className={"dt-tab" + (tab === "chat" ? " active" : "")} onClick={() => setTab("chat")}>
          Chat <span className="badge">{r.chat?.length || 0}</span>
          {r.status === "needs-input" && <span className="nudge" />}
        </button>
      </div>
      <div className="dt-body">
        {tab === "overview" && (
          <>
            <div className="dt-section">
              <div className="dt-section-head"><span className="num">1</span> What the agent looked at</div>
              <div className="dt-section-body"><p>{r.summary}</p></div>
            </div>
            <div className="dt-section">
              <div className="dt-section-head"><span className="num">2</span> Signals reviewed</div>
              <div className="dt-section-body">
                <div className="evidence-list">{r.signals.map((ev, i) => <Evidence key={i} ev={ev} />)}</div>
              </div>
            </div>
            {r.blockers.length > 0 && (
              <div className="dt-section">
                <div className="dt-section-head"><span className="num">3</span> What's blocking a solution</div>
                <div className="dt-section-body">
                  <div className="report-blockers">
                    <div className="head">Needs from you</div>
                    <ul>{r.blockers.map((b, i) => <li key={i}>{b}</li>)}</ul>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
        {tab === "chat" && (
          <div className="dt-section">
            <div className="dt-section-body">
              <ChatThread chat={r.chat} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { SolutionDetail, ReportDetail, DismissDialog });
