// maths-brevet-helpers.jsx
// Math-specific reusable building blocks for the Brevet pack.
// All composed on top of locked V1.2 blocks. No page chrome — these are
// inner components that go *inside* PageShell / Box / ExerciseCard.

const MB_F = React.Fragment;

/* ────────────────────────────────────────────────
   MathExpr — display math (lightweight, print-safe)
   ──────────────────────────────────────────────── */
function MathExpr({ children, size = "0.16in", display = false }) {
  return (
    <span style={{
      fontFamily: '"Cambria Math", "STIX Two Math", "Latin Modern Math", Georgia, serif',
      fontStyle: "italic",
      fontSize: size,
      display: display ? "block" : "inline-block",
      textAlign: display ? "center" : "left",
      width: display ? "100%" : "auto",
      lineHeight: 1.4,
      margin: display ? "0.04in 0" : 0,
      color: "var(--ae-text)",
    }}>{children}</span>
  );
}

// Fraction (numerator over denominator) — rendered with stacked divs
function Frac({ num, den, size = "0.14in" }) {
  return (
    <span style={{
      display: "inline-flex", flexDirection: "column", alignItems: "center",
      verticalAlign: "middle", margin: "0 0.03in", fontSize: size,
      fontFamily: '"Cambria Math", Georgia, serif', fontStyle: "italic",
      lineHeight: 1.05,
    }}>
      <span style={{ padding: "0 0.05in" }}>{num}</span>
      <span style={{
        height: 1.4, background: "var(--ae-text)",
        alignSelf: "stretch", marginTop: 1, marginBottom: 1,
      }} />
      <span style={{ padding: "0 0.05in" }}>{den}</span>
    </span>
  );
}

// Square root
function Sqrt({ children, size = "0.14in" }) {
  return (
    <span style={{
      fontSize: size, fontFamily: '"Cambria Math", Georgia, serif',
      fontStyle: "italic", display: "inline-block",
    }}>
      <span style={{ fontStyle: "normal" }}>√</span>
      <span style={{
        borderTop: "1.4px solid currentColor", paddingLeft: "0.02in", paddingRight: "0.02in",
      }}>{children}</span>
    </span>
  );
}

// Power
function Pow({ base, exp, size = "0.14in" }) {
  return (
    <span style={{
      fontSize: size, fontFamily: '"Cambria Math", Georgia, serif',
      fontStyle: "italic",
    }}>
      {base}
      <sup style={{ fontSize: "0.65em", marginLeft: 1 }}>{exp}</sup>
    </span>
  );
}

/* ────────────────────────────────────────────────
   StepBlock — aligned calculation steps
   « = 3x + 12 — 5 »  with leading "=" indented
   ──────────────────────────────────────────────── */
function StepBlock({ steps = [], hint, tone = "neutral" }) {
  const bg = tone === "cool" ? "var(--ae-primary-soft)" : "white";
  return (
    <div style={{
      border: "1px solid var(--ae-border)",
      background: bg,
      borderRadius: "0.06in",
      padding: "0.08in 0.12in",
      fontFamily: '"Cambria Math", Georgia, serif',
      fontStyle: "italic",
      fontSize: "0.135in",
      lineHeight: 1.55,
    }}>
      {steps.map((s, i) => (
        <div key={i} style={{
          display: "grid",
          gridTemplateColumns: "0.2in 1fr auto",
          alignItems: "baseline",
          gap: "0.06in",
        }}>
          <span style={{
            color: "var(--ae-text-soft)",
            fontStyle: "normal", fontFamily: "var(--ae-font-body)",
            fontSize: "0.1in", textAlign: "right",
          }}>{i === 0 ? "" : "="}</span>
          <span>{s.expr}</span>
          {s.note && <span style={{
            color: "var(--ae-primary-deep)",
            fontStyle: "normal",
            fontFamily: "var(--ae-font-body)",
            fontSize: "0.1in",
            background: "var(--ae-yellow)",
            padding: "0 0.06in", borderRadius: "0.04in",
          }}>{s.note}</span>}
        </div>
      ))}
      {hint && <div style={{
        marginTop: "0.06in",
        fontStyle: "normal", fontFamily: "var(--ae-font-body)",
        fontSize: "0.105in", color: "var(--ae-text-soft)",
        borderTop: "1px dashed var(--ae-border)", paddingTop: "0.05in",
      }}>{hint}</div>}
    </div>
  );
}

