/* ============================================================
   INside Cotizador Pro — Builder: items table, image cell (lógica C), modal
   ============================================================ */

// ---------- APU editor modal (desglose de precio unitario) ----------
function APUModal({ item, product, onClose, onSave }) {
  const init = item.apu || window.getAPU(product || item);
  const [apu, setApu] = React.useState({ suministro: init.suministro || 0, logistica: init.logistica || 0, instalacion: init.instalacion || 0 });
  const [aparte, setAparte] = React.useState(!!item.logistica_aparte);
  const set = (k, v) => setApu((a) => ({ ...a, [k]: parseFloat(v) || 0 }));

  const full = apu.suministro + apu.logistica + apu.instalacion;
  const unit = window.apuUnitPrice(apu, aparte);
  const C = window.APU_COLORS;
  const rows = [
    ["suministro", "Suministro", "Material y producto puesto en bodega"],
    ["logistica", "Logística y manejo", "Transporte, montacargas, manejo en sitio"],
    ["instalacion", "Instalación", "Mano de obra y montaje"],
  ];

  const save = () => onSave({ apu, logistica_aparte: aparte, unit_price: unit });

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 480 }}>
        <div className="modal-head">
          <div>
            <div className="eyebrow">Análisis de precio unitario</div>
            <h3 style={{ margin: "3px 0 0", fontFamily: "var(--display)", fontSize: 19, fontWeight: 600 }}>Desglose APU</h3>
          </div>
          <button className="iconbtn" onClick={onClose}><window.Icon name="x" size={18} /></button>
        </div>
        <div style={{ padding: "2px 22px 6px", color: "var(--muted)", fontSize: 12.5, lineHeight: 1.5 }}>
          {product ? product.name : (item.name || "Ítem")} — define qué compone el precio por {item.unit}.
        </div>

        {/* stacked bar */}
        <div style={{ padding: "8px 22px 4px" }}>
          <div className="apu-bar">
            {full > 0 && rows.map(([k]) => (
              <div key={k} className="apu-seg" style={{ width: (apu[k] / full * 100) + "%", background: C[k] }} />
            ))}
          </div>
        </div>

        <div style={{ padding: "8px 22px 0" }}>
          {rows.map(([k, label, hint]) => (
            <div key={k} className="apu-row">
              <div className="apu-key">
                <span className="apu-dot" style={{ background: C[k] }} />
                <div>
                  <div style={{ fontWeight: 500 }}>{label}{k === "logistica" && aparte && <span style={{ color: "var(--muted)", fontWeight: 400 }}> · ítem aparte</span>}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{hint}</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
                <span style={{ color: "var(--muted)", fontFamily: "var(--mono)", fontSize: 12 }}>$</span>
                <input className="apu-inp" inputMode="decimal" value={apu[k]} onChange={(e) => set(k, e.target.value)} />
              </div>
            </div>
          ))}
        </div>

        {/* logística aparte toggle */}
        <div style={{ margin: "14px 22px 0", padding: "12px 14px", background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 10,
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Facturar logística como ítem aparte</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2, maxWidth: 300, lineHeight: 1.45 }}>
              Se muestra en una línea separada del precio del producto (recomendado, porque varía).
            </div>
          </div>
          <window.Toggle on={aparte} onChange={setAparte} />
        </div>

        {/* result */}
        <div style={{ margin: "14px 22px 0", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16 }}>
          <div>
            <div className="lbl">Precio unitario al cliente</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 22, fontWeight: 700 }}>{window.fmtMoney(unit)}</div>
          </div>
          {aparte && (
            <div style={{ textAlign: "right" }}>
              <div className="lbl">+ Logística / {item.unit}</div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 15, fontWeight: 600, color: C.logistica }}>{window.fmtMoney(apu.logistica)}</div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <div style={{ flex: 1 }} />
          <window.Btn variant="outline" onClick={onClose}>Cancelar</window.Btn>
          <window.Btn variant="gold" icon="check" onClick={save}>Aplicar</window.Btn>
        </div>
      </div>
    </div>
  );
}

