{
const n = pg_controls.n, a_top = pg_controls.a_top, delta = pg_controls.delta, MC = pg_controls.mc;
const slope = 0.5, Qmax = 100, Pmax = 200;
const a_i = d3.range(n).map(i => a_top - i * delta);
const Qs = d3.range(0, Qmax + 0.5, 0.5);
const indivCurves = a_i.map((a, idx) =>
Qs.map(q => ({Q: q, P: Math.max(0, a - slope * q)})).filter(p => p.P >= 0 && p.P <= Pmax));
const msb = Qs.map(q => ({Q: q, P: a_i.reduce((acc, a) => acc + Math.max(0, a - slope * q), 0)}))
.filter(p => p.P >= 0 && p.P <= Pmax);
const mcLine = [{Q: 0, P: MC}, {Q: Qmax, P: MC}];
let Qstar = 0;
for (let i = msb.length - 1; i >= 0; i--) { if (msb[i].P >= MC) { Qstar = msb[i].Q; break; } }
const Qm = Math.max(0, (a_i[0] - MC) / slope);
const palette = ["#A9C3DA", "#7FA3C6", "#5683B0", "#3D6B99", "#2D5A8E", "#1E3F63"];
const indivMarks = indivCurves.map((curve, idx) =>
Plot.line(curve, {x: "Q", y: "P", stroke: palette[idx % palette.length], strokeWidth: 1.5}));
return Plot.plot({
width: 880, height: 320, marginLeft: 52, marginRight: 20, marginTop: 24, marginBottom: 40,
style: {fontSize: "12px", fontFamily: "Public Sans, system-ui, sans-serif", color: "#3A332D", background: "transparent"},
x: {label: "Količina javnog dobra (Q) →", domain: [0, Qmax]},
y: {label: "↑ Cijena / Korist (P)", domain: [0, Pmax], grid: true},
marks: [
Plot.ruleY([0], {stroke: "#C9C3B8"}),
...indivMarks,
Plot.line(msb, {x: "Q", y: "P", stroke: "#1C1916", strokeWidth: 3}),
Plot.line(mcLine, {x: "Q", y: "P", stroke: "#6B1F26", strokeWidth: 2.5}),
Plot.ruleX([Qm], {y1: 0, y2: MC, stroke: "#6B6357", strokeDasharray: "4,3"}),
Plot.ruleX([Qstar], {y1: 0, y2: MC, stroke: "#6B6357", strokeDasharray: "4,3"}),
Plot.dot([{Q: Qm, P: MC}], {x: "Q", y: "P", r: 5, fill: "#6B1F26", stroke: "white", strokeWidth: 2}),
Plot.dot([{Q: Qstar, P: MC}], {x: "Q", y: "P", r: 5, fill: "#1C1916", stroke: "white", strokeWidth: 2}),
Plot.text([{x: Qmax * 0.62, y: msb.find(p => p.Q >= Qmax * 0.62)?.P ?? 0, label: "ΣDᵢ = MSB"}],
{x: "x", y: "y", text: "label", fill: "#1C1916", fontSize: 13, fontWeight: 700, dy: -10}),
Plot.text([{x: Qmax * 0.05, y: MC, label: `MC = ${MC}`}],
{x: "x", y: "y", text: "label", fill: "#6B1F26", fontSize: 12, fontWeight: 600, dy: -8, textAnchor: "start"}),
Plot.text([{x: Qm, y: 4, label: `Q_M = ${Qm.toFixed(1)}`}],
{x: "x", y: "y", text: "label", textAnchor: "middle", fontSize: 11, fill: "#6B1F26"}),
Plot.text([{x: Qstar, y: 4, label: `Q* = ${Qstar.toFixed(1)}`}],
{x: "x", y: "y", text: "label", textAnchor: "middle", fontSize: 11, fill: "#1C1916"}),
Plot.text([{x: 2, y: Pmax * 0.97, label: `Premala tržišna proizvodnja: Q* − Q_M = ${(Qstar - Qm).toFixed(1)}`}],
{x: "x", y: "y", text: "label", textAnchor: "start", fontSize: 14, fill: "#1C1916", fontWeight: 700})
]
});
}