const NUTRISCORE_DESC = {
  A: "Qualità nutrizionale eccellente",
  B: "Buona qualità nutrizionale",
  C: "Qualità nutrizionale nella media",
  D: "Scarsa qualità nutrizionale",
  E: "Cattiva qualità nutrizionale",
};
const ECOSCORE_DESC = {
  A: "Impatto ambientale molto basso",
  B: "Impatto ambientale basso",
  C: "Impatto ambientale moderato",
  D: "Impatto ambientale alto",
  E: "Impatto ambientale molto alto",
};
const NOVA_DESC = {
  1: "Alimenti non trasformati o minimamente trasformati",
  2: "Ingredienti culinari trasformati",
  3: "Alimenti trasformati",
  4: "Alimenti ultra-trasformati",
};

function ScoreScale({ grade, scale, colorFn, label, subtitle, descriptions }) {
  grade = !grade || grade.toLowerCase() === "unknown" ? null : grade;
  if (!grade) return null;
  return (
    <div className="min-w-[100px]">
      <div className="text-xs font-bold text-gray-500 uppercase tracking-wide mb-0.5">
        {label}
      </div>
      <div className="text-xs text-gray-400 mb-2">{subtitle}</div>
      <div className="flex gap-1 mb-2">
        {scale.map((s) => {
          const active = s === grade;
          return (
            <div
              key={s}
              className="w-7 h-7 rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold"
              style={{
                background: active ? colorFn(s) : "#e8e8e8",
                color: active ? "#fff" : "#bbb",
                boxShadow: active ? `0 2px 6px ${colorFn(s)}66` : "none",
                outline: active ? `2px solid ${colorFn(s)}` : "none",
                outlineOffset: "2px",
                transform: active ? "scale(1.15)" : "none",
              }}
            >
              {s}
            </div>
          );
        })}
      </div>
      {grade && descriptions?.[grade] ? (
        <div className="text-xs text-gray-500 leading-snug">
          {descriptions[grade]}
        </div>
      ) : (
        <div className="text-xs text-gray-300">Nessun dato</div>
      )}
    </div>
  );
}