// ---------- Image upload mini-modal (real file loading + URL) ----------
function ImageModal({ item, product, onClose, onSave }) {
  const [tab, setTab] = React.useState("upload");
  const [url, setUrl] = React.useState(window.isRealImage(item.item_image_url) ? item.item_image_url : "");
  const [label, setLabel] = React.useState(item.image_label || "");
  const [drag, setDrag] = React.useState(false);
  const fileRef = React.useRef(null);

  const readFile = (file) => {
    if (!file || !file.type.startsWith("image/")) return;
    const reader = new FileReader();
    reader.onload = (e) => setUrl(e.target.result); // data URL
    reader.readAsDataURL(file);
  };

  const hasPreview = window.isRealImage(url);
  const save = () => onSave({ item_image_url: url || null, image_source: url ? "custom" : "product", image_label: label || null });

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 460 }}>
        <div className="modal-head">
          <div>
            <div className="eyebrow">Imagen del ítem</div>
            <h3 style={{ margin: "3px 0 0", fontFamily: "var(--display)", fontSize: 19, fontWeight: 600 }}>Cambiar imagen</h3>
          </div>
          <button className="iconbtn" onClick={onClose}><window.Icon name="x" size={18} /></button>
        </div>
        <div style={{ padding: "4px 22px 8px", color: "var(--muted)", fontSize: 12.5, lineHeight: 1.5 }}>
          {product ? product.name : "Producto"} — reemplaza la foto del catálogo por la referencia del acabado elegido.
        </div>

        <div className="seg" style={{ margin: "12px 22px" }}>
          <button className={tab === "upload" ? "on" : ""} onClick={() => setTab("upload")}>Subir imagen</button>
          <button className={tab === "url" ? "on" : ""} onClick={() => setTab("url")}>URL externa</button>
        </div>

        <div style={{ padding: "0 22px" }}>
          {tab === "upload" ? (
            <div onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)}
              onDrop={(e) => { e.preventDefault(); setDrag(false); readFile(e.dataTransfer.files[0]); }}
              onClick={() => fileRef.current && fileRef.current.click()}
              style={{ border: "1.5px dashed " + (drag ? "var(--gold)" : "var(--border-strong)"), borderRadius: 11,
                padding: "26px 18px", textAlign: "center", background: drag ? "color-mix(in oklch, var(--gold) 8%, transparent)" : "var(--bg)",
                transition: "all .15s ease", cursor: "pointer" }}>
              <input ref={fileRef} type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => readFile(e.target.files[0])} />
              <window.Icon name="upload" size={24} style={{ color: "var(--muted)" }} />
              <div style={{ marginTop: 9, fontSize: 13, color: "var(--text)" }}>Arrastra una imagen o haz click para elegir</div>
              <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4, fontFamily: "var(--mono)" }}>JPG · PNG · WEBP</div>
            </div>
          ) : (
            <div>
              <label className="field-lbl">Pega un enlace directo (ej. fabricante, FINSA)</label>
              <input className="inp" value={url} onChange={(e) => setUrl(e.target.value)}
                placeholder="https://finsa.com/acabados/oak-4796.jpg" />
            </div>
          )}

          {/* live preview */}
          {hasPreview && (
            <div style={{ marginTop: 14, display: "flex", gap: 12, alignItems: "center" }}>
              <div style={{ width: 72, height: 72, borderRadius: 9, overflow: "hidden", border: "1px solid var(--border-strong)", flexShrink: 0, background: "var(--bg)" }}>
                <img src={url} alt="preview" style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  onError={(e) => { e.target.style.display = "none"; }} />
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
                Vista previa de la imagen cargada.<br />Aparecerá en la tabla y en el PDF.
              </div>
            </div>
          )}

          <div style={{ marginTop: 16 }}>
            <label className="field-lbl">Caption opcional <span style={{ color: "var(--muted)", fontWeight: 400, textTransform: "none" }}>— aparece bajo la imagen en el PDF</span></label>
            <input className="inp" value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Oak Natural 4796 — FINSA" />
          </div>
        </div>

        <div className="modal-foot">
          {item.item_image_url && (
            <window.Btn variant="outline" icon="reset" onClick={() => onSave({ item_image_url: null, image_source: "product", image_label: null })}>
              Resetear a catálogo
            </window.Btn>
          )}
          <div style={{ flex: 1 }} />
          <window.Btn variant="outline" onClick={onClose}>Cancelar</window.Btn>
          <window.Btn variant="gold" icon="check" onClick={save} disabled={!url}>Guardar</window.Btn>
        </div>
      </div>
    </div>
  );
}

