function ItemDetailsPage({ initialBarcode = "" }) {
  const [input, setInput] = React.useState(initialBarcode);
  const [barcode, setBarcode] = React.useState(initialBarcode);
  const [product, setProduct] = React.useState(null);
  const [similar, setSimilar] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [loadingSimilar, setLoadingSimilar] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [scanning, setScanning] = React.useState(false);
  const [debugProduct, setDebugProduct] = React.useState(null);
  const videoRef = React.useRef(null);
  const readerRef = React.useRef(null);

  React.useEffect(() => {
    if (debugProduct) {
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = "";
      };
    }
  }, [debugProduct]);

  function openDebug() {
    setDebugProduct(product._raw || product);
  }

  // Fetch product whenever barcode changes
  React.useEffect(() => {
    if (!barcode) return;
    window.location.hash = `#/item/${barcode}`;
    setProduct(null);
    setSimilar([]);
    setError(null);
    setLoading(true);
    fetch(`/api/search-off?barcode=${encodeURIComponent(barcode)}`)
      .then((r) => r.json())
      .then((d) => {
        const hit = d.results?.[0];
        if (hit) {
          setProduct({ ...hit, off_found: true, _raw: d.raw || null });
        } else {
          setError("Prodotto non trovato su OpenFoodFacts.");
        }
      })
      .catch(() => setError("Errore di rete."))
      .finally(() => setLoading(false));
  }, [barcode]);

  // Fetch similar products after product loads
  React.useEffect(() => {
    const bc = product?.barcode;
    if (!bc) return;
    setLoadingSimilar(true);
    fetch(`/api/similar/${encodeURIComponent(bc)}`)
      .then((r) => r.json())
      .then((d) => setSimilar(d.results || []))
      .catch(() => {})
      .finally(() => setLoadingSimilar(false));
  }, [product?.barcode]);

  // Start/stop camera with ZXing
  React.useEffect(() => {
    if (!scanning) return;
    if (!videoRef.current) return;
    const reader = new ZXing.BrowserMultiFormatReader();
    readerRef.current = reader;
    reader
      .decodeFromVideoDevice(undefined, videoRef.current, (result) => {
        if (!result) return;
        const text = result.getText();
        reader.reset();
        readerRef.current = null;
        setScanning(false);
        setInput(text);
        setBarcode(text);
      })
      .catch(() => setScanning(false));
    return () => {
      reader.reset();
      readerRef.current = null;
    };
  }, [scanning]);

  function stopScan() {
    readerRef.current?.reset();
    readerRef.current = null;
    setScanning(false);
  }

  function handleSubmit(e) {
    e.preventDefault();
    const cleaned = input.trim();
    if (cleaned) setBarcode(cleaned);
  }

  function loadProduct(p) {
    setInput(p.barcode);
    setBarcode(p.barcode);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  return (
    <div className="space-y-4">
      {/* ── Barcode input ─────────────────────────────────────────── */}
      <div className="bg-white rounded-2xl shadow-sm p-4 space-y-3">
        <form onSubmit={handleSubmit} className="flex gap-2">
          <input
            type="text"
            inputMode="numeric"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Codice a barre…"
            className="flex-1 px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#2d7a3a]/30 focus:border-[#2d7a3a]"
          />
          <button
            type="submit"
            disabled={!input.trim()}
            className="px-4 py-2 bg-[#2d7a3a] text-white text-sm font-semibold rounded-lg active:bg-[#236130] disabled:opacity-40"
          >
            Cerca
          </button>
          <button
            type="button"
            onClick={scanning ? stopScan : () => setScanning(true)}
            className={`px-3 py-2 border rounded-lg text-base leading-none transition-colors ${
              scanning
                ? "bg-red-50 border-red-200 text-red-600"
                : "border-gray-200 text-gray-600 active:bg-gray-50"
            }`}
            title={
              scanning ? "Interrompi scansione" : "Scansiona con fotocamera"
            }
          >
            {scanning ? "✕" : "📷"}
          </button>
        </form>

        {/* Camera viewfinder */}
        {scanning && (
          <div className="relative rounded-xl overflow-hidden bg-black">
            <video
              ref={videoRef}
              className="w-full"
              style={{ maxHeight: 260 }}
              playsInline
              muted
            />
            {/* Targeting overlay */}
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
              <div
                className="border-2 border-white/70 rounded-lg"
                style={{ width: 220, height: 90 }}
              />
            </div>
            <div className="absolute bottom-2 inset-x-0 text-center text-white/70 text-xs">
              Inquadra il codice a barre
            </div>
          </div>
        )}
      </div>

      {/* ── Loading ───────────────────────────────────────────────── */}
      {loading && (
        <div className="flex justify-center py-10">
          <div className="w-6 h-6 border-2 border-[#2d7a3a] border-t-transparent rounded-full animate-spin" />
        </div>
      )}

      {/* ── Not found ─────────────────────────────────────────────── */}
      {error && !loading && (
        <div className="bg-white rounded-2xl shadow-sm p-6 text-sm text-gray-400 text-center">
          {error}
        </div>
      )}

      {/* ── Italian Mediterranean score ───────────────────────────── */}
      {product && !loading && product.mediterranean_score && (
        <ScoreCard score={product.mediterranean_score} />
      )}

      {/* ── Product card + nutrition ──────────────────────────────── */}
      {product && !loading && (
        <div className="bg-white rounded-2xl shadow-sm overflow-hidden relative">
          {/* Debug button */}
          <button
            onClick={openDebug}
            className="absolute top-3 right-3 px-2 py-0.5 border border-gray-200 text-gray-400 text-xs font-medium rounded-lg active:bg-gray-100 z-10"
          >
            {"{}"}
          </button>
          {/* Header row */}
          <div className="p-4 flex gap-3 items-start">
            <img
              src={offImg(product.barcode)}
              alt={product.product_name}
              onError={(e) => {
                e.target.onerror = null;
                e.target.src = PLACEHOLDER_IMG;
              }}
              className="w-20 h-20 object-contain rounded-lg border border-gray-100 bg-white flex-shrink-0"
            />
            <div className="flex-1 min-w-0">
              <div className="font-semibold text-gray-900 text-sm leading-snug">
                {product.product_name || "—"}
              </div>
              {product.brands && (
                <div className="text-xs text-gray-400 mt-0.5">
                  {product.brands}
                </div>
              )}
              {product.quantity && (
                <div className="text-xs text-gray-400">{product.quantity}</div>
              )}
              <div className="flex gap-1.5 mt-2">
                <ScoreBadge
                  grade={product.nutriscore_grade}
                  colorFn={nutriscoreColor}
                  title="Nutriscore"
                />
                <ScoreBadge
                  grade={
                    product.nova_group != null
                      ? String(product.nova_group)
                      : null
                  }
                  colorFn={(g) => novaColor(parseInt(g))}
                  title="NOVA"
                />
              </div>
            </div>
          </div>

          {/* Full nutrition panel */}
          <NutritionPanel match={product} />
        </div>
      )}

      {/* ── Similar products ──────────────────────────────────────── */}
      {(loadingSimilar || similar.length > 0) && (
        <div>
          <div className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2 px-1">
            Prodotti simili
          </div>

          {loadingSimilar ? (
            <div className="flex justify-center py-4">
              <div className="w-5 h-5 border-2 border-gray-300 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : (
            <div className="flex flex-col gap-2">
              {similar.map((p) => {
                const ms = p.mediterranean_score;
                const msColor =
                  ms && ms.score >= 75
                    ? "#16a34a"
                    : ms && ms.score >= 50
                      ? "#84cc16"
                      : ms && ms.score >= 25
                        ? "#f97316"
                        : "#ef4444";
                return (
                  <button
                    key={p.barcode}
                    onClick={() => loadProduct(p)}
                    className="flex items-center gap-3 bg-white rounded-xl shadow-sm p-3 text-left active:bg-gray-50 transition-colors w-full"
                  >
                    <img
                      src={offImg(p.barcode)}
                      alt={p.product_name}
                      onError={(e) => {
                        e.target.onerror = null;
                        e.target.src = PLACEHOLDER_IMG;
                      }}
                      className="w-14 h-14 object-contain rounded-lg border border-gray-100 bg-white flex-shrink-0"
                    />
                    <div className="flex-1 min-w-0">
                      <div className="text-xs font-semibold text-gray-800 leading-tight truncate">
                        {p.product_name || "—"}
                      </div>
                      {p.brands && (
                        <div className="text-[10px] text-gray-400 truncate mt-0.5">
                          {p.brands}
                        </div>
                      )}
                      {ms && (
                        <div className="mt-1.5">
                          <span
                            className="inline-flex items-center text-[10px] font-bold text-white px-1.5 py-0.5 rounded"
                            style={{ backgroundColor: msColor }}
                            title="Mediterranean score"
                          >
                            {ms.score}
                          </span>
                        </div>
                      )}
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* OFF JSON debug modal */}
      {debugProduct &&
        ReactDOM.createPortal(
          <div
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
            onClick={() => setDebugProduct(null)}
          >
            <div
              className="bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
                <span className="font-semibold text-sm text-gray-700 truncate">
                  {debugProduct.product_name}
                </span>
                <button
                  onClick={() => setDebugProduct(null)}
                  className="text-gray-400 text-lg leading-none ml-2"
                >
                  ✕
                </button>
              </div>
              <div className="overflow-auto p-4 text-xs font-mono">
                <JsonNode value={debugProduct} depth={0} />
              </div>
            </div>
          </div>,
          document.body,
        )}
    </div>
  );
}
