/* ============================================================
   INside Cotizador Pro — Quote Builder shell (Módulo B · CORE)
   ============================================================ */

function QuoteBuilderView() {
  const ctx = React.useContext(window.AppCtx);
  const { products, settings, adminMode, quoteMeta, setQuoteMeta, currentItems,
          updateItem, removeItem, addItemToQuote, addCustomItem, goTo } = ctx;
  const [imgModalFor, setImgModalFor] = React.useState(null);
  const [apuModalFor, setApuModalFor] = React.useState(null);

  // ---- totals ----
  const subtotal = window.quoteSubtotal(currentItems);
  const discount = subtotal * (quoteMeta.discount_pct / 100);
  const taxed = subtotal - discount;
  const itbms = quoteMeta.itbms ? taxed * (settings.itbms_rate / 100) : 0;
  const total = taxed + itbms;
  const costTotal = currentItems.reduce((s, it) => s + it.quantity * it.cost_price, 0);
  const profit = taxed - costTotal;
  const marginPct = taxed > 0 ? (profit / taxed) * 100 : 0;

  const editItem = currentItems.find((i) => i.id === imgModalFor);
  const editProd = editItem && products.find((p) => p.id === editItem.product_id);
  const apuItem = currentItems.find((i) => i.id === apuModalFor);
  const apuProd = apuItem && products.find((p) => p.id === apuItem.product_id);

  return (
    <div className="builder">
      {/* ============ LEFT: client / project ============ */}
      <aside className="builder-left">
        <div className="eyebrow">Paso 1 · Datos</div>
        <h2 className="col-title">Proyecto y cliente</h2>

        <Field label="N.º de cotización" mono>
          <input className="inp" value={quoteMeta.quote_number} onChange={(e) => setQuoteMeta({ quote_number: e.target.value })} />
        </Field>
        <Field label="Nombre del proyecto">
          <input className="inp" value={quoteMeta.project_name} onChange={(e) => setQuoteMeta({ project_name: e.target.value })} placeholder="Auditorio Corporativo" />
        </Field>
        <div className="hr" />
        <Field label="Cliente">
          <input className="inp" value={quoteMeta.client_name} onChange={(e) => setQuoteMeta({ client_name: e.target.value })} placeholder="Carlos Quintero" />
        </Field>
        <Field label="Empresa">
          <input className="inp" value={quoteMeta.client_company} onChange={(e) => setQuoteMeta({ client_company: e.target.value })} placeholder="CREATIVE DEV, INC." />
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <Field label="Email"><input className="inp" value={quoteMeta.client_email} onChange={(e) => setQuoteMeta({ client_email: e.target.value })} placeholder="cq@dev.com" /></Field>
          <Field label="Teléfono"><input className="inp" value={quoteMeta.client_phone} onChange={(e) => setQuoteMeta({ client_phone: e.target.value })} placeholder="6000-0000" /></Field>
        </div>
        <div className="hr" />
        <Field label="Preparado por">
          <input className="inp" value={quoteMeta.prepared_by} onChange={(e) => setQuoteMeta({ prepared_by: e.target.value })} placeholder="Nombre del asesor" />
        </Field>
        <Field label="Email del asesor">
          <input className="inp" value={quoteMeta.prepared_email} onChange={(e) => setQuoteMeta({ prepared_email: e.target.value })} placeholder="asesor@insideelementos.com" />
        </Field>
        <Field label="Válido hasta" mono>
          <input className="inp" type="date" value={quoteMeta.valid_until} onChange={(e) => setQuoteMeta({ valid_until: e.target.value })} />
        </Field>
        <Field label="Notas">
          <textarea className="inp" rows={3} value={quoteMeta.notes} onChange={(e) => setQuoteMeta({ notes: e.target.value })}
            placeholder="Condiciones, tiempos de entrega, observaciones…" style={{ resize: "vertical", fontFamily: "var(--body)" }} />
        </Field>
      </aside>

      {/* ============ CENTER: picker + items ============ */}
      <main className="builder-main">
        <ProductPicker products={products} currentItems={currentItems} onAdd={addItemToQuote} />

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "26px 0 12px" }}>
          <div>
            <div className="eyebrow">Paso 3 · Ítems</div>
            <h2 className="col-title" style={{ margin: 0 }}>Tabla de cotización
              <span style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--muted)", fontWeight: 400, marginLeft: 10 }}>
                {currentItems.length} {currentItems.length === 1 ? "ítem" : "ítems"}</span>
            </h2>
          </div>
          {currentItems.length > 0 && (
            <div style={{ display: "flex", gap: 8 }}>
              <window.Btn variant="outline" size="sm" icon="plus" onClick={addCustomItem}>Ítem manual</window.Btn>
              <window.Btn variant="outline" size="sm" icon="doc" onClick={() => goTo("pdf")}>Vista previa PDF</window.Btn>
            </div>
          )}
        </div>

        <window.ItemsTable items={currentItems} products={products} adminMode={adminMode}
          onUpdate={updateItem} onRemove={removeItem} onEditImage={setImgModalFor} onEditAPU={setApuModalFor} />

        {currentItems.length > 0 && (
          <div style={{ marginTop: 12 }}>
            <window.Btn variant="ghost" size="sm" icon="plus" onClick={addCustomItem}>Agregar ítem manual (logística, fletes, etc.)</window.Btn>
          </div>
        )}
      </main>

      {/* ============ RIGHT: summary + margin ============ */}
      <aside className="builder-right">
        <div style={{ position: "sticky", top: 18 }}>
          <SummaryPanel {...{ subtotal, discount, itbms, total, quoteMeta, setQuoteMeta, settings }} onExport={() => goTo("pdf")} />
          {adminMode && <MarginPanel {...{ quoteMeta, total: taxed, costTotal, profit, marginPct, currentItems, products }} />}
        </div>
      </aside>

      {imgModalFor && editItem && (
        <window.ImageModal item={editItem} product={editProd}
          onClose={() => setImgModalFor(null)}
          onSave={(patch) => { updateItem(editItem.id, patch); setImgModalFor(null); }} />
      )}
      {apuModalFor && apuItem && (
        <window.APUModal item={apuItem} product={apuProd}
          onClose={() => setApuModalFor(null)}
          onSave={(patch) => { updateItem(apuItem.id, patch); setApuModalFor(null); }} />
      )}
    </div>
  );
}