// ---------- Image cell in the items table ----------
function ItemImageCell({ item, product, onEdit }) {
  const resolved = window.resolveItemImage(item, product);
  const custom = resolved.source === "custom";
  return (
    <div className="imgcell" style={{ width: 72 }}>
      <div style={{ position: "relative", width: 72, height: 72, borderRadius: 8, overflow: "hidden" }}>
        <window.ImageSlot cat={product ? product.category : null}
          src={resolved.url}
          label={custom ? "acabado" : (product ? product.name.split(" ")[0].toLowerCase() : "foto")}
          radius={8} custom={custom} />
        <button className="imgcell-edit" onClick={onEdit} title="Cambiar imagen">
          <window.Icon name="edit" size={15} />
        </button>
      </div>
      {resolved.label && (
        <div style={{ fontFamily: "var(--mono)", fontSize: 8.5, color: "var(--muted)", marginTop: 3, lineHeight: 1.25,
          maxWidth: 72, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={resolved.label}>{resolved.label}</div>
      )}
    </div>
  );
}

// ---------- Items table ----------
function ItemsTable({ items, products, adminMode, onUpdate, onRemove, onEditImage, onEditAPU }) {
  const prodById = React.useMemo(() => Object.fromEntries(products.map((p) => [p.id, p])), [products]);

  if (items.length === 0) {
    return (
      <div className="empty" style={{ padding: "60px 20px" }}>
        <window.Icon name="quote" size={30} style={{ color: "var(--muted)", marginBottom: 12 }} />
        <div style={{ fontSize: 15, color: "var(--text)", marginBottom: 4 }}>Aún no hay productos en la cotización</div>
        <div style={{ fontSize: 13 }}>Busca y agrega productos desde el catálogo de arriba, o agrega un ítem manual.</div>
      </div>
    );
  }

  return (
    <div className="items-table">
      <div className="it-head">
        <div style={{ width: 22 }} />
        <div style={{ width: 90 }}>Zona</div>
        <div style={{ width: 78 }}>Imagen</div>
        <div style={{ flex: 1, minWidth: 180 }}>Producto</div>
        <div style={{ width: 120 }}>Color / acabado</div>
        <div style={{ width: 84, textAlign: "right" }}>Cantidad</div>
        <div style={{ width: 110, textAlign: "right" }}>P. unit.</div>
        <div style={{ width: 96, textAlign: "right" }}>Total</div>
        {adminMode && <div style={{ width: 70, textAlign: "right" }}>Margen</div>}
        <div style={{ width: 34 }} />
      </div>

      {items.map((it) => {
        const prod = it.custom ? null : prodById[it.product_id];
        const isCustom = !!it.custom;
        const base = window.itemBase(it);
        const logi = window.itemLogistica(it);
        const margin = it.unit_price > 0 ? ((it.unit_price - it.cost_price) / it.unit_price) * 100 : 0;
        return (
          <React.Fragment key={it.id}>
          <div className="it-row">
            <div style={{ width: 22, display: "flex", alignItems: "center", color: "var(--muted)", cursor: "grab" }}>
              <window.Icon name="drag" size={16} />
            </div>
            <div style={{ width: 90 }}>
              <input className="cell-inp" value={it.zone} onChange={(e) => onUpdate(it.id, { zone: e.target.value })} placeholder="Zona" />
            </div>
            <div style={{ width: 78 }}>
              {isCustom
                ? <div className="custom-tag">manual</div>
                : <ItemImageCell item={it} product={prod} onEdit={() => onEditImage(it.id)} />}
            </div>
            <div style={{ flex: 1, minWidth: 180 }}>
              {isCustom ? (
                <>
                  <input className="cell-inp" style={{ fontSize: 13.5, fontWeight: 600 }} value={it.name}
                    onChange={(e) => onUpdate(it.id, { name: e.target.value })} placeholder="Concepto (ej. Logística)" />
                  <input className="cell-inp" style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 4 }} value={it.description}
                    onChange={(e) => onUpdate(it.id, { description: e.target.value })} placeholder="Descripción" />
                </>
              ) : (
                <>
                  <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.3 }}>{prod ? prod.name : "—"}</div>
                  <div style={{ display: "flex", gap: 7, alignItems: "center", marginTop: 4 }}>
                    {prod && <window.CatBadge cat={prod.category} />}
                    <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--muted)" }}>{prod ? prod.sku : ""}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--muted)", lineHeight: 1.45, marginTop: 5, maxWidth: 340,
                    display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{prod ? prod.description : ""}</div>
                </>
              )}
            </div>
            <div style={{ width: 120 }}>
              <input className="cell-inp" value={it.color} onChange={(e) => onUpdate(it.id, { color: e.target.value })} placeholder="Por definir" />
            </div>
            <div style={{ width: 84 }}>
              <div className="qtywrap">
                <input className="cell-inp num" value={it.quantity}
                  onChange={(e) => onUpdate(it.id, { quantity: parseFloat(e.target.value) || 0 })} />
                <span className="unit-tag">{it.unit}</span>
              </div>
            </div>
            <div style={{ width: 110, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 3 }}>
              <input className="cell-inp num" value={it.unit_price}
                onChange={(e) => onUpdate(it.id, { unit_price: parseFloat(e.target.value) || 0 })} />
              {!isCustom && (
                <button className="apu-btn" onClick={() => onEditAPU(it.id)} title="Editar desglose de precio (APU)">
                  <window.Icon name="settings" size={11} /> APU
                </button>
              )}
            </div>
            <div style={{ width: 96, textAlign: "right", fontFamily: "var(--mono)", fontSize: 14, fontWeight: 600, paddingTop: 7 }}>
              {window.fmtMoney(base)}
            </div>
            {adminMode && (
              <div style={{ width: 70, textAlign: "right", paddingTop: 4 }}>{isCustom ? <span style={{ color: "var(--muted)", fontSize: 12 }}>—</span> : <window.MarginPill pct={margin} />}</div>
            )}
            <div style={{ width: 34, display: "flex", justifyContent: "flex-end" }}>
              <button className="iconbtn danger" onClick={() => onRemove(it.id)} title="Eliminar ítem"><window.Icon name="trash" size={15} /></button>
            </div>
          </div>
          {logi > 0 && (
            <div className="it-row sub">
              <div style={{ width: 22 }} />
              <div style={{ width: 90 }} />
              <div style={{ width: 78, display: "flex", justifyContent: "center" }}><span className="sub-arrow">↳</span></div>
              <div style={{ flex: 1, minWidth: 180, display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: window.APU_COLORS.logistica }} />
                <span style={{ fontSize: 13, fontWeight: 500 }}>Logística y manejo</span>
                <span style={{ fontSize: 11.5, color: "var(--muted)" }}>· línea separada</span>
              </div>
              <div style={{ width: 120 }} />
              <div style={{ width: 84, textAlign: "right", fontFamily: "var(--mono)", fontSize: 12, color: "var(--muted)", paddingRight: 4 }}>{window.fmtNum(it.quantity)} {it.unit}</div>
              <div style={{ width: 110, textAlign: "right", fontFamily: "var(--mono)", fontSize: 13, paddingRight: 4 }}>{window.fmtMoney(it.apu.logistica)}</div>
              <div style={{ width: 96, textAlign: "right", fontFamily: "var(--mono)", fontSize: 14, fontWeight: 600 }}>{window.fmtMoney(logi)}</div>
              {adminMode && <div style={{ width: 70 }} />}
              <div style={{ width: 34 }} />
            </div>
          )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

window.APUModal = APUModal;

window.ImageModal = ImageModal;
window.ItemsTable = ItemsTable;
