// Agentic Review Center — the guided prototype flow.
const RV = window.RP;

function sevColor(s) { return s === "HIGH" ? "var(--rp-sev-high)" : s === "MED" ? "var(--rp-sev-med)" : "var(--rp-sev-low)"; }
function SeverityPill({ s }) {
  return <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".05em", color: "#fff", background: sevColor(s), padding: "2px 8px", borderRadius: 9999 }}>{s}</span>;
}
function now() { return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); }

// ---- Recommendation / detail block for an issue ----
function IssueDetail({ issue, status, draft, setDraft, onSend, onApprove, onDecline, onDismiss }) {
  const { Icon, Button, Avatar } = RV;
  if (!issue) return null;
  const waiting = status === "waiting";
  return (
    <div style={{ background: "#fff", borderRadius: 8, boxShadow: "var(--rp-shadow-card)", padding: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <SeverityPill s={issue.severity} />
            <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--rp-muted)" }}>{issue.category} · {issue.risk} at risk</span>
          </div>
          <div style={{ fontSize: 21, fontWeight: 700, color: "var(--rp-ink)", lineHeight: 1.2 }}>{issue.title}</div>
          <a style={{ fontSize: 13.5, color: "var(--rp-blue)", fontWeight: 700 }}>{issue.who} · #{issue.ref}</a>
        </div>
        <Avatar name={issue.who} flag={issue.flag} size={46} />
      </div>

      {waiting && (
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, background: "var(--rp-warning-soft)", borderRadius: 8, padding: "10px 14px" }}>
          <Icon name="Clock" size={16} color="#9A7400" />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: "#7a5c00" }}>Waiting on the contractor. Message sent to {issue.who.split(" ")[0]}.</span>
        </div>
      )}

      {/* AI Insights */}
      <div style={{ marginTop: 18, background: "var(--rp-ai-soft)", border: "1px solid #E3D8FA", borderRadius: 8, padding: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}>
          <span style={{ width: 24, height: 24, borderRadius: "50%", background: "var(--rp-ai-gradient)", display: "grid", placeItems: "center" }}>
            <Icon name="WandSparkles" size={14} color="#fff" stroke={2.2} />
          </span>
          <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--rp-ai-indigo)" }}>AI Insights</span>
        </div>
        <div style={{ fontSize: 14, color: "var(--rp-ink)", lineHeight: 1.5 }}>{issue.summary}</div>

        <div style={{ marginTop: 12, background: "#fff", borderRadius: 6, padding: "4px 4px" }}>
          {issue.evidence.map((e, i) => (
            <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 9, padding: "8px 10px", borderBottom: i < issue.evidence.length - 1 ? "1px solid var(--rp-border)" : "none" }}>
              <Icon name={e.flagged ? "CircleAlert" : "CircleCheck"} size={16} color={e.flagged ? "var(--rp-danger)" : "var(--rp-success)"} stroke={2.2} style={{ marginTop: 1 }} />
              <span style={{ fontSize: 13, color: "var(--rp-ink)", lineHeight: 1.45 }}>{e.label}</span>
            </div>
          ))}
        </div>

        {/* Recommended action */}
        <div style={{ marginTop: 14, fontSize: 12, fontWeight: 800, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--rp-ai-indigo)" }}>Recommended action</div>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--rp-ink)", marginTop: 4 }}>{issue.action}</div>

        {issue.kind === "ask" && (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 12, color: "var(--rp-muted)", marginBottom: 5 }}>Drafted message (editable)</div>
            <textarea value={draft} onChange={(e) => setDraft(e.target.value)} disabled={waiting}
              style={{ width: "100%", boxSizing: "border-box", minHeight: 78, resize: "vertical", border: "1px solid #E3D8FA", borderRadius: 6, padding: "10px 12px", fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--rp-ink)", lineHeight: 1.5, background: waiting ? "var(--rp-app-bg)" : "#fff" }} />
          </div>
        )}

        <div data-tour="issue-actions" style={{ display: "flex", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
          {issue.kind === "ask" && !waiting && <Button variant="ai" icon="Send" size="sm" onClick={onSend}>Send (confirm)</Button>}
          {!waiting && <Button variant="success" size="sm" onClick={onApprove}>Approve</Button>}
          {!waiting && <Button variant="danger" size="sm" onClick={onDecline}>Decline</Button>}
          {!waiting && <Button variant="ghost" size="sm" onClick={onDismiss}>Dismiss</Button>}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 12, color: "var(--rp-muted)" }}>
          <Icon name="Info" size={13} color="var(--rp-muted)" />
          <span style={{ fontSize: 11.5 }}>AI can make mistakes, double-check results.</span>
        </div>
      </div>
    </div>
  );
}

// ---- Count-up number ----
function CountUp({ value, prefix, duration = 900 }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const steps = 36, dt = duration / steps;
    let i = 0;
    const id = setInterval(() => {
      i++;
      const p = Math.min(1, i / steps);
      setN(value * (1 - Math.pow(1 - p, 3)));
      if (p >= 1) clearInterval(id);
    }, dt);
    return () => clearInterval(id);
  }, [value]);
  const disp = Number.isInteger(value) ? Math.round(n).toLocaleString("en-US") : n.toLocaleString("en-US", { maximumFractionDigits: 0 });
  return <span>{prefix}{disp}</span>;
}

window.IssueDetail = IssueDetail;
window.SeverityPill = SeverityPill;
window.CountUp = CountUp;
window.rcNow = now;
