// ── Italian Mediterranean score — POC debug view ─────────────────────────────

function scoreColor(n) {
  if (n == null) return "#999";
  if (n >= 75) return "#1b7340";
  if (n >= 50) return "#85BB2F";
  if (n >= 25) return "#EE8100";
  return "#E63312";
}

const ADDITIVE_COLOR = {
  green: "#4caf50",
  yellow: "#fbc02d",
  orange: "#ff9800",
  red: "#e53935",
};

const CAP_REASON_LABEL = {
  red_additive: "Cap a 49 per additivo rosso",
  nutriscore_d_e: "Cap a 49 per Nutri-Score D/E",
  exempt_soften_d_e: "−10 pts (esente, non capped)",
};

function StatRow({ label, value, max, hint }) {
  return (
    <div className="flex items-baseline justify-between text-xs leading-5">
      <span className="text-gray-500">{label}</span>
      <span className="font-mono">
        <span className="font-semibold text-gray-800">
          {value == null ? "—" : value}
        </span>
        {max != null && <span className="text-gray-400">/{max}</span>}
        {hint && <span className="text-gray-400 ml-1">{hint}</span>}
      </span>
    </div>
  );
}

function PointsBar({ label, points, max }) {
  const pct = max > 0 ? (points / max) * 100 : 0;
  return (
    <div className="space-y-1">
      <div className="flex items-baseline justify-between text-xs">
        <span className="text-gray-600 font-semibold">{label}</span>
        <span className="font-mono text-gray-700">
          <span className="font-semibold">{points}</span>
          <span className="text-gray-400">/{max}</span>
        </span>
      </div>
      <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
        <div
          className="h-full rounded-full transition-all"
          style={{
            width: `${pct}%`,
            background: scoreColor((points / max) * 100),
          }}
        />
      </div>
    </div>
  );
}

