/* Review inbox — uncategorized + flagged transactions */

const ReviewInbox = ({ goTo, txState, setTxState, rules, setRules }) => {
  const queue = React.useMemo(() => window.CB_INTEL.reviewQueue(txState), [txState]);
  const [picked, setPicked] = React.useState(0);
  const current = queue[Math.min(picked, queue.length - 1)];

  // If the queue empties, reset index
  React.useEffect(() => {
    if (picked >= queue.length && queue.length > 0) setPicked(queue.length - 1);
  }, [queue.length]);

  const categorizeAndContinue = async (catId, makeRule) => {
    if (!current) return;
    try {
      if (window.CB_API) await window.CB_API.updateTransaction(current.id, { categoryId: catId, needsReview: false });
      setTxState(ts => ts.map(t =>
        t.id === current.id
          ? { ...t, category: catId, needsReview: false, autoCategorized: false }
          : t
      ));
      if (makeRule) {
        const token = current.vendor.split(/\s+/).slice(0, 2).join(" ");
        const ruleBody = { match: { vendorContains: token }, categoryId: catId, description: `Match: vendor contains "${token}"` };
        if (window.CB_API) {
          const saved = await window.CB_API.createRule(ruleBody);
          setRules(rs => [...rs, { id: saved.id, match: saved.match, category: saved.category, description: saved.description, priority: saved.priority }]);
        } else {
          setRules(rs => [...rs, { id: "r_" + Date.now(), match: ruleBody.match, category: catId, description: ruleBody.description }]);
        }
      }
      setPicked(p => Math.min(p, queue.length - 2));
    } catch(e) {
      window.toast?.({ type: "error", message: "Failed to save" });
    }
  };

  const skip = () => setPicked(p => (p + 1) % Math.max(1, queue.length));

  const markCategorized = (txId, catId) => {
    setTxState(ts => ts.map(t => t.id === txId ? { ...t, category: catId, needsReview: false } : t));
  };

  const runAllRules = async () => {
    const result = window.CB_INTEL.runRulesOverLedger(rules, txState);
    setTxState(result.updated);
    if (window.CB_API && result.categorized > 0) {
      const changed = result.updated.filter((t, i) => t.category !== txState[i]?.category || t.needsReview !== txState[i]?.needsReview);
      await Promise.allSettled(changed.map(t =>
        window.CB_API.updateTransaction(t.id, { categoryId: t.category, needsReview: t.needsReview })
      ));
    }
  };

  const expenseCats = window.CB_DATA.categories.expense;
  const incomeCats = window.CB_DATA.categories.income;
  const currentCats = current?.type === "income" ? incomeCats : expenseCats;

  if (queue.length === 0) {
    return (
      <div className="page-fade">
        <div className="page-head">
          <div>
            <h1 className="page-title">Review</h1>
            <div className="page-sub">Inbox zero — everything's categorized</div>
          </div>
        </div>
        <EmptyState
          icon="check"
          title="All caught up"
          subtitle="Every transaction is categorized. Connect more accounts or import a CSV to keep things flowing."
          action={{ label: "View ledger", icon: "ledger", onClick: () => goTo("ledger") }}
          secondary={{ label: "Manage rules", icon: "sparkles", onClick: () => goTo("settings") }}
        />
      </div>
    );
  }

  return (
    <div className="page-fade">
      <div className="page-head">
        <div>
          <h1 className="page-title">Review</h1>
          <div className="page-sub">
            {queue.length} transaction{queue.length === 1 ? "" : "s"} need your attention
          </div>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={runAllRules}>
            <Icon name="sparkles" size={14} /> Re-run rules
          </button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "280px 1fr", gap: 16 }}>
        {/* Queue list */}
        <div className="card" style={{ padding: 0, maxHeight: 600, overflowY: "auto" }}>
          <div style={{ padding: "14px 16px 10px", fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.05em", borderBottom: "1px solid var(--hairline)" }}>
            Queue ({queue.length})
          </div>
          {queue.map((tx, i) => {
            const cat = CB.catById(tx.suggestedCategory);
            return (
              <button key={tx.id}
                onClick={() => setPicked(i)}
                style={{
                  width: "100%", border: 0, background: i === picked ? "var(--surface-2)" : "transparent",
                  padding: "12px 16px", borderBottom: "1px solid var(--hairline)", cursor: "pointer",
                  textAlign: "left", display: "block",
                  borderLeft: i === picked ? "3px solid var(--primary)" : "3px solid transparent",
                }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
                  <div style={{ fontWeight: 500, fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}>
                    {tx.vendor}
                  </div>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: tx.type === "income" ? "var(--income-text)" : "var(--ink)" }}>
                    {tx.type === "income" ? "+" : "−"}{CB.fmtCur(tx.amount, tx.currency || "USD", { cents: false })}
                  </span>
                </div>
                <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2, display: "flex", alignItems: "center", gap: 6 }}>
                  {new Date(tx.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                  {!tx.category
                    ? <Pill kind="">Uncategorized</Pill>
                    : <Pill kind="primary">Confirm: {cat?.name}</Pill>
                  }
                </div>
              </button>
            );
          })}
        </div>

        {/* Detail */}
        {current && (
          <div className="card" style={{ padding: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
              <div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 28, lineHeight: 1.1 }}>
                  {current.vendor}
                </div>
                <div style={{ color: "var(--muted)", marginTop: 6, fontSize: 13 }}>
                  {new Date(current.date).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" })}
                  {" · "}{CB.accountById(current.account)?.name}
                </div>
                {current.note && (
                  <div style={{ marginTop: 8, fontSize: 13, color: "var(--ink-soft)" }}>{current.note}</div>
                )}
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="bignum-sm" style={{ color: current.type === "income" ? "var(--income-text)" : "var(--ink)" }}>
                  {current.type === "income" ? "+" : "−"}{CB.fmtCur(current.amount, current.currency || "USD")}
                </div>
                {!current.category
                  ? <Pill kind="">Uncategorized</Pill>
                  : <Pill kind="primary">Suggested: {CB.catById(current.suggestedCategory)?.name}</Pill>
                }
              </div>
            </div>

            <div style={{ marginTop: 22, padding: "14px 0", borderTop: "1px solid var(--hairline)", borderBottom: "1px solid var(--hairline)" }}>
              <div className="label">Pick a category</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6, marginTop: 4 }}>
                {currentCats.map(c => (
                  <button key={c.id}
                    className={"chip" + (c.id === current.suggestedCategory ? " on" : "")}
                    style={{ justifyContent: "flex-start", padding: "9px 11px" }}
                    onClick={() => categorizeAndContinue(c.id, false)}>
                    <span className="cat-swatch" style={{ background: c.color }} />
                    <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.name}</span>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ marginTop: 16, display: "flex", gap: 8, alignItems: "center" }}>
              {current.suggestedCategory && (
                <button className="btn btn-primary" onClick={() => categorizeAndContinue(current.suggestedCategory, false)}>
                  <Icon name="check" size={14} /> Accept "{CB.catById(current.suggestedCategory)?.name}"
                </button>
              )}
              <button className="btn"
                disabled={!current.suggestedCategory}
                onClick={() => categorizeAndContinue(current.suggestedCategory, true)}>
                <Icon name="sparkles" size={14} /> Accept + make rule
              </button>
              <button className="btn btn-ghost" onClick={skip}>Skip</button>
              <div style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--muted)" }}>
                {picked + 1} of {queue.length}
              </div>
            </div>

            <div className="card-quiet" style={{ marginTop: 20, padding: 12, fontSize: 12, color: "var(--ink-soft)" }}>
              <b style={{ color: "var(--ink)" }}>Make a rule</b> to auto-categorize future charges from this vendor.
              Rules run during every account sync — you'll only see new vendors here.
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.ReviewInbox = ReviewInbox;