// ---------- product picker rail ----------
function ProductPicker({ products, currentItems, onAdd }) {
  const [search, setSearch] = React.useState("");
  const [cat, setCat] = React.useState("ALL");
  const inQuote = new Set(currentItems.map((i) => i.product_id));
  const cats = window.AppData.CATEGORIES;
  const filtered = products.filter((p) => {
    if (cat !== "ALL" && p.category !== cat) return false;
    if (search) { const q = search.toLowerCase(); return (p.name + p.sku + p.category).toLowerCase().includes(q); }
    return true;
  });

  return (
    <div>
      <div className="eyebrow">Paso 2 · Agregar productos</div>
      <h2 className="col-title">Catálogo</h2>
      <div style={{ display: "flex", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <div className="searchbox" style={{ flex: "1 1 220px", maxWidth: 320 }}>
          <window.Icon name="search" size={16} />
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Buscar producto, SKU…" />
        </div>
        <div className="seg sm">
          <button className={cat === "ALL" ? "on" : ""} onClick={() => setCat("ALL")}>Todos</button>
          {Object.keys(cats).map((c) => <button key={c} className={cat === c ? "on" : ""} onClick={() => setCat(c)}>{cats[c].label}</button>)}
        </div>
      </div>
      <div className="picker-rail">
        {filtered.map((p) => {
          const added = inQuote.has(p.id);
          return (
            <div key={p.id} className="picker-card" onClick={() => onAdd(p)} style={{ borderColor: added ? "color-mix(in oklch, var(--gold) 40%, transparent)" : "var(--border)" }}>
              <window.ImageSlot cat={p.category} src={p.image_url} label={p.name.split(" ")[0].toLowerCase()} radius={7} />
              <div style={{ padding: "8px 9px 9px" }}>
                <div style={{ fontSize: 12, fontWeight: 600, lineHeight: 1.25, height: 30, overflow: "hidden" }}>{p.name}</div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 6 }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 12, fontWeight: 600, color: "var(--gold)" }}>{window.fmtMoney(p.sale_price)}</span>
                  <span className="picker-add" style={{ color: added ? "var(--gold)" : "var(--muted)" }}>
                    <window.Icon name={added ? "check" : "plus"} size={15} stroke={2.4} />
                  </span>
                </div>
              </div>
            </div>
          );
        })}
        {filtered.length === 0 && <div style={{ color: "var(--muted)", fontSize: 13, padding: 20 }}>Sin resultados.</div>}
      </div>
    </div>
  );
}

