
// SynthesizedItemCard — renders ONE item returned by the synthesis service.
// Used by both the Opportunities surface and the What-Matters-Now panel. It
// renders only the fields the service returned; it never runs the evaluator,
// reads catalogs, or parses a signal set. The rendering structure is universal
// across archetypes — content varies because the synthesis output varies, the
// component does not branch on archetype.
//
//   <window.SynthesizedItemCard item={item} setPage={setPage} setDrillKey={setDrillKey} />
//
// item: { headline, supporting_detail, diagnosed_driver, recommended_action,
//         estimated_dollar_impact, drill_into, source_signal_ids }
// Opportunities items additionally carry (all optional, guardrailed server-side):
//   account, current_spend, saving_pct, impact ("High"|"Medium"|"Low"),
//   trend ("Rising"|"Stable"|"Falling"), how_to_achieve: string[]

(function () {
  const R = window.React;
  if (!R) return;

  // Severity → left-border color. Opt-in via the `severityBorder` prop (Stage 10
  // Top Findings panel); other consumers render the neutral card unchanged.
  const SEV_BORDER = { high: "#c0392b", medium: "#b7791f", low: "#047857" }; // red / amber / green

  const fmtUSD = (n) => {
    const F = window.PerduraFmt;
    if (F && F.fmtUSD) return F.fmtUSD(Math.abs(n), { compact: true });
    return "$" + Math.round(Math.abs(n)).toLocaleString();
  };

  function Field({ label, value, color }) {
    if (!value) return null;
    return R.createElement("div", { style: { marginTop: 8 } },
      R.createElement("div", {
        style: { fontSize: 11, textTransform: "uppercase", letterSpacing: 0.4, color: "var(--text-3,#98a2b3)", fontWeight: 600, marginBottom: 2 },
      }, label),
      R.createElement("div", { style: { fontSize: 13.5, color: color || "var(--text-1,#111)", lineHeight: 1.5 } }, value)
    );
  }

  // ── Opportunities savings card (PerduraCEO design): expandable row with a
  // savings strip, why/how, and drill-through. Rendered only when the item
  // carries the additive savings fields; otherwise the neutral card is used.
  const IMPACT_COLOR = { High: "#e74c3c", Medium: "#f59e0b", Low: "#6475a0" };
  const TREND_COLOR = { Rising: "#e74c3c", Falling: "#00b894", Stable: "#6475a0" };
  const IMPACT_DOT = { High: "🔴", Medium: "🟡", Low: "🟢" };

  function Badge({ text, color }) {
    if (!text) return null;
    return R.createElement("span", {
      style: { padding: "2px 8px", borderRadius: 12, background: (color || "#6475a0") + "22", color: color || "#6475a0", fontSize: 9, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.4 },
    }, text);
  }

  function SavingsCard({ item, expanded, onToggle }) {
    const account = item.account || item.headline;
    const impactColor = IMPACT_COLOR[item.impact] || "#6475a0";
    const trendColor = TREND_COLOR[item.trend] || "#6475a0";
    const hasSaving = item.estimated_dollar_impact != null && isFinite(item.estimated_dollar_impact);
    const steps = Array.isArray(item.how_to_achieve) && item.how_to_achieve.length
      ? item.how_to_achieve
      : (item.recommended_action ? [item.recommended_action] : []);

    return R.createElement("div", {
      style: {
        border: expanded ? "1px solid #e74c3c" : "1px solid var(--border,#e9ecef)",
        borderRadius: 10, marginBottom: 8, overflow: "hidden", background: "#fff", transition: "all .2s",
      },
    },
      // Row header — always visible, click to expand.
      R.createElement("div", {
        onClick: onToggle,
        title: "Click to see why it matters and how to achieve it",
        style: { padding: "14px 18px", display: "flex", alignItems: "center", gap: 12, cursor: "pointer", background: expanded ? "rgba(231,76,60,.04)" : "#fff" },
      },
        R.createElement("div", {
          style: { width: 32, height: 32, borderRadius: 8, background: expanded ? "#e74c3c" : "rgba(13,32,64,.06)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, fontSize: 14 },
        }, IMPACT_DOT[item.impact] || "🟢"),
        R.createElement("div", { style: { flex: 1, minWidth: 0 } },
          R.createElement("div", { style: { fontSize: 13, fontWeight: 700, color: "#0d2040", marginBottom: 3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, account),
          R.createElement("div", { style: { display: "flex", gap: 6, flexWrap: "wrap" } },
            item.impact ? R.createElement(Badge, { text: item.impact + " impact", color: impactColor }) : null,
            item.trend ? R.createElement(Badge, { text: item.trend, color: trendColor }) : null
          )
        ),
        item.current_spend != null ? R.createElement("div", { style: { textAlign: "right", flexShrink: 0 } },
          R.createElement("div", { style: { fontSize: 11, color: "#6475a0", marginBottom: 2 } }, "Current spend"),
          R.createElement("div", { style: { fontSize: 12, fontWeight: 700, color: "#1a2540", fontFamily: "'JetBrains Mono',ui-monospace,monospace" } }, fmtUSD(item.current_spend))
        ) : null,
        R.createElement("div", { style: { textAlign: "right", flexShrink: 0, marginLeft: 16 } },
          R.createElement("div", { style: { fontSize: 11, color: "#6475a0", marginBottom: 2 } }, "Potential saving"),
          R.createElement("div", { style: { fontSize: 14, fontWeight: 800, color: "#00b894", fontFamily: "'JetBrains Mono',ui-monospace,monospace" } }, hasSaving ? fmtUSD(item.estimated_dollar_impact) : "—"),
          item.saving_pct != null ? R.createElement("div", { style: { fontSize: 10, color: "#00b894" } }, item.saving_pct + "% reduction") : null
        ),
        R.createElement("div", { style: { color: "#6475a0", fontSize: 12, marginLeft: 8 } }, expanded ? "▲" : "▼")
      ),
      // Expanded detail.
      expanded ? R.createElement("div", { style: { borderTop: "1px solid #e9ecef", background: "rgba(231,76,60,.02)", padding: 20 } },
        // Savings summary strip.
        R.createElement("div", { style: { display: "flex", gap: 1, background: "rgba(13,32,64,.06)", borderRadius: 8, overflow: "hidden", marginBottom: 16 } },
          [
            { label: "Period Spend", value: item.current_spend != null ? fmtUSD(item.current_spend) : "—" },
            { label: "Potential Saving", value: hasSaving ? fmtUSD(item.estimated_dollar_impact) : "—", color: "#00b894" },
            { label: "Saving %", value: item.saving_pct != null ? item.saving_pct + "%" : "—", color: "#00b894" },
          ].map((s, si) => R.createElement("div", { key: si, style: { flex: 1, background: "#fff", padding: "10px 8px", textAlign: "center" } },
            R.createElement("div", { style: { fontSize: 9, fontWeight: 700, color: "#6475a0", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 3 } }, s.label),
            R.createElement("div", { style: { fontSize: 13, fontWeight: 800, color: s.color || "#0d2040", fontFamily: "'JetBrains Mono',ui-monospace,monospace" } }, s.value)
          ))
        ),
        // Why this matters.
        item.supporting_detail ? R.createElement("div", { style: { marginBottom: 16 } },
          R.createElement("div", { style: { fontSize: 10, fontWeight: 700, color: "#6475a0", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 } }, "Why This Matters"),
          R.createElement("div", { style: { fontSize: 12.5, color: "#1a2540", lineHeight: 1.7 } }, item.supporting_detail)
        ) : null,
        // How to achieve it.
        steps.length ? R.createElement("div", { style: { marginBottom: 16 } },
          R.createElement("div", { style: { fontSize: 10, fontWeight: 700, color: "#6475a0", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 } }, "How To Achieve It"),
          R.createElement("ul", { style: { margin: 0, padding: "0 0 0 16px" } },
            steps.map((tip, ti) => R.createElement("li", { key: ti, style: { fontSize: 11.5, color: "#4a5680", marginBottom: 6, lineHeight: 1.6 } }, tip))
          )
        ) : null,
        // Drill-through buttons — real data, no fabricated in-card chart.
        R.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 } },
          R.createElement("button", {
            onClick: () => window.openAccountDetail && window.openAccountDetail({ name: account, category: item.category || undefined, page: "opportunities" }),
            style: { padding: "7px 16px", background: "rgba(13,32,64,.06)", border: "1px solid rgba(13,32,64,.12)", borderRadius: 7, fontSize: 11, fontWeight: 600, color: "#0d2040", cursor: "pointer" },
          }, "📊 View Monthly Breakdown"),
          R.createElement("button", {
            onClick: () => window.openGLDrawer ? window.openGLDrawer({ accountName: account }) : (window.openAccountDetail && window.openAccountDetail({ name: account, page: "opportunities" })),
            style: { padding: "7px 16px", background: "#0d2040", color: "#fff", border: "none", borderRadius: 7, fontSize: 11, fontWeight: 700, cursor: "pointer" },
          }, "→ View Transactions")
        )
      ) : null
    );
  }

  function SynthesizedItemCard({ item, setPage, setDrillKey, severityBorder }) {
    const [expanded, setExpanded] = R.useState(false);
    if (!item) return null;

    // Opportunities items carry the additive savings fields → PerduraCEO
    // expandable savings card. Every other surface keeps the neutral card.
    const isSavings = !!(item.how_to_achieve || item.current_spend != null || item.impact || item.account);
    if (isSavings) {
      return R.createElement(SavingsCard, { item, expanded, onToggle: () => setExpanded(!expanded) });
    }

    const hasImpact = item.estimated_dollar_impact != null && isFinite(item.estimated_dollar_impact);
    const sevColor = (severityBorder && item.severity && SEV_BORDER[item.severity]) || null;

    const onDrill = () => {
      if (window.PerduraSynthesis && window.PerduraSynthesis.navigateDrill) {
        window.PerduraSynthesis.navigateDrill(item.drill_into, setPage, setDrillKey);
      }
    };

    return R.createElement("div", {
      className: "pc-intel-card",
      style: {
        border: "1px solid var(--border,#e4e7ec)", borderRadius: 12, padding: 16,
        marginBottom: 12, background: "var(--surface-1,#fff)",
        boxShadow: "0 1px 2px rgba(16,24,40,0.04)",
        ...(sevColor ? { borderLeft: `4px solid ${sevColor}`, paddingLeft: 16 } : {}),
      },
    },
      // Header: headline + prominent dollar impact.
      R.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16 } },
        R.createElement("div", { style: { fontSize: 15.5, fontWeight: 700, color: "var(--text-1,#111)", lineHeight: 1.35 } }, item.headline),
        hasImpact
          ? R.createElement("div", {
            style: {
              flex: "0 0 auto", textAlign: "right",
              fontSize: 20, fontWeight: 800, color: "var(--positive,#047857)",
              whiteSpace: "nowrap",
            },
          }, fmtUSD(item.estimated_dollar_impact))
          : null
      ),
      item.supporting_detail
        ? R.createElement("div", { style: { fontSize: 13.5, color: "var(--text-2,#475467)", marginTop: 8, lineHeight: 1.5 } }, item.supporting_detail)
        : null,
      R.createElement(Field, { label: "Why", value: item.diagnosed_driver }),
      R.createElement(Field, { label: "Recommended action", value: item.recommended_action, color: "var(--text-1,#111)" }),
      // Drill-into link.
      item.drill_into
        ? R.createElement("button", {
          className: "pc-btn-mini ghost",
          onClick: onDrill,
          style: { marginTop: 14, cursor: "pointer" },
        }, "View details →")
        : null
    );
  }

  window.SynthesizedItemCard = SynthesizedItemCard;
})();
