// ============ NOW VIEW ============
// Live priority queue. Shows the top 5 conversations needing attention,
// sorted by urgency score. Auto-polls every 60s. Default landing tab.

const S = () => (window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) || "";
const POLL_INTERVAL_MS = 60 * 1000;
const OPTIMISTIC_HIDE_MS = 25 * 60 * 1000; // 25 min
const BANNER_KEY = "citrus_now_banner_dismissed";

function NowUrgencyChip({ reason }) {
  if (!reason || reason === "Active") return null;
  const isEscalation = reason.toLowerCase().includes("escalation");
  const isWaiting    = reason.toLowerCase().includes("waiting") || reason.toLowerCase().includes("no reply");
  const color = isEscalation
    ? { bg: "var(--red-soft, #fff0f0)", text: "var(--red, #c0392b)", border: "var(--red-soft2, #fdd)" }
    : isWaiting
    ? { bg: "var(--amber-soft, #fffbea)", text: "var(--amber, #b45309)", border: "var(--amber-soft2, #fde68a)" }
    : { bg: "var(--ink-wash, #f5f5f5)", text: "var(--ink-2, #666)", border: "var(--border, #eee)" };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "2px 8px", borderRadius: 20, fontSize: 11, fontWeight: 500,
      background: color.bg, color: color.text, border: `1px solid ${color.border}`,
    }}>
      {reason}
    </span>
  );
}