// ---------- summary panel (Paso 3) ----------
function SummaryPanel({ subtotal, discount, itbms, total, quoteMeta, setQuoteMeta, settings, onExport }) {
  return (
    <window.Card pad={18} style={{ marginBottom: 16 }}>
      <div className="eyebrow">Resumen</div>
      <h3 style={{ fontFamily: "var(--display)", fontSize: 17, margin: "2px 0 16px" }}>Totales</h3>

      <Row label="Subtotal" value={window.fmtMoney(subtotal)} />
      <div className="sum-row">
        <span className="sum-lbl">Descuento
          <span className="mini-inp"><input value={quoteMeta.discount_pct}
            onChange={(e) => setQuoteMeta({ discount_pct: parseFloat(e.target.value) || 0 })} />%</span>
        </span>
        <span className="sum-val" style={{ color: discount > 0 ? "var(--red)" : "var(--muted)" }}>−{window.fmtMoney(discount)}</span>
      </div>
      <div className="sum-row">
        <span className="sum-lbl" style={{ display: "flex", alignItems: "center", gap: 10 }}>
          ITBMS <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>{settings.itbms_rate}%</span>
          <window.Toggle on={quoteMeta.itbms} onChange={(v) => setQuoteMeta({ itbms: v })} />
        </span>
        <span className="sum-val" style={{ color: itbms > 0 ? "var(--text)" : "var(--muted)" }}>{window.fmtMoney(itbms)}</span>
      </div>

      <div className="total-row">
        <span>Total</span>
        <span style={{ fontFamily: "var(--mono)", fontWeight: 700, color: "var(--gold)" }}>{window.fmtMoney(total)}</span>
      </div>

      <window.Btn variant="gold" size="lg" icon="download" style={{ width: "100%", marginTop: 16 }} onClick={onExport}>Exportar cotización PDF</window.Btn>
    </window.Card>
  );
}

// ---------- margin / performance panel (PRIVADO) ----------
function MarginPanel({ quoteMeta, total, costTotal, profit, marginPct, currentItems, products }) {
  const tier = window.marginTier(marginPct);
  const prodById = Object.fromEntries(products.map((p) => [p.id, p]));
  return (
    <window.Card pad={0} style={{ overflow: "hidden", border: "1px solid color-mix(in oklch, var(--gold) 22%, var(--border))" }}>
      <div style={{ padding: "13px 18px", display: "flex", alignItems: "center", justifyContent: "space-between",
        background: "color-mix(in oklch, var(--gold) 7%, transparent)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <window.Icon name="eyeoff" size={15} style={{ color: "var(--gold)" }} />
          <span style={{ fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600, letterSpacing: ".08em", color: "var(--gold)" }}>RENDIMIENTO · PRIVADO</span>
        </div>
        <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>{quoteMeta.quote_number}</span>
      </div>
      <div style={{ padding: 18 }}>
        <Row label="Valor cotizado" value={window.fmtMoney(total)} />
        <Row label="Costo total" value={window.fmtMoney(costTotal)} muted />
        <Row label="Ganancia bruta" value={window.fmtMoney(profit)} accent />
        <div className="sum-row" style={{ borderTop: "1px solid var(--border)", marginTop: 8, paddingTop: 12 }}>
          <span className="sum-lbl">Margen neto</span>
          <window.MarginPill pct={marginPct} showLabel />
        </div>
        <div style={{ marginTop: 6, height: 6, borderRadius: 6, background: "var(--bg)", overflow: "hidden" }}>
          <div style={{ width: Math.min(100, Math.max(0, marginPct)) + "%", height: "100%", background: tier.color, transition: "width .3s ease" }} />
        </div>

        {currentItems.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <div className="lbl" style={{ marginBottom: 8 }}>Por línea</div>
            {currentItems.map((it) => {
              const m = it.unit_price > 0 ? ((it.unit_price - it.cost_price) / it.unit_price) * 100 : 0;
              const prod = prodById[it.product_id];
              return (
                <div key={it.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "5px 0", gap: 10 }}>
                  <span style={{ fontSize: 12, color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {prod ? prod.name : "—"}</span>
                  <window.MarginPill pct={m} />
                </div>
              );
            })}
          </div>
        )}
        <div style={{ marginTop: 14, fontSize: 10.5, color: "var(--muted)", fontFamily: "var(--mono)", lineHeight: 1.5,
          display: "flex", gap: 7, alignItems: "flex-start" }}>
          <window.Icon name="eyeoff" size={13} style={{ flexShrink: 0, marginTop: 1 }} />
          Este panel nunca se incluye en el PDF del cliente.
        </div>
      </div>
    </window.Card>
  );
}

// ---------- small helpers ----------
function Field({ label, children, mono }) {
  return (
    <div style={{ marginBottom: 13 }}>
      <label className="field-lbl" style={{ fontFamily: mono ? "var(--mono)" : "var(--body)" }}>{label}</label>
      {children}
    </div>
  );
}
function Row({ label, value, muted, accent }) {
  return (
    <div className="sum-row">
      <span className="sum-lbl">{label}</span>
      <span className="sum-val" style={{ color: accent ? "var(--gold)" : muted ? "var(--muted)" : "var(--text)" }}>{value}</span>
    </div>
  );
}

window.QuoteBuilderView = QuoteBuilderView;
