/* global window, React */

window.Pipeline = function Pipeline({ ctx }) {
  const Icon = window.Icon;
  const stages = window.PIPELINE_STAGES;
  const [stage, setStage] = React.useState("all");

  const filtered = stage === "all" ? window.DEALS : window.DEALS.filter(d => d.stage === stage);
  const totalValue = filtered.reduce((a, b) => a + b.value, 0);

  return (
    <window.Screen
      title="Pipeline"
      right={<button className="icon-btn" onClick={() => ctx.notify("Filter deal")}><Icon.Filter size={18} /></button>}
    >
      {/* Summary */}
      <div className="m-card" style={{ marginBottom: 12 }}>
        <div className="between">
          <div>
            <div className="label-tiny">Total nilai pipeline</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, marginTop: 2 }}>
              {window.fmtShort(totalValue)}
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div className="label-tiny">Deal</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, marginTop: 2 }}>{filtered.length}</div>
          </div>
        </div>
      </div>

      {/* Stage chips */}
      <div className="chip-row">
        <window.Chip label={`Semua (${window.DEALS.length})`} active={stage === "all"} onClick={() => setStage("all")} />
        {stages.map(s => {
          const n = window.DEALS.filter(d => d.stage === s.id).length;
          return <window.Chip key={s.id} label={`${s.name} (${n})`} active={stage === s.id} onClick={() => setStage(s.id)} />;
        })}
      </div>

      {/* Deal list */}
      {filtered.map(d => {
        const st = stages.find(s => s.id === d.stage);
        const tone = d.stage === "won" ? "emerald" : d.stage === "contract" ? "primary" : d.stage === "nego" ? "warning" : d.stage === "survey" ? "indigo" : "info";
        return (
          <div key={d.id} className="deal-card" onClick={() => ctx.notify(`Detail ${d.name}`)}>
            <div className="dh">
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="dn">{d.name}</div>
                <div className="dc">{d.customer} · {d.rep}</div>
              </div>
              <window.StatusPill tone={tone}>{st?.name}</window.StatusPill>
            </div>
            <div className="dv">{window.fmtShort(d.value)}</div>
            <div className="df">
              <span>{d.age} hari di stage</span>
              <span className="prob">Prob {d.prob}%</span>
            </div>
            <div className="progress" style={{ marginTop: 8 }}>
              <div className="progress-fill" style={{ width: `${d.prob}%`, background: st?.color || "var(--primary)" }}></div>
            </div>
          </div>
        );
      })}

      <window.FAB icon="Plus" onClick={() => ctx.notify("Tambah deal baru")} />
    </window.Screen>
  );
};