function NutritionPanel({ match }) {
  if (!match)
    return (
      <div className="p-4 text-sm text-gray-400 text-center">
        Nessun prodotto collegato — premi "Trova abbinamento" per cercare su
        OpenFoodFacts.
      </div>
    );

  const isWeighted = match.is_weighted;
  const link = match.off_found
    ? `https://world.openfoodfacts.org/product/${match.barcode}`
    : null;
  const novaGrade = match.nova_group != null ? String(match.nova_group) : null;
  const levels = match.nutrient_levels || {};

  const nutrients = [
    [
      "Energia",
      match.energy_kcal != null
        ? `${Math.round(match.energy_kcal)} kcal`
        : null,
      null,
    ],
    [
      "Carboidrati",
      match.carbohydrates != null ? `${fmt(match.carbohydrates)} g` : null,
      null,
    ],
    [
      "· Zuccheri",
      match.sugars != null ? `${fmt(match.sugars)} g` : null,
      levels.sugars,
    ],
    ["Grassi", match.fat != null ? `${fmt(match.fat)} g` : null, levels.fat],
    [
      "· Grassi saturi",
      match.saturated_fat != null ? `${fmt(match.saturated_fat)} g` : null,
      levels.saturated_fat,
    ],
    ["Fibre", match.fiber != null ? `${fmt(match.fiber)} g` : null, null],
    [
      "Proteine",
      match.proteins != null ? `${fmt(match.proteins)} g` : null,
      null,
    ],
    ["Sale", match.salt != null ? `${fmt(match.salt)} g` : null, levels.salt],
  ].filter(([, v]) => v != null);

  const allergens = match.allergens || [];
  const traces = match.traces || [];
  const packaging = match.packaging || [];
  const additives = match.additives || [];

  return (
    <div className="p-4 bg-gray-50 border-t border-gray-100">
      {/* Product identity */}
      <div className="flex gap-3 items-start">
        <div className="min-w-0 space-y-3">
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
            <div>
              <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                Nome prodotto
              </div>
              <div className="font-semibold text-sm text-[#2d7a3a] leading-tight">
                {match.product_name || "—"}
              </div>
            </div>
            {match.brands && (
              <div>
                <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                  Marca
                </div>
                <div className="text-xs text-gray-600 font-medium">
                  {match.brands}
                </div>
              </div>
            )}
            {match.quantity && (
              <div>
                <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                  Quantità
                </div>
                <div className="text-xs text-gray-600 font-medium">
                  {match.quantity}
                </div>
              </div>
            )}
            {match.barcode && (
              <div>
                <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                  {isWeighted ? "Articolo a peso" : "Codice a barre"}
                </div>
                <div className="text-xs text-gray-500 font-mono">
                  {isWeighted
                    ? `indice articolo ${match.barcode}`
                    : match.barcode}
                </div>
              </div>
            )}
            {link && (
              <div>
                <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                  Fonte
                </div>
                <div>
                  <a
                    href={link}
                    target="_blank"
                    className="text-xs text-blue-500 hover:text-[#2d7a3a] underline whitespace-nowrap"
                  >
                    Open Food Facts ↗
                  </a>
                </div>
              </div>
            )}
          </div>

          {match.categories?.length > 0 && (
            <div>
              <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold mb-1.5">
                Categorie
              </div>
              <div className="flex items-center flex-wrap gap-x-1 gap-y-1">
                {match.categories.map((cat, i) => (
                  <React.Fragment key={cat}>
                    {i > 0 && (
                      <span className="text-[10px] text-gray-300 select-none">
                        ›
                      </span>
                    )}
                    <span className="px-1.5 py-0.5 rounded text-[10px] bg-gray-100 text-gray-600 font-medium">
                      {cat}
                    </span>
                  </React.Fragment>
                ))}
              </div>
            </div>
          )}

          {match.suggested_from && (
            <div className="flex items-center gap-2">
              <span className="text-[10px] text-gray-400 uppercase tracking-wider font-bold">
                Tipo abbinamento:
              </span>
              <span className="inline-block px-2 py-0.5 rounded text-[10px] font-bold bg-purple-100 text-purple-700">
                SUGGERITO DA {match.suggested_from.toUpperCase()}
              </span>
            </div>
          )}

          {(match.vegan ||
            match.vegetarian ||
            match.palm_oil ||
            match.additives_n != null) && (
            <div>
              <div className="text-[10px] text-gray-400 uppercase tracking-wider font-bold mb-1.5">
                Dieta e lavorazione
              </div>
              <div className="flex gap-1.5 flex-wrap">
                <StatusPill
                  value={match.vegan}
                  yesLabel="Vegano"
                  noLabel="Non vegano"
                />
                <StatusPill
                  value={match.vegetarian}
                  yesLabel="Vegetariano"
                  noLabel="Non vegetariano"
                />
                <StatusPill
                  value={match.palm_oil}
                  yesLabel="Senza olio di palma"
                  noLabel="Olio di palma"
                  yesColor="#388e3c"
                  noColor="#f57c00"
                />
                {match.additives_n === 0 && (
                  <span className="px-2 py-0.5 rounded text-[10px] font-bold text-white bg-green-500">
                    SENZA ADDITIVI
                  </span>
                )}
                {match.additives_n > 0 && (
                  <span className="px-2 py-0.5 rounded text-[10px] font-bold text-white bg-orange-400">
                    {match.additives_n}{" "}
                    {match.additives_n > 1 ? "ADDITIVI" : "ADDITIVO"}
                  </span>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Score scales */}
      <div className="mt-4 flex gap-6 flex-wrap">
        <ScoreScale
          grade={match.nutriscore_grade}
          scale={["A", "B", "C", "D", "E"]}
          colorFn={nutriscoreColor}
          label="Nutriscore"
          subtitle="Nutrizione"
          descriptions={NUTRISCORE_DESC}
        />
        <ScoreScale
          grade={novaGrade}
          scale={["1", "2", "3", "4"]}
          colorFn={(g) => novaColor(parseInt(g))}
          label="NOVA"
          subtitle="Lavorazione"
          descriptions={NOVA_DESC}
        />
      </div>

      {/* Nutrients */}
      {nutrients.length > 0 && (
        <PanelSection title="Nutrienti per 100 g">
          <div className="grid grid-cols-2 gap-x-4 gap-y-1">
            {nutrients.map(([label, value, level]) => {
              const sub = label.startsWith("·");
              return (
                <div
                  key={label}
                  className="flex items-center justify-between col-span-1"
                >
                  <span
                    className={`text-xs ${sub ? "text-gray-400 pl-3" : "text-gray-600"}`}
                  >
                    {sub ? label.slice(1).trim() : label}
                  </span>
                  <span className="text-xs font-medium text-gray-800 flex items-center gap-0.5">
                    <LevelPill level={level} />
                    {value}
                  </span>
                </div>
              );
            })}
          </div>
        </PanelSection>
      )}

      {/* Allergens */}
      {(allergens.length > 0 || traces.length > 0) && (
        <PanelSection title="Allergeni">
          {allergens.length > 0 && (
            <div className="flex gap-1.5 flex-wrap mb-1">
              {allergens.map((a) => (
                <span
                  key={a}
                  className="px-2 py-0.5 rounded text-xs font-semibold bg-red-100 text-red-700"
                >
                  {a}
                </span>
              ))}
            </div>
          )}
          {traces.length > 0 && (
            <div className="text-xs text-gray-400">
              Può contenere: {traces.join(", ")}
            </div>
          )}
        </PanelSection>
      )}

      {/* Ingredients */}
      {match.ingredients_text && (
        <PanelSection title="Ingredienti">
          <p className="text-xs text-gray-500 leading-relaxed">
            {match.ingredients_text}
          </p>
        </PanelSection>
      )}

      {/* Additives */}
      {additives.length > 0 && (
        <PanelSection title={`Additivi (${match.additives_n})`}>
          <div className="flex gap-1.5 flex-wrap">
            {additives.map((a) => (
              <span
                key={a}
                className="px-1.5 py-0.5 rounded text-xs font-semibold bg-orange-50 text-orange-700"
              >
                {a}
              </span>
            ))}
          </div>
        </PanelSection>
      )}

      {/* Packaging */}
      {packaging.length > 0 && (
        <PanelSection title="Imballaggio">
          <div className="flex gap-1.5 flex-wrap">
            {packaging.map((p) => (
              <span
                key={p}
                className="px-1.5 py-0.5 rounded text-xs bg-green-50 text-green-700"
              >
                {p}
              </span>
            ))}
          </div>
        </PanelSection>
      )}

      {/* Origin & Manufacturing */}
      {(match.origin || match.manufacturing_places) && (
        <PanelSection title="Origine">
          <div className="grid grid-cols-1 gap-1">
            {match.origin && (
              <div className="flex gap-2 text-xs">
                <span className="text-gray-400 min-w-[110px]">
                  Origine ingredienti:
                </span>
                <span className="text-gray-600">{match.origin}</span>
              </div>
            )}
            {match.manufacturing_places && (
              <div className="flex gap-2 text-xs">
                <span className="text-gray-400 min-w-[110px]">
                  Prodotto in:
                </span>
                <span className="text-gray-600">
                  {match.manufacturing_places}
                </span>
              </div>
            )}
          </div>
        </PanelSection>
      )}

      <BarcodeBlock code={match.barcode} isWeighted={match.is_weighted} />
    </div>
  );
}