/* ────────────────────────────────────────────────
   GridCalc — grid of small calc cells
   ──────────────────────────────────────────────── */
function GridCalc({ items = [], cols = 3, withResult = true }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: `repeat(${cols}, 1fr)`,
      gap: "0.08in",
    }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display: "flex", alignItems: "center", gap: "0.08in",
          padding: "0.07in 0.1in", borderRadius: "0.06in",
          border: "1px solid var(--ae-border)", background: "white",
          fontFamily: '"Cambria Math", Georgia, serif',
          fontStyle: "italic", fontSize: "0.135in",
        }}>
          <span style={{
            display: "grid", placeItems: "center",
            width: "0.22in", height: "0.22in", borderRadius: "999px",
            background: "var(--ae-primary-soft)",
            color: "var(--ae-primary-deep)",
            fontFamily: "var(--ae-font-title)", fontStyle: "normal",
            fontWeight: 600, fontSize: "0.1in", flex: "0 0 auto",
          }}>{i + 1}</span>
          <span style={{ flex: 1 }}>{it} {withResult && <span style={{ color: "var(--ae-text-soft)" }}>= </span>}</span>
          {withResult && <span style={{
            display: "inline-block",
            minWidth: "0.7in", height: "0.22in",
            borderBottom: "1.5px solid var(--ae-text-soft)",
          }} />}
        </div>
      ))}
    </div>
  );
}

/* ────────────────────────────────────────────────
   QCMRow — single MCQ question with A/B/C
   ──────────────────────────────────────────────── */