function NowRow({ item, onOpen }) {
  const waitLabel = item.waitMs != null
    ? (() => {
        const m = Math.round(item.waitMs / 60000);
        if (m < 60) return `${m}m`;
        return `${Math.round(m / 60)}h`;
      })()
    : null;

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={() => onOpen(item)}
      onKeyDown={(e) => e.key === "Enter" && onOpen(item)}
      style={{
        display: "flex", alignItems: "center", gap: 12, padding: "14px 16px",
        borderBottom: "1px solid var(--border, #eee)", cursor: "pointer",
        transition: "background 0.12s",
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = "var(--row-hover, #f9f9f9)"}
      onMouseLeave={(e) => e.currentTarget.style.background = ""}
    >
      <div style={{ width: 32, height: 32, borderRadius: "50%", background: "var(--ink-wash, #eee)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 600, color: "var(--ink-2, #666)", flexShrink: 0 }}>
        {(item.customerName || "?")[0].toUpperCase()}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {item.customerName}
          </span>
          {item.agentName && (
            <span style={{ fontSize: 11, color: "var(--ink-2, #888)", flexShrink: 0 }}>{item.agentName}</span>
          )}
          {waitLabel && (
            <span style={{ fontSize: 11, color: "var(--ink-3, #aaa)", marginLeft: "auto", flexShrink: 0 }}>{waitLabel}</span>
          )}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
          <NowUrgencyChip reason={item.urgencyReason} />
          {item.lastMessage && (
            <span style={{ fontSize: 12, color: "var(--ink-2, #888)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 240 }}>
              {item.lastMessage}
            </span>
          )}
        </div>
      </div>
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, color: "var(--ink-3, #bbb)" }}>
        <path d="M6 3l5 5-5 5"/>
      </svg>
    </div>
  );
}

function NowBanner({ onDismiss }) {
  return (
    <div style={{
      display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 16px",
      background: "var(--blue-soft, #eff6ff)", borderBottom: "1px solid var(--blue-soft2, #dbeafe)",
      fontSize: 12, color: "var(--blue, #1d4ed8)",
    }}>
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
        <circle cx="8" cy="8" r="6"/><path d="M8 6h.01M8 8v3"/>
      </svg>
      <span style={{ flex: 1, lineHeight: 1.5 }}>
        Your inbox now sorts by urgency — CITRUS decides what needs your attention first. Recency view is still under <strong>Inbox</strong>.
      </span>
      <button
        onClick={onDismiss}
        style={{ background: "none", border: "none", cursor: "pointer", padding: "0 2px", color: "var(--blue-2, #3b82f6)", fontSize: 16, lineHeight: 1, flexShrink: 0 }}
        aria-label="Dismiss"
      >×</button>
    </div>
  );
}

function NowTab({ onSwitchTab, onAskCitrus }) {
  const [queue, setQueue]         = React.useState(null);    // null = loading
  const [computedAt, setComputedAt] = React.useState(undefined);
  const [total, setTotal]         = React.useState(0);
  const [error, setError]         = React.useState(null);
  const [showBanner, setShowBanner] = React.useState(() => {
    try { return !localStorage.getItem(BANNER_KEY); } catch { return true; }
  });
  const repliedIds = React.useRef(new Set());
  const repliedTimestamps = React.useRef({});

  const dismissBanner = () => {
    setShowBanner(false);
    try { localStorage.setItem(BANNER_KEY, "1"); } catch {}
  };

  const isOptimisticallyHidden = (id) => {
    if (!repliedIds.current.has(id)) return false;
    const ts = repliedTimestamps.current[id] || 0;
    return (Date.now() - ts) < OPTIMISTIC_HIDE_MS;
  };

  const fetchQueue = React.useCallback(async () => {
    try {
      const r = await fetch(`${S()}/api/citrus/priority-queue`);
      if (!r.ok) throw new Error(`${r.status}`);
      const data = await r.json();
      setComputedAt(data.computedAt || null);
      setTotal(data.total || 0);
      // Prune expired optimistic hides
      for (const id of repliedIds.current) {
        const ts = repliedTimestamps.current[id] || 0;
        if ((Date.now() - ts) >= OPTIMISTIC_HIDE_MS) {
          repliedIds.current.delete(id);
          delete repliedTimestamps.current[id];
        }
      }
      setQueue((data.queue || []).filter((item) => !isOptimisticallyHidden(item.conversationId)));
      setError(null);
    } catch (e) {
      setError("Could not load priority queue.");
    }
  }, []);

  // Initial load + 60s auto-poll
  React.useEffect(() => {
    fetchQueue();
    const timer = setInterval(fetchQueue, POLL_INTERVAL_MS);
    return () => clearInterval(timer);
  }, [fetchQueue]);

  // Listen for reply events from inbox.jsx to apply optimistic removal
  React.useEffect(() => {
    const handler = (e) => {
      const id = e.detail?.from;
      if (!id) return;
      repliedIds.current.add(id);
      repliedTimestamps.current[id] = Date.now();
      setQueue((prev) => (prev || []).filter((item) => item.conversationId !== id));
    };
    window.addEventListener("citrus:replied", handler);
    return () => window.removeEventListener("citrus:replied", handler);
  }, []);

  // Analytics: fire now_view_open on mount (T9)
  React.useEffect(() => {
    fetch(`${S()}/api/citrus/metrics`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ event: "now_view_open", queueLength: queue?.length ?? 0, totalUrgent: total, hasItems: (queue?.length ?? 0) > 0 }),
    }).catch(() => {});
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // fire once on mount only

  const handleRowClick = (item, position) => {
    // Analytics: fire now_row_click (T9)
    fetch(`${S()}/api/citrus/metrics`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        event: "now_row_click",
        position,
        urgencyReason: item.urgencyReason,
        waitMinutes: item.waitMs != null ? Math.round(item.waitMs / 60000) : null,
      }),
    }).catch(() => {});
    // Navigate to inbox with this thread pre-selected
    if (onSwitchTab) onSwitchTab("inbox", { threadId: item.conversationId });
  };

  const lastUpdatedLabel = React.useMemo(() => {
    if (!computedAt) return null;
    const diffMs = Date.now() - new Date(computedAt).getTime();
    const m = Math.round(diffMs / 60000);
    if (m < 1) return "just now";
    return `${m}m ago`;
  }, [computedAt]);

  const headerCount = total > 5 ? `5 of ${total}` : (queue?.length ?? 0);
  const isComputing = computedAt === null;

  return (
    <div style={{ maxWidth: 640, margin: "0 auto", padding: "0 0 40px" }}>
      {/* Banner — one-time dismissible */}
      {showBanner && <NowBanner onDismiss={dismissBanner} />}

      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 16px 12px" }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: "var(--ink)" }}>
            {isComputing
              ? "Computing priorities…"
              : queue?.length
              ? `CITRUS sees ${headerCount} conversation${headerCount !== 1 ? "s" : ""} needing attention`
              : "CITRUS sees nothing urgent right now"}
          </h2>
          {lastUpdatedLabel && !isComputing && (
            <p style={{ margin: "3px 0 0", fontSize: 11, color: "var(--ink-3, #aaa)" }}>
              Last updated {lastUpdatedLabel}
            </p>
          )}
        </div>
        <button
          onClick={fetchQueue}
          title="Refresh"
          style={{ background: "none", border: "none", cursor: "pointer", padding: 6, color: "var(--ink-2, #888)", borderRadius: 6 }}
        >
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M2 8a6 6 0 1 0 1.5-3.9M2 4v4h4"/>
          </svg>
        </button>
      </div>

      {/* Content */}
      {error ? (
        <div style={{ padding: "32px 16px", textAlign: "center", color: "var(--ink-2, #888)", fontSize: 13 }}>
          {error}
        </div>
      ) : isComputing ? (
        <div style={{ padding: "48px 16px", textAlign: "center" }}>
          <div style={{ fontSize: 28, marginBottom: 12, opacity: 0.4 }}>◌</div>
          <p style={{ fontSize: 13, color: "var(--ink-2, #888)", margin: 0, lineHeight: 1.6 }}>
            Scoring all active conversations — this takes about 15 seconds on first deploy.
          </p>
        </div>
      ) : queue === null ? (
        <div style={{ padding: "48px 16px", textAlign: "center", color: "var(--ink-3, #bbb)", fontSize: 13 }}>
          Loading…
        </div>
      ) : queue.length === 0 ? (
        <EmptyState onSwitchTab={onSwitchTab} />
      ) : (
        <div style={{ borderTop: "1px solid var(--border, #eee)", borderRadius: 8, overflow: "hidden", margin: "0 16px" }}>
          {queue.map((item, i) => (
            <NowRow key={item.conversationId} item={item} onOpen={() => handleRowClick(item, i)} />
          ))}
        </div>
      )}

      {/* Ask Citrus nudge */}
      {!isComputing && (
        <div style={{ padding: "16px 16px 0", textAlign: "center" }}>
          <button
            onClick={() => onAskCitrus?.()}
            style={{ background: "none", border: "none", cursor: "pointer", fontSize: 12, color: "var(--ink-2, #888)", padding: "4px 8px", borderRadius: 6 }}
          >
            Ask CITRUS what to handle next →
          </button>
        </div>
      )}
    </div>
  );
}

function EmptyState({ onSwitchTab }) {
  // Analytics: fire now_empty_state (T9)
  React.useEffect(() => {
    const S = () => (window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) || "";
    fetch(`${S()}/api/citrus/metrics`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ event: "now_empty_state", trigger: "empty" }),
    }).catch(() => {});
  }, []);

  return (
    <div style={{ padding: "48px 16px", textAlign: "center" }}>
      <div style={{ fontSize: 28, marginBottom: 12, opacity: 0.3 }}>✓</div>
      <p style={{ fontSize: 14, color: "var(--ink)", fontWeight: 500, margin: "0 0 6px" }}>
        All conversations are being handled.
      </p>
      <p style={{ fontSize: 13, color: "var(--ink-2, #888)", margin: 0, lineHeight: 1.6 }}>
        Nothing needs your attention right now.{" "}
        <button
          onClick={() => onSwitchTab && onSwitchTab("inbox")}
          style={{ background: "none", border: "none", cursor: "pointer", color: "var(--blue, #2563eb)", fontSize: 13, padding: 0, textDecoration: "underline" }}
        >
          Browse all conversations →
        </button>
      </p>
    </div>
  );
}

window.NowTab = NowTab;
