import { useState, useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import api from "../../api/client";
import { useAuth } from "../../auth/AuthContext";

const CATEGORY_LABELS = {
  controller: "Controller",
  striker: "Striker",
  clock: "Clock",
  part: "Part",
  repair_service: "Repair / Service",
};

const CATEGORIES = Object.keys(CATEGORY_LABELS);

const STATUS_OPTIONS = [
  { value: "active",       label: "Active",       activeColor: "#31ee76", activeBg: "#14532d", inactiveBg: "var(--bg-input)", inactiveColor: "var(--text-secondary)" },
  { value: "discontinued", label: "Discontinued", activeColor: "#ef4444", activeBg: "#450a0a", inactiveBg: "var(--bg-input)", inactiveColor: "var(--text-secondary)" },
  { value: "planned",      label: "Planned",      activeColor: "#f59e0b", activeBg: "#451a03", inactiveBg: "var(--bg-input)", inactiveColor: "var(--text-secondary)" },
];

const defaultForm = {
  name: "",
  sku: "",
  category: "controller",
  description: "",
  name_en: "",
  name_gr: "",
  description_en: "",
  description_gr: "",
  price: "",
  currency: "EUR",
  status: "active",
  costs: {
    labor_hours: "",
    labor_rate: "",
    items: [],
  },
  stock: {
    on_hand: "",
    reserved: "",
  },
};

function numOr(v, fallback = 0) {
  const n = parseFloat(v);
  return isNaN(n) ? fallback : n;
}

function computeCostsTotal(costs, priceField = "price_last") {
  const labor = numOr(costs.labor_hours) * numOr(costs.labor_rate);
  const itemsTotal = (costs.items || []).reduce(
    (sum, it) => sum + numOr(it.quantity, 1) * numOr(it[priceField] || it.price_last || it.price),
    0
  );
  return labor + itemsTotal;
}

const inputClass = "w-full px-3 py-2 text-sm rounded-md border";
const inputStyle = {
  backgroundColor: "var(--bg-input)",
  borderColor: "var(--border-primary)",
  color: "var(--text-primary)",
};


function Field({ label, children }) {
  return (
    <div>
      <label className="ui-form-label">{label}</label>
      {children}
    </div>
  );
}

function SectionCard({ title, children, style }) {
  return (
    <div className="ui-section-card" style={style}>
      {title && (
        <div className="ui-section-card__title-row">
          <h2 className="ui-section-card__header-title">{title}</h2>
        </div>
      )}
      {children}
    </div>
  );
}

export default function ProductForm() {
  const { id } = useParams();
  const isEdit = Boolean(id);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("crm", "edit");
  const fileInputRef = useRef(null);

  const [form, setForm] = useState(defaultForm);
  const [loading, setLoading] = useState(isEdit);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [photoPreview, setPhotoPreview] = useState(null); // local blob URL for preview
  const [photoFile, setPhotoFile] = useState(null);       // File object pending upload
  const [uploadingPhoto, setUploadingPhoto] = useState(false);
  const [existingPhotoUrl, setExistingPhotoUrl] = useState(null);

  useEffect(() => {
    if (!isEdit) return;
    api.get(`/crm/products/${id}`)
      .then((data) => {
        setForm({
          name: data.name || "",
          sku: data.sku || "",
          category: data.category || "controller",
          description: data.description || "",
          name_en: data.name_en || data.name || "",
          name_gr: data.name_gr || data.name || "",
          description_en: data.description_en || data.description || "",
          description_gr: data.description_gr || data.description || "",
          price: data.price != null ? String(data.price) : "",
          currency: data.currency || "EUR",
          status: data.status || (data.active !== false ? "active" : "discontinued"),
          costs: {
            labor_hours: data.costs?.labor_hours != null ? String(data.costs.labor_hours) : "",
            labor_rate: data.costs?.labor_rate != null ? String(data.costs.labor_rate) : "",
            items: (data.costs?.items || []).map((it) => ({
              name: it.name || "",
              quantity: String(it.quantity ?? 1),
              price_last: String(it.price_last ?? it.price ?? ""),
              price_min: String(it.price_min ?? ""),
              price_max: String(it.price_max ?? ""),
            })),
          },
          stock: {
            on_hand: data.stock?.on_hand != null ? String(data.stock.on_hand) : "",
            reserved: data.stock?.reserved != null ? String(data.stock.reserved) : "",
          },
        });
        if (data.photo_url) {
          setExistingPhotoUrl(`/api${data.photo_url}`);
        }
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [id, isEdit]);

  const set = (field, value) => setForm((f) => ({ ...f, [field]: value }));
  const setCost = (field, value) => setForm((f) => ({ ...f, costs: { ...f.costs, [field]: value } }));
  const setStock = (field, value) => setForm((f) => ({ ...f, stock: { ...f.stock, [field]: value } }));

  const addCostItem = () =>
    setForm((f) => ({
      ...f,
      costs: { ...f.costs, items: [...f.costs.items, { name: "", quantity: "1", price_last: "", price_min: "", price_max: "" }] },
    }));
  const removeCostItem = (i) =>
    setForm((f) => ({
      ...f,
      costs: { ...f.costs, items: f.costs.items.filter((_, idx) => idx !== i) },
    }));
  const setCostItem = (i, field, value) =>
    setForm((f) => ({
      ...f,
      costs: {
        ...f.costs,
        items: f.costs.items.map((it, idx) => idx === i ? { ...it, [field]: value } : it),
      },
    }));

  function handlePhotoChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    setPhotoFile(file);
    setPhotoPreview(URL.createObjectURL(file));
  }

  const buildPayload = () => ({
    name: form.name_en.trim() || form.name.trim(),
    sku: form.sku.trim() || null,
    category: form.category,
    description: form.description_en.trim() || form.description.trim() || null,
    name_en: form.name_en.trim() || null,
    name_gr: form.name_gr.trim() || null,
    description_en: form.description_en.trim() || null,
    description_gr: form.description_gr.trim() || null,
    price: form.price !== "" ? parseFloat(form.price) : null,
    currency: form.currency,
    status: form.status,
    active: form.status === "active",
    costs: {
      labor_hours: numOr(form.costs.labor_hours),
      labor_rate: numOr(form.costs.labor_rate),
      items: form.costs.items
        .filter((it) => it.name.trim())
        .map((it) => ({
          name: it.name.trim(),
          quantity: numOr(it.quantity, 1),
          price: numOr(it.price_last || it.price),
          price_last: numOr(it.price_last || it.price),
          price_min: numOr(it.price_min),
          price_max: numOr(it.price_max),
        })),
    },
    stock: {
      on_hand: parseInt(form.stock.on_hand, 10) || 0,
      reserved: parseInt(form.stock.reserved, 10) || 0,
    },
  });

  const handleSave = async () => {
    if (!form.name_en.trim() && !form.name.trim()) {
      setError("Product name (English) is required.");
      return;
    }
    setSaving(true);
    setError("");
    try {
      let savedProduct;
      if (isEdit) {
        savedProduct = await api.put(`/crm/products/${id}`, buildPayload());
      } else {
        savedProduct = await api.post("/crm/products", buildPayload());
      }
      // Upload photo if a new one was selected
      if (photoFile && savedProduct?.id) {
        setUploadingPhoto(true);
        const formData = new FormData();
        formData.append("file", photoFile);
        await fetch(`/api/crm/products/${savedProduct.id}/photo`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${localStorage.getItem("access_token")}`,
          },
          body: formData,
        });
      }
      navigate("/crm/products");
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
      setUploadingPhoto(false);
    }
  };

  const handleDelete = async () => {
    setSaving(true);
    try {
      await api.delete(`/crm/products/${id}`);
      navigate("/crm/products");
    } catch (err) {
      setError(err.message);
      setSaving(false);
    }
  };

  const costsTotalEst = computeCostsTotal(form.costs, "price_last");
  const costsTotalMin = computeCostsTotal(form.costs, "price_min");
  const costsTotalMax = computeCostsTotal(form.costs, "price_max");
  const price = parseFloat(form.price) || 0;
  const marginEst = price - costsTotalEst;
  const marginMin = price - costsTotalMax; // highest cost = lowest margin
  const marginMax = price - costsTotalMin; // lowest cost = highest margin
  const stockAvailable = (parseInt(form.stock.on_hand, 10) || 0) - (parseInt(form.stock.reserved, 10) || 0);

  if (loading) {
    return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  }

  const currentPhoto = photoPreview || existingPhotoUrl;

  return (
    <div style={{ maxWidth: 1800, margin: "0 auto" }}>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          {isEdit ? "Edit Product" : "New Product"}
        </h1>
        <div className="flex items-center gap-2">
          {isEdit && canEdit && !showDeleteConfirm && (
            <button
              type="button"
              onClick={() => setShowDeleteConfirm(true)}
              className="px-4 py-2 text-sm rounded-md border cursor-pointer hover:opacity-80"
              style={{ borderColor: "var(--danger)", color: "var(--danger)", backgroundColor: "transparent" }}
            >
              Delete
            </button>
          )}
          {isEdit && canEdit && showDeleteConfirm && (
            <>
              <span className="text-sm" style={{ color: "var(--text-secondary)" }}>Are you sure?</span>
              <button
                type="button"
                onClick={handleDelete}
                disabled={saving}
                className="px-4 py-2 text-sm rounded-md cursor-pointer hover:opacity-80"
                style={{ backgroundColor: "var(--danger)", color: "#fff", opacity: saving ? 0.7 : 1 }}
              >
                {saving ? "Deleting..." : "Yes, Delete"}
              </button>
              <button
                type="button"
                onClick={() => setShowDeleteConfirm(false)}
                className="px-4 py-2 text-sm rounded-md border cursor-pointer"
                style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
              >
                Cancel
              </button>
            </>
          )}
          {!showDeleteConfirm && (
            <>
              <button
                onClick={() => navigate("/crm/products")}
                className="px-4 py-2 text-sm rounded-md border cursor-pointer"
                style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
              >
                Cancel
              </button>
              {canEdit && (
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
                  style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: saving ? 0.7 : 1 }}
                >
                  {saving ? (uploadingPhoto ? "Uploading photo..." : "Saving...") : "Save"}
                </button>
              )}
            </>
          )}
        </div>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
        >
          {error}
        </div>
      )}

      {/* 2-column layout */}
      <div style={{ display: "flex", gap: 20, alignItems: "flex-start" }}>

        {/* LEFT column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>

          {/* Product Details */}
          <SectionCard title="Product Details">
            {/* Photo upload */}
            <div style={{ display: "flex", gap: 16, alignItems: "flex-start", marginBottom: 16 }}>
              <div
                onClick={() => canEdit && fileInputRef.current?.click()}
                style={{
                  width: 120, height: 120, borderRadius: 10, border: "2px dashed var(--border-primary)",
                  backgroundColor: "var(--bg-primary)", display: "flex", alignItems: "center",
                  justifyContent: "center", overflow: "hidden", flexShrink: 0,
                  cursor: canEdit ? "pointer" : "default", position: "relative",
                }}
              >
                {currentPhoto ? (
                  <img src={currentPhoto} alt="" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
                ) : (
                  <div style={{ textAlign: "center" }}>
                    <div style={{ fontSize: 24, opacity: 0.3 }}>📷</div>
                    <div style={{ fontSize: 10, color: "var(--text-muted)", marginTop: 4 }}>Photo</div>
                  </div>
                )}
              </div>
              <div style={{ flex: 1 }}>
                {canEdit && (
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="px-3 py-1.5 text-xs rounded-md border cursor-pointer hover:opacity-80"
                    style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
                  >
                    {currentPhoto ? "Change Photo" : "Upload Photo"}
                  </button>
                )}
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  style={{ display: "none" }}
                  onChange={handlePhotoChange}
                />
                {photoFile && (
                  <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 6 }}>
                    {photoFile.name} — will upload on save
                  </div>
                )}
                <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 6 }}>
                  JPG, PNG, or WebP. Stored on server.
                </div>
              </div>
            </div>

            {/* Name (EN) + Name (GR) */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Field label="Name — English *">
                <input
                  className={inputClass}
                  style={inputStyle}
                  value={form.name_en}
                  onChange={(e) => set("name_en", e.target.value)}
                  placeholder="e.g. Vesper Plus"
                />
              </Field>
              <Field label="Name — Greek">
                <input
                  className={inputClass}
                  style={inputStyle}
                  value={form.name_gr}
                  onChange={(e) => set("name_gr", e.target.value)}
                  placeholder="π.χ. Vesper Plus"
                />
              </Field>
            </div>

            {/* SKU + Category */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Field label="SKU">
                <input
                  className={inputClass}
                  style={inputStyle}
                  value={form.sku}
                  onChange={(e) => set("sku", e.target.value)}
                  placeholder="e.g. VSP-001"
                />
              </Field>
              <Field label="Category">
                <select
                  className={inputClass}
                  style={inputStyle}
                  value={form.category}
                  onChange={(e) => set("category", e.target.value)}
                >
                  {CATEGORIES.map((c) => (
                    <option key={c} value={c}>{CATEGORY_LABELS[c]}</option>
                  ))}
                </select>
              </Field>
            </div>

            {/* Description EN */}
            <div style={{ marginBottom: 14 }}>
              <Field label="Description — English">
                <textarea
                  className={inputClass}
                  style={{ ...inputStyle, resize: "vertical", minHeight: 72 }}
                  value={form.description_en}
                  onChange={(e) => set("description_en", e.target.value)}
                  placeholder="Optional product description in English..."
                />
              </Field>
            </div>

            {/* Description GR */}
            <div style={{ marginBottom: 14 }}>
              <Field label="Description — Greek">
                <textarea
                  className={inputClass}
                  style={{ ...inputStyle, resize: "vertical", minHeight: 72 }}
                  value={form.description_gr}
                  onChange={(e) => set("description_gr", e.target.value)}
                  placeholder="Προαιρετική περιγραφή προϊόντος στα Ελληνικά..."
                />
              </Field>
            </div>

            {/* Status toggle — color coded */}
            <div>
              <div className="ui-form-label">Status</div>
              <div style={{ display: "flex", borderRadius: 6, overflow: "hidden", border: "1px solid var(--border-primary)" }}>
                {STATUS_OPTIONS.map((opt, idx) => {
                  const isActive = form.status === opt.value;
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => canEdit && set("status", opt.value)}
                      style={{
                        flex: 1, padding: "7px 0", fontSize: 12, fontWeight: 600,
                        border: "none", cursor: canEdit ? "pointer" : "default",
                        backgroundColor: isActive ? opt.activeBg : opt.inactiveBg,
                        color: isActive ? opt.activeColor : opt.inactiveColor,
                        borderRight: idx < STATUS_OPTIONS.length - 1 ? "1px solid var(--border-primary)" : "none",
                        transition: "background-color 0.15s",
                      }}
                    >
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            </div>
          </SectionCard>

          {/* Stock */}
          <SectionCard title="Stock">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
              <Field label="On Hand">
                <input
                  type="number" min="0" step="1"
                  className={inputClass} style={inputStyle}
                  value={form.stock.on_hand}
                  onChange={(e) => setStock("on_hand", e.target.value)}
                  placeholder="0"
                />
              </Field>
              <Field label="Reserved">
                <input
                  type="number" min="0" step="1"
                  className={inputClass} style={inputStyle}
                  value={form.stock.reserved}
                  onChange={(e) => setStock("reserved", e.target.value)}
                  placeholder="0"
                />
              </Field>
              <Field label="Available">
                <div
                  className="px-3 py-2 text-sm rounded-md border"
                  style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)", color: "var(--text-heading)", fontWeight: 600 }}
                >
                  {stockAvailable}
                </div>
              </Field>
            </div>
          </SectionCard>

        </div>

        {/* RIGHT column */}
        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 16 }}>

          {/* Pricing & Mfg. Costs */}
          <SectionCard title="Pricing & Mfg. Costs">
            {/* Price */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Field label="Price (EUR)">
                <input
                  type="number" min="0" step="0.01"
                  className={inputClass} style={inputStyle}
                  value={form.price}
                  onChange={(e) => set("price", e.target.value)}
                  onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) set("price", v.toFixed(2)); }}
                  placeholder="0.00"
                />
              </Field>
              <div />
            </div>

            {/* Labor */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Field label="Labor Hours">
                <input type="number" min="0" step="0.5" className={inputClass} style={inputStyle}
                  value={form.costs.labor_hours} onChange={(e) => setCost("labor_hours", e.target.value)} placeholder="0" />
              </Field>
              <Field label="Labor Rate (€/hr)">
                <input type="number" min="0" step="0.01" className={inputClass} style={inputStyle}
                  value={form.costs.labor_rate} onChange={(e) => setCost("labor_rate", e.target.value)} placeholder="0.00" />
              </Field>
            </div>

            {/* Cost line items */}
            {form.costs.items.length > 0 && (
              <div style={{ marginBottom: 8 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 72px 85px 85px 85px 28px", gap: 6, marginBottom: 4 }}>
                  <div className="ui-form-label" style={{ marginBottom: 0 }}>Item Name</div>
                  <div className="ui-form-label" style={{ marginBottom: 0, textAlign: "center" }}>QTY</div>
                  <div className="ui-form-label" style={{ marginBottom: 0, textAlign: "center" }}>Min (€)</div>
                  <div className="ui-form-label" style={{ marginBottom: 0, textAlign: "center" }}>Max (€)</div>
                  <div className="ui-form-label" style={{ marginBottom: 0, textAlign: "center" }}>Est. (€)</div>
                  <div />
                </div>
                {form.costs.items.map((it, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 72px 85px 85px 85px 28px", gap: 6, marginBottom: 6 }}>
                    <input className={inputClass} style={inputStyle} value={it.name}
                      onChange={(e) => setCostItem(i, "name", e.target.value)} placeholder="e.g. PCB" />
                    <input type="number" min="0" step="1" className={inputClass}
                      style={{ ...inputStyle, textAlign: "center" }}
                      value={it.quantity}
                      onChange={(e) => setCostItem(i, "quantity", e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, "quantity", v.toFixed(2)); }}
                      placeholder="1" />
                    <input type="number" min="0" step="0.01" className={inputClass}
                      style={{ ...inputStyle, textAlign: "center" }}
                      value={it.price_min}
                      onChange={(e) => setCostItem(i, "price_min", e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, "price_min", v.toFixed(2)); }}
                      placeholder="0.00" title="Minimum expected price" />
                    <input type="number" min="0" step="0.01" className={inputClass}
                      style={{ ...inputStyle, textAlign: "center" }}
                      value={it.price_max}
                      onChange={(e) => setCostItem(i, "price_max", e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, "price_max", v.toFixed(2)); }}
                      placeholder="0.00" title="Maximum expected price" />
                    <input type="number" min="0" step="0.01" className={inputClass}
                      style={{ ...inputStyle, textAlign: "center" }}
                      value={it.price_last}
                      onChange={(e) => setCostItem(i, "price_last", e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, "price_last", v.toFixed(2)); }}
                      placeholder="0.00" title="Estimated / last paid price" />
                    <button type="button" onClick={() => removeCostItem(i)}
                      className="flex items-center justify-center text-base cursor-pointer hover:opacity-70"
                      style={{ color: "var(--danger)", background: "none", border: "none", padding: 0 }}>
                      ×
                    </button>
                  </div>
                ))}
              </div>
            )}

            <button type="button" onClick={addCostItem}
              className="px-3 py-1.5 text-xs rounded-md border cursor-pointer hover:opacity-80 mb-4"
              style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}>
              + Add Cost Item
            </button>

            {/* Summary rows */}
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {/* Mfg. Cost Total — three values */}
              <div className="px-3 py-2 rounded-md text-sm"
                style={{ backgroundColor: "var(--bg-primary)", color: "var(--text-secondary)" }}>
                <div className="flex items-center justify-between">
                  <span>Mfg. Cost Total</span>
                  <div className="flex items-center gap-2 font-mono text-xs">
                    <span style={{ color: "var(--text-more-muted)" }} title="Min–Max cost range">
                      €{costsTotalMin.toFixed(2)} – €{costsTotalMax.toFixed(2)}
                    </span>
                    <span style={{ color: "var(--border-primary)" }}>|</span>
                    <span className="font-semibold" style={{ color: "var(--text-heading)" }} title="Estimated cost">
                      est. €{costsTotalEst.toFixed(2)}
                    </span>
                  </div>
                </div>
              </div>
              {/* Margin — three values */}
              <div className="px-3 py-2 rounded-md text-sm"
                style={{ backgroundColor: "var(--bg-primary)", color: "var(--text-secondary)" }}>
                <div className="flex items-center justify-between">
                  <span>Margin (Price − Cost)</span>
                  {form.price ? (
                    <div className="flex items-center gap-2 font-mono text-xs">
                      <span style={{ color: (marginMin >= 0 && marginMax >= 0) ? "var(--text-more-muted)" : "var(--danger-text)" }} title="Margin range (min–max cost)">
                        €{marginMax.toFixed(2)} – €{marginMin.toFixed(2)}
                      </span>
                      <span style={{ color: "var(--border-primary)" }}>|</span>
                      <span className="font-semibold" style={{ color: marginEst >= 0 ? "var(--success-text)" : "var(--danger-text)" }} title="Estimated margin">
                        est. €{marginEst.toFixed(2)}
                      </span>
                    </div>
                  ) : (
                    <span className="font-mono font-semibold" style={{ color: "var(--text-muted)" }}>—</span>
                  )}
                </div>
              </div>
            </div>
          </SectionCard>

        </div>
      </div>
    </div>
  );
}