function QCMRow({ n, q, options = [] }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "0.22in 1fr",
      gap: "0.08in", alignItems: "start",
      padding: "0.08in 0", borderBottom: "1px dashed var(--ae-border)",
    }}>
      <span style={{
        display: "grid", placeItems: "center",
        width: "0.22in", height: "0.22in", borderRadius: "999px",
        background: "var(--ae-primary)", color: "white",
        fontFamily: "var(--ae-font-title)", fontWeight: 600, fontSize: "0.11in",
      }}>{n}</span>
      <div>
        <div style={{ fontSize: "var(--ae-fs-body)", lineHeight: 1.4, marginBottom: "0.06in" }}>{q}</div>
        <div style={{ display: "flex", gap: "0.12in", flexWrap: "wrap" }}>
          {options.map((opt, i) => (
            <span key={i} style={{
              display: "inline-flex", alignItems: "center", gap: "0.05in",
              fontSize: "var(--ae-fs-body)",
            }}>
              <span style={{
                display: "inline-grid", placeItems: "center",
                width: "0.2in", height: "0.2in", borderRadius: "0.04in",
                border: "1.4px solid var(--ae-text-soft)",
                fontFamily: "var(--ae-font-title)", fontWeight: 600, fontSize: "0.1in",
                color: "var(--ae-text-soft)",
              }}>{String.fromCharCode(65 + i)}</span>
              <span>{opt}</span>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────
   ProportionalityTable — 2-row table with coefficient
   ──────────────────────────────────────────────── */
function ProportionalityTable({ headers = ["Quantité", "Prix"], cols = [], coef }) {
  return (
    <div>
      <div style={{
        display: "grid",
        gridTemplateColumns: `1.1in repeat(${cols.length}, 1fr)`,
        border: "1.5px solid var(--ae-text)",
        borderRadius: "0.06in",
        overflow: "hidden",
        fontFamily: '"Cambria Math", Georgia, serif',
        fontSize: "0.13in",
        background: "white",
      }}>
        {/* header row */}
        <div style={{ ...propCellHead, background: "var(--ae-primary-soft)" }}>{headers[0]}</div>
        {cols.map((c, i) => (
          <div key={i} style={{ ...propCellHead, borderLeft: "1px solid var(--ae-text-soft)" }}>{c.x ?? "…"}</div>
        ))}
        {/* second row */}
        <div style={{ ...propCellHead, background: "var(--ae-primary-soft)", borderTop: "1px solid var(--ae-text-soft)" }}>{headers[1]}</div>
        {cols.map((c, i) => (
          <div key={i} style={{ ...propCell, borderLeft: "1px solid var(--ae-text-soft)", borderTop: "1px solid var(--ae-text-soft)" }}>{c.y ?? <AnswerLine width="0.6in" />}</div>
        ))}
      </div>
      {coef !== undefined && (
        <div style={{ marginTop: "0.06in", fontSize: "var(--ae-fs-body)" }}>
          Coefficient de proportionnalité : <b>×&nbsp;{coef === null ? <AnswerLine width="0.5in" /> : coef}</b>
        </div>
      )}
    </div>
  );
}
const propCellHead = {
  padding: "0.07in 0.1in",
  fontFamily: "var(--ae-font-title)", fontWeight: 600,
  textAlign: "center", color: "var(--ae-primary-deep)", fontStyle: "normal",
};
const propCell = {
  padding: "0.08in 0.1in", textAlign: "center",
  fontFamily: '"Cambria Math", Georgia, serif', fontStyle: "italic",
};

/* ────────────────────────────────────────────────
   AxisGrid — small repère orthonormé for fonctions
   ──────────────────────────────────────────────── */
function AxisGrid({ width = "2.6in", height = "2.2in", points = [], plotF, xMin = -3, xMax = 4, yMin = -2, yMax = 5 }) {
  const W = 260, H = 220;
  const px = x => 30 + ((x - xMin) / (xMax - xMin)) * (W - 40);
  const py = y => H - 25 - ((y - yMin) / (yMax - yMin)) * (H - 40);
  const xs = []; for (let x = xMin; x <= xMax; x++) xs.push(x);
  const ys = []; for (let y = yMin; y <= yMax; y++) ys.push(y);
  let path = "";
  if (plotF) {
    const N = 80;
    for (let i = 0; i <= N; i++) {
      const x = xMin + (i / N) * (xMax - xMin);
      const y = plotF(x);
      const cmd = i === 0 ? "M" : "L";
      path += `${cmd}${px(x).toFixed(1)},${py(y).toFixed(1)} `;
    }
  }
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width={width} height={height} style={{ background: "white", border: "1px solid var(--ae-border)", borderRadius: "0.06in" }}>
      {/* gridlines */}
      {xs.map(x => <line key={"vx" + x} x1={px(x)} y1={py(yMin)} x2={px(x)} y2={py(yMax)} stroke="#E7ECF5" strokeWidth="1" />)}
      {ys.map(y => <line key={"hy" + y} x1={px(xMin)} y1={py(y)} x2={px(xMax)} y2={py(y)} stroke="#E7ECF5" strokeWidth="1" />)}
      {/* axes */}
      <line x1={px(xMin)} y1={py(0)} x2={px(xMax)} y2={py(0)} stroke="#0F1A3D" strokeWidth="1.4" />
      <line x1={px(0)} y1={py(yMin)} x2={px(0)} y2={py(yMax)} stroke="#0F1A3D" strokeWidth="1.4" />
      {/* arrows */}
      <polygon points={`${px(xMax)},${py(0)} ${px(xMax)-7},${py(0)-4} ${px(xMax)-7},${py(0)+4}`} fill="#0F1A3D" />
      <polygon points={`${px(0)},${py(yMax)} ${px(0)-4},${py(yMax)+7} ${px(0)+4},${py(yMax)+7}`} fill="#0F1A3D" />
      {/* tick labels */}
      {xs.filter(x => x !== 0).map(x => <text key={"xl" + x} x={px(x)} y={py(0) + 14} textAnchor="middle" fontSize="11" fill="#5b6478" fontFamily="Georgia, serif" fontStyle="italic">{x}</text>)}
      {ys.filter(y => y !== 0).map(y => <text key={"yl" + y} x={px(0) - 8} y={py(y) + 4} textAnchor="end" fontSize="11" fill="#5b6478" fontFamily="Georgia, serif" fontStyle="italic">{y}</text>)}
      <text x={px(xMax) - 4} y={py(0) - 6} textAnchor="end" fontSize="12" fill="#0F1A3D" fontFamily="Georgia, serif" fontStyle="italic">x</text>
      <text x={px(0) + 8} y={py(yMax) + 14} fontSize="12" fill="#0F1A3D" fontFamily="Georgia, serif" fontStyle="italic">y</text>
      {/* curve */}
      {path && <path d={path} fill="none" stroke="var(--ae-primary)" strokeWidth="2" />}
      {/* points */}
      {points.map((p, i) => (
        <g key={i}>
          <circle cx={px(p.x)} cy={py(p.y)} r="3.2" fill="var(--ae-orange)" stroke="white" strokeWidth="1.5" />
          {p.label && <text x={px(p.x) + 6} y={py(p.y) - 6} fontSize="11" fill="var(--ae-orange)" fontFamily="var(--ae-font-title)" fontWeight="600">{p.label}</text>}
        </g>
      ))}
    </svg>
  );
}

/* ────────────────────────────────────────────────
   BarChart — small vertical bar chart for stats
   ──────────────────────────────────────────────── */
function BarChart({ data = [], width = "2.8in", height = "1.8in", yMax }) {
  const W = 280, H = 180;
  const max = yMax ?? Math.max(...data.map(d => d.v));
  const bw = (W - 40) / data.length;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width={width} height={height} style={{ background: "white", border: "1px solid var(--ae-border)", borderRadius: "0.06in" }}>
      <line x1="30" y1={H - 25} x2={W - 6} y2={H - 25} stroke="#0F1A3D" strokeWidth="1.4" />
      <line x1="30" y1="10" x2="30" y2={H - 25} stroke="#0F1A3D" strokeWidth="1.4" />
      {[0.25, 0.5, 0.75, 1].map((f, i) => (
        <MB_F key={i}>
          <line x1="30" y1={(H - 25) - (H - 40) * f} x2={W - 6} y2={(H - 25) - (H - 40) * f} stroke="#E7ECF5" strokeWidth="1" />
          <text x="26" y={(H - 25) - (H - 40) * f + 4} fontSize="10" fill="#5b6478" textAnchor="end" fontFamily="Georgia, serif" fontStyle="italic">{Math.round(max * f)}</text>
        </MB_F>
      ))}
      {data.map((d, i) => {
        const h = (d.v / max) * (H - 40);
        return (
          <MB_F key={i}>
            <rect x={30 + i * bw + 6} y={(H - 25) - h} width={bw - 12} height={h} fill="var(--ae-primary)" rx="2" />
            <text x={30 + i * bw + bw / 2} y={H - 8} fontSize="10" fill="#0F1A3D" textAnchor="middle" fontFamily="Inter, sans-serif">{d.label}</text>
            <text x={30 + i * bw + bw / 2} y={(H - 25) - h - 4} fontSize="10" fill="#0F1A3D" textAnchor="middle" fontFamily="Inter, sans-serif" fontWeight="600">{d.v}</text>
          </MB_F>
        );
      })}
    </svg>
  );
}

/* ────────────────────────────────────────────────
   TriangleFigure — generic SVG for Pythagore/Thalès/Trigo
   variant: "pythagoras" | "pythagoras-converse" | "thales" | "trigonometry"
   ──────────────────────────────────────────────── */
function TriangleFigure({ variant = "pythagoras", labels = {}, width = "2.8in", height = "2in" }) {
  const W = 280, H = 200;
  // Standard right triangle, right angle at C (bottom-left)
  const A = { x: 50, y: 30 };
  const B = { x: 240, y: 160 };
  const C = { x: 50, y: 160 };

  const RightAngleSquare = ({ at, dir = "br" }) => {
    const s = 12;
    const dx = dir.includes("r") ? s : -s;
    const dy = dir.includes("b") ? -s : s;
    return <polyline points={`${at.x + dx},${at.y} ${at.x + dx},${at.y + dy} ${at.x},${at.y + dy}`} fill="none" stroke="#0F1A3D" strokeWidth="1.4" />;
  };

  if (variant === "thales") {
    // Two intersecting lines crossed by parallels — Thalès classic
    const O = { x: 50, y: 175 };
    const M = { x: 130, y: 100 };
    const A2 = { x: 220, y: 25 };
    const N = { x: 175, y: 145 };
    const B2 = { x: 260, y: 130 };
    return (
      <svg viewBox={`0 0 ${W} ${H}`} width={width} height={height} style={{ background: "white", border: "1px solid var(--ae-border)", borderRadius: "0.06in" }}>
        <line x1={O.x} y1={O.y} x2={A2.x} y2={A2.y} stroke="#0F1A3D" strokeWidth="1.6" />
        <line x1={O.x} y1={O.y} x2={B2.x} y2={B2.y} stroke="#0F1A3D" strokeWidth="1.6" />
        <line x1={M.x} y1={M.y} x2={N.x} y2={N.y} stroke="var(--ae-primary)" strokeWidth="1.8" />
        <line x1={A2.x} y1={A2.y} x2={B2.x} y2={B2.y} stroke="var(--ae-primary)" strokeWidth="1.8" />
        {[[O,"O"],[M,"M"],[N,"N"],[A2,"A"],[B2,"B"]].map(([p,l],i) => (
          <MB_F key={i}>
            <circle cx={p.x} cy={p.y} r="3" fill="#0F1A3D" />
            <text x={p.x + 6} y={p.y - 6} fontSize="13" fill="#0F1A3D" fontFamily="Georgia, serif" fontWeight="600">{l}</text>
          </MB_F>
        ))}
      </svg>
    );
  }

  // Right triangle figure — used for Pythagore, converse, trigo
  const isTri = variant === "trigonometry";
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width={width} height={height} style={{ background: "white", border: "1px solid var(--ae-border)", borderRadius: "0.06in" }}>
      {/* triangle */}
      <polygon points={`${A.x},${A.y} ${B.x},${B.y} ${C.x},${C.y}`} fill="var(--ae-primary-soft)" stroke="var(--ae-primary-deep)" strokeWidth="1.8" />
      <RightAngleSquare at={C} dir="tr" />
      {/* vertex labels */}
      <text x={A.x - 14} y={A.y + 4} fontSize="14" fontFamily="Georgia, serif" fontWeight="600">A</text>
      <text x={B.x + 6} y={B.y + 6} fontSize="14" fontFamily="Georgia, serif" fontWeight="600">B</text>
      <text x={C.x - 14} y={C.y + 14} fontSize="14" fontFamily="Georgia, serif" fontWeight="600">C</text>
      {/* side labels */}
      <text x={(A.x + B.x) / 2 + 6} y={(A.y + B.y) / 2 - 6} fontSize="12" fontStyle="italic" fontFamily="Georgia, serif" fill="var(--ae-orange)">{labels.AB ?? "?"}</text>
      <text x={(A.x + C.x) / 2 - 14} y={(A.y + C.y) / 2 + 4} fontSize="12" fontStyle="italic" fontFamily="Georgia, serif">{labels.AC ?? ""}</text>
      <text x={(B.x + C.x) / 2 - 4} y={(B.y + C.y) / 2 + 16} fontSize="12" fontStyle="italic" fontFamily="Georgia, serif">{labels.BC ?? ""}</text>
      {/* angle marker for trigo */}
      {isTri && (
        <MB_F>
          <path d={`M ${A.x + 16} ${A.y} A 16 16 0 0 1 ${A.x + 12} ${A.y + 11}`} fill="none" stroke="var(--ae-orange)" strokeWidth="1.6" />
          <text x={A.x + 22} y={A.y + 14} fontSize="12" fill="var(--ae-orange)" fontStyle="italic" fontFamily="Georgia, serif" fontWeight="600">{labels.angle ?? "α"}</text>
        </MB_F>
      )}
    </svg>
  );
}

/* ────────────────────────────────────────────────
   ScoreCells — score boxes for graded exercises
   ──────────────────────────────────────────────── */
function ScoreCells({ items = [] }) {
  return (
    <div style={{ display: "flex", gap: "0.06in", flexWrap: "wrap" }}>
      {items.map((it, i) => (
        <div key={i} style={{
          padding: "0.05in 0.1in", borderRadius: "0.05in",
          background: "white", border: "1px solid var(--ae-border)",
          fontSize: "0.105in",
          display: "flex", alignItems: "center", gap: "0.06in",
        }}>
          <span style={{ color: "var(--ae-text-soft)" }}>{it.label}</span>
          <span style={{
            display: "inline-block",
            width: "0.4in", borderBottom: "1.4px solid var(--ae-text)",
            textAlign: "center", fontFamily: "Georgia, serif", fontStyle: "italic",
          }}>{it.value ?? "\u00A0"}</span>
          <span style={{ color: "var(--ae-text-soft)" }}>/ {it.max}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  MathExpr, Frac, Sqrt, Pow,
  StepBlock, GridCalc, QCMRow,
  ProportionalityTable, AxisGrid, BarChart, TriangleFigure, ScoreCells,
});
