/* ============================================================
   INside Cotizador Pro — Export PDF preview (Módulo E)
   A4 portrait — espejo del PDF al cliente. Nunca muestra costos/márgenes.
   ============================================================ */

function PDFPreview() {
  const { products, settings, quoteMeta, currentItems, goTo } = React.useContext(window.AppCtx);
  const prodById = Object.fromEntries(products.map((p) => [p.id, p]));
  const [pageSize, setPageSize] = React.useState("A4");

  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 m2total = currentItems.filter((i) => i.unit === "m2").reduce((s, i) => s + i.quantity, 0);

  const issued = new Date().toLocaleDateString("es-PA", { day: "2-digit", month: "2-digit", year: "numeric" });
  const validUntil = quoteMeta.valid_until
    ? new Date(quoteMeta.valid_until + "T00:00").toLocaleDateString("es-PA", { day: "2-digit", month: "2-digit", year: "numeric" })
    : "—";

  const downloadPDF = () => {
    const id = "__print-page-size";
    let s = document.getElementById(id);
    if (!s) { s = document.createElement("style"); s.id = id; document.head.appendChild(s); }
    s.textContent = `@media print{@page{size:${pageSize === "Letter" ? "Letter" : "A4"} portrait;margin:0;}}`;
    window.print();
  };

  return (
    <div style={{ padding: "26px 36px 80px" }}>
      {/* toolbar */}
      <div className="pdf-toolbar no-print">
        <window.Btn variant="outline" icon="chevron" onClick={() => goTo("builder")} style={{ flexDirection: "row-reverse" }}>Volver al constructor</window.Btn>
        <div>
          <div className="eyebrow" style={{ textAlign: "center" }}>Módulo · Export PDF</div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--muted)", textAlign: "center" }}>Sin márgenes ni costos · listo para el cliente</div>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <div className="seg sm">
            <button className={pageSize === "A4" ? "on" : ""} onClick={() => setPageSize("A4")}>A4</button>
            <button className={pageSize === "Letter" ? "on" : ""} onClick={() => setPageSize("Letter")}>Letter</button>
          </div>
          <window.Btn variant="gold" icon="download" onClick={downloadPDF}>Descargar PDF</window.Btn>
        </div>
      </div>

      {/* A4 sheet */}
      <div className="a4-wrap">
        <div className="a4" style={{ minHeight: pageSize === "Letter" ? 984 : 1075 }}>
          <div className="a4-strip" />
          {/* header */}
          <div className="a4-pad">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <img src="cotizador/assets/logo-lockup-black.png" alt="INside Elementos Arquitectónicos"
                  style={{ height: 52, width: "auto", display: "block" }} />
              </div>
              <div style={{ textAlign: "right", fontSize: 8, color: "#7a7d82", lineHeight: 1.6 }}>
                <div>{settings.company_address}</div>
                <div>{settings.company_ruc}</div>
                <div>{settings.company_phone}</div>
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 22, paddingBottom: 12, borderBottom: "2px solid #16181b" }}>
              <div style={{ minWidth: 0, flex: 1, paddingRight: 16 }}>
                <div style={{ fontSize: 8, letterSpacing: ".2em", color: "#9a9da2", textTransform: "uppercase" }}>Cotización</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginTop: 2 }}>
                  <span style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 26, color: "#16181b", letterSpacing: "-.02em", lineHeight: 1 }}>{quoteMeta.quote_number}</span>
                  <span style={{ fontWeight: 400, color: "#7a7d82", fontSize: 13, lineHeight: 1.2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{quoteMeta.project_name || "Proyecto"}</span>
                </div>
              </div>
              <div style={{ textAlign: "right", fontSize: 8.5, color: "#5a5d62", lineHeight: 1.7, flexShrink: 0 }}>
                <div>Emitida: <b style={{ color: "#16181b" }}>{issued}</b></div>
                <div>Válido hasta: <b style={{ color: "#16181b" }}>{validUntil}</b></div>
              </div>
            </div>

            {/* client / prepared block */}
            <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr auto", gap: 18, marginTop: 14 }}>
              <div>
                <div className="a4-lbl">Cliente</div>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#16181b" }}>{quoteMeta.client_name || "—"}</div>
                <div style={{ fontSize: 9, color: "#5a5d62" }}>{quoteMeta.client_company}</div>
                <div style={{ fontSize: 8.5, color: "#7a7d82", marginTop: 2 }}>{quoteMeta.client_email} · {quoteMeta.client_phone}</div>
              </div>
              <div>
                <div className="a4-lbl">Preparado por</div>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#16181b" }}>{quoteMeta.prepared_by || "—"}</div>
                {quoteMeta.prepared_email && <div style={{ fontSize: 8.5, color: "#7a7d82", marginTop: 2 }}>{quoteMeta.prepared_email}</div>}
              </div>
              <div style={{ textAlign: "right", borderLeft: "1px solid #e6e6e8", paddingLeft: 16 }}>
                <div className="a4-lbl">M² total</div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 20, fontWeight: 700, color: "#16181b" }}>{window.fmtNum(m2total)}</div>
              </div>
            </div>

            {/* items table */}
            <table className="a4-table">
              <thead>
                <tr>
                  <th style={{ width: 54 }}>Zona</th>
                  <th style={{ width: 62 }}>Imagen</th>
                  <th>Descripción</th>
                  <th style={{ width: 70 }}>Color</th>
                  <th style={{ width: 30 }}>Uni</th>
                  <th style={{ width: 42, textAlign: "right" }}>Cant</th>
                  <th style={{ width: 54, textAlign: "right" }}>Precio</th>
                  <th style={{ width: 60, textAlign: "right" }}>Total</th>
                </tr>
              </thead>
              <tbody>
                {currentItems.map((it) => {
                  const isCustom = !!it.custom;
                  const prod = isCustom ? null : prodById[it.product_id];
                  const resolved = window.resolveItemImage(it, prod);
                  const base = window.itemBase(it);
                  const logi = window.itemLogistica(it);
                  const name = isCustom ? (it.name || "Concepto") : (prod ? prod.name : "—");
                  const desc = isCustom ? (it.description || "") : (prod ? prod.description : "");
                  return (
                    <React.Fragment key={it.id}>
                    <tr>
                      <td style={{ fontWeight: 600, color: "#16181b" }}>{it.zone}</td>
                      <td>
                        {isCustom ? <span style={{ fontSize: 6, color: "#b5b7bb", fontFamily: "var(--mono)" }}>—</span> : (
                        <><div className="a4-img">
                          {window.isRealImage(resolved.url)
                            ? <img src={resolved.url} alt="" />
                            : <span style={{ fontSize: 5.5, color: "#9a9da2", fontFamily: "var(--mono)" }}>{resolved.source === "custom" ? "acabado" : "foto"}</span>}
                        </div>
                        {resolved.label && <div style={{ fontSize: 5.5, color: "#9a9da2", marginTop: 2, lineHeight: 1.2 }}>{resolved.label}</div>}</>)}
                      </td>
                      <td>
                        <div style={{ fontWeight: 700, color: "#16181b", fontSize: 8.5 }}>{name}</div>
                        <div style={{ color: "#7a7d82", fontSize: 7.5, lineHeight: 1.45, marginTop: 1 }}>{desc}</div>
                      </td>
                      <td style={{ color: "#5a5d62" }}>{it.color}</td>
                      <td style={{ color: "#5a5d62" }}>{it.unit}</td>
                      <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{window.fmtNum(it.quantity)}</td>
                      <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{window.fmtMoney(it.unit_price)}</td>
                      <td style={{ textAlign: "right", fontFamily: "var(--mono)", fontWeight: 700, color: "#16181b" }}>{window.fmtMoney(base)}</td>
                    </tr>
                    {logi > 0 && (
                      <tr>
                        <td></td><td></td>
                        <td><div style={{ fontWeight: 600, color: "#16181b", fontSize: 8 }}>↳ Logística y manejo</div>
                          <div style={{ color: "#7a7d82", fontSize: 7, marginTop: 1 }}>Transporte y manejo en sitio</div></td>
                        <td></td>
                        <td style={{ color: "#5a5d62" }}>{it.unit}</td>
                        <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{window.fmtNum(it.quantity)}</td>
                        <td style={{ textAlign: "right", fontFamily: "var(--mono)" }}>{window.fmtMoney(it.apu.logistica)}</td>
                        <td style={{ textAlign: "right", fontFamily: "var(--mono)", fontWeight: 700, color: "#16181b" }}>{window.fmtMoney(logi)}</td>
                      </tr>
                    )}
                    </React.Fragment>
                  );
                })}
                {currentItems.length === 0 && (
                  <tr><td colSpan={8} style={{ textAlign: "center", color: "#9a9da2", padding: 20 }}>Sin ítems — agrégalos en el constructor.</td></tr>
                )}
              </tbody>
            </table>

            {/* totals */}
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}>
              <div style={{ width: 220 }}>
                <PdfTot label="Subtotal" value={window.fmtMoney(subtotal)} />
                <PdfTot label={`Descuento (${quoteMeta.discount_pct}%)`} value={"−" + window.fmtMoney(discount)} />
                <PdfTot label={`ITBMS (${quoteMeta.itbms ? settings.itbms_rate : 0}%)`} value={window.fmtMoney(itbms)} />
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4, padding: "7px 0", borderTop: "2px solid #16181b" }}>
                  <span style={{ fontWeight: 800, fontSize: 11, color: "#16181b" }}>TOTAL</span>
                  <span style={{ fontFamily: "var(--mono)", fontWeight: 800, fontSize: 14, color: "#16181b" }}>{window.fmtMoney(total)}</span>
                </div>
              </div>
            </div>

            {/* notes / footer */}
            <div style={{ marginTop: 18, paddingTop: 12, borderTop: "1px solid #e6e6e8", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
              <div>
                {quoteMeta.notes && (<><div className="a4-lbl">Notas</div><div style={{ fontSize: 8, color: "#5a5d62", lineHeight: 1.55, marginBottom: 8 }}>{quoteMeta.notes}</div></>)}
                <div className="a4-lbl">Información bancaria</div>
                <div style={{ fontSize: 8, color: "#5a5d62", lineHeight: 1.55 }}>{settings.bank_info}</div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
                <div style={{ borderTop: "1px solid #16181b", paddingTop: 5, fontSize: 8, color: "#7a7d82" }}>Cotización aceptada por (firma)</div>
              </div>
            </div>
            <div style={{ marginTop: 20, paddingTop: 10, borderTop: "1px solid #e6e6e8", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 8, color: "#7a7d82" }}>{settings.tagline}</span>
              <span style={{ fontFamily: "var(--mono)", fontSize: 8, color: "#7a7d82" }}>{settings.company_web}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PdfTot({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9, padding: "3px 0", color: "#5a5d62" }}>
      <span>{label}</span><span style={{ fontFamily: "var(--mono)" }}>{value}</span>
    </div>
  );
}

window.PDFPreview = PDFPreview;