function ScoreCard({ score }) {
  const [open, setOpen] = React.useState(false);
  if (!score) return null;

  const color = scoreColor(score.score);
  const n = score.nutrition;
  const p = score.processing;
  const q = score.quality;

  return (
    <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
      {/* Header: big score */}
      <div className="p-4 flex items-center gap-4">
        <div
          className="flex flex-col items-center justify-center w-20 h-20 rounded-full flex-shrink-0"
          style={{ background: color + "22", border: `3px solid ${color}` }}
        >
          <span className="text-3xl font-black leading-none" style={{ color }}>
            {score.score}
          </span>
          <span
            className="text-xs font-semibold leading-none"
            style={{ color }}
          >
            /100
          </span>
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-lg font-bold" style={{ color }}>
            {score.label_it}
          </div>
          <div className="text-xs text-gray-400 mt-0.5">
            Italian Mediterranean Score
          </div>
          <div className="flex gap-1.5 mt-1.5 flex-wrap">
            {score.nutri_grade && (
              <span className="px-1.5 py-0.5 text-[10px] font-bold text-white rounded bg-gray-600">
                Nutri {score.nutri_grade}
              </span>
            )}
            {score.is_exempt && (
              <span className="px-1.5 py-0.5 text-[10px] font-bold text-white rounded bg-emerald-600">
                Mediterraneo
              </span>
            )}
            {score.cap_reason && (
              <span className="px-1.5 py-0.5 text-[10px] font-bold text-white rounded bg-red-600">
                {CAP_REASON_LABEL[score.cap_reason] || score.cap_reason}
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Component bars */}
      <div className="px-4 pb-3 space-y-2">
        <PointsBar label="Nutrizione" points={n.points} max={50} />
        <PointsBar label="Additivi & Processing" points={p.points} max={30} />
        <PointsBar label="Qualità & Origine" points={q.points} max={20} />
        {score.raw_total !== score.score && (
          <div className="text-[11px] text-gray-400 text-right font-mono pt-1">
            raw {score.raw_total} → {score.score}
          </div>
        )}
      </div>

      {/* Expandable debug breakdown */}
      <button
        onClick={() => setOpen((o) => !o)}
        className="w-full px-4 py-2 text-xs font-semibold text-gray-500 border-t border-gray-100 flex items-center justify-between active:bg-gray-50"
      >
        <span>Dettagli debug</span>
        <span className="text-gray-400">{open ? "▴" : "▾"}</span>
      </button>

      {open && (
        <div className="px-4 pb-4 pt-2 border-t border-gray-100 space-y-4 text-xs">
          {/* ── Nutrition ── */}
          <section>
            <div className="font-bold text-gray-700 uppercase tracking-wider text-[11px] mb-1.5">
              Nutrizione · {n.points}/50 · variante{" "}
              <span className="font-mono text-gray-500">{n.variant}</span>
            </div>

            <div className="bg-gray-50 rounded-lg p-2 space-y-0.5">
              <div className="text-[10px] font-bold text-gray-400 uppercase mb-0.5">
                Input (per 100g/ml)
              </div>
              <StatRow label="Energia" value={n.inputs.energy_kj} hint="kJ" />
              <StatRow label="Grassi" value={n.inputs.fat_g} hint="g" />
              <StatRow
                label="Grassi saturi"
                value={n.inputs.sat_fat_g}
                hint="g"
              />
              {n.inputs.sat_fat_ratio_pct != null && (
                <StatRow
                  label="Rapporto saturi/grassi"
                  value={n.inputs.sat_fat_ratio_pct}
                  hint="%"
                />
              )}
              <StatRow label="Zuccheri" value={n.inputs.sugars_g} hint="g" />
              <StatRow label="Sodio" value={n.inputs.sodium_mg} hint="mg" />
              <StatRow label="Fibre" value={n.inputs.fiber_g} hint="g" />
              <StatRow label="Proteine" value={n.inputs.proteins_g} hint="g" />
              <StatRow
                label="Frutta/verd/nocc"
                value={n.inputs.fvn_pct}
                hint="%"
              />
            </div>

            <div className="mt-1.5 grid grid-cols-2 gap-1.5">
              <div className="bg-red-50 rounded-lg p-2 space-y-0.5">
                <div className="text-[10px] font-bold text-red-400 uppercase mb-0.5">
                  Negativi
                </div>
                <StatRow
                  label="Energia"
                  value={n.negative_pts.energy}
                  max={10}
                />
                <StatRow
                  label="Sat. fat"
                  value={n.negative_pts.sat_fat}
                  max={10}
                />
                <StatRow
                  label="Zuccheri"
                  value={n.negative_pts.sugars}
                  max={10}
                />
                <StatRow label="Sodio" value={n.negative_pts.sodium} max={10} />
                <div className="border-t border-red-100 mt-1 pt-1">
                  <StatRow
                    label="Totale"
                    value={n.negative_pts.total}
                    max={40}
                  />
                </div>
              </div>
              <div className="bg-green-50 rounded-lg p-2 space-y-0.5">
                <div className="text-[10px] font-bold text-green-600 uppercase mb-0.5">
                  Positivi
                </div>
                <StatRow label="Fibre" value={n.positive_pts.fiber} max={5} />
                <StatRow
                  label="Proteine"
                  value={n.positive_pts.protein}
                  max={5}
                  hint={n.positive_pts.protein_excluded ? "(esclusa)" : ""}
                />
                <StatRow
                  label="FVN"
                  value={n.positive_pts.fruit_veg_nuts}
                  max={n.variant === "beverages" ? 10 : 5}
                />
                <div className="border-t border-green-100 mt-1 pt-1">
                  <StatRow
                    label="Totale"
                    value={n.positive_pts.total}
                    max={20}
                  />
                </div>
              </div>
            </div>

            <div className="mt-1.5 bg-gray-50 rounded-lg p-2 flex justify-between text-xs">
              <span className="text-gray-500">
                N (neg − pos, range −15..40)
              </span>
              <span className="font-mono font-bold">{n.n_score}</span>
            </div>
          </section>

          {/* ── Processing ── */}
          <section>
            <div className="font-bold text-gray-700 uppercase tracking-wider text-[11px] mb-1.5">
              Additivi & Processing · {p.points}/30
            </div>

            <div className="bg-gray-50 rounded-lg p-2 space-y-1">
              <div className="flex items-baseline justify-between">
                <span className="text-gray-500">
                  Additivi ({p.additives.length})
                </span>
                <span className="font-mono font-semibold">
                  {p.additive_pts}/20
                </span>
              </div>
              {p.additives.length > 0 ? (
                <div className="flex flex-wrap gap-1">
                  {p.additives.map((a, i) => (
                    <span
                      key={i}
                      className="px-1.5 py-0.5 text-[10px] font-mono font-bold text-white rounded"
                      style={{ background: ADDITIVE_COLOR[a.level] }}
                      title={a.level}
                    >
                      {a.tag.replace("en:", "").toUpperCase()}
                    </span>
                  ))}
                </div>
              ) : (
                <div className="text-[10px] text-gray-400 italic">nessuno</div>
              )}
              <div className="text-[10px] text-gray-400 pt-1">
                yellow −{p.yellow_penalty} · orange −{p.orange_penalty}
                {p.has_red && " · red (cap 49)"}
              </div>
            </div>

            <div className="mt-1.5 grid grid-cols-2 gap-1.5">
              <div className="bg-gray-50 rounded-lg p-2">
                <StatRow
                  label={`NOVA ${p.nova ?? "?"}`}
                  value={p.nova_pts}
                  max={10}
                />
              </div>
              <div className="bg-gray-50 rounded-lg p-2">
                <StatRow
                  label="Palm oil"
                  value={p.palm_oil ? `−${p.palm_penalty}` : "no"}
                />
              </div>
            </div>
          </section>

          {/* ── Quality ── */}
          <section>
            <div className="font-bold text-gray-700 uppercase tracking-wider text-[11px] mb-1.5">
              Qualità & Origine · {q.points}/20
            </div>
            <div className="bg-gray-50 rounded-lg p-2 space-y-1">
              {q.granted.length === 0 && (
                <div className="text-[10px] text-gray-400 italic">
                  nessun bonus
                </div>
              )}
              {q.granted.map((g, i) => (
                <div
                  key={i}
                  className="flex items-center justify-between text-xs"
                >
                  <span className="text-gray-700">{g.name}</span>
                  <span className="font-mono text-emerald-700 font-semibold">
                    +{g.bonus}
                  </span>
                </div>
              ))}
            </div>
          </section>

          {/* ── Final math ── */}
          <section className="bg-gray-900 text-gray-100 rounded-lg p-2.5 font-mono text-[11px] space-y-0.5">
            <div className="flex justify-between">
              <span className="text-gray-400">nutrition</span>
              <span>{n.points}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">+ processing</span>
              <span>{p.points}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">+ quality</span>
              <span>{q.points}</span>
            </div>
            <div className="flex justify-between border-t border-gray-700 pt-1 mt-1">
              <span className="text-gray-400">= raw total</span>
              <span>{score.raw_total}</span>
            </div>
            {score.cap_reason && (
              <div className="flex justify-between text-yellow-400">
                <span>{score.cap_reason}</span>
                <span>→</span>
              </div>
            )}
            <div className="flex justify-between text-base font-bold pt-1">
              <span>final</span>
              <span>{score.score}</span>
            </div>
          </section>
        </div>
      )}
    </div>
  );
}
