// Documentos imprimibles: Resumen, Cliente, Cocina, Reparto
const fmt = (n) => "$" + (Number(n) || 0).toLocaleString("es-MX", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtDate = (d) => d ? new Date(d + "T00:00").toLocaleDateString("es-MX", { day: "2-digit", month: "long", year: "numeric" }) : "—";

function DocHeader({ subtitle }) {
  return (
    <header className="doc-header">
      <img src={(window.COTIZADOR_BASE || "") + "assets/deus-cake-logo.png"} alt="Deus Cake" className="doc-logo" />
      <div className="doc-title-bar">
        <div className="doc-title-strip">ORDEN DE COMPRA <span className="thin">||</span> <strong>{subtitle}</strong></div>
      </div>
    </header>
  );
}

function Row({ label, value, danger }) {
  return (
    <div className="doc-row">
      <div className="doc-row-label">{label}</div>
      <div className={"doc-row-value " + (danger && (!value || value === "0") ? "danger" : "")}>{value || "—"}</div>
    </div>
  );
}

// === Resumen breve (cotización) ===
function DocResumen({ s, totals }) {
  const D = window.DEUS_DATA;
  const flavorName = (id) => D.flavors.find(f => f.id === id)?.name || "—";
  const fillName = (id) => D.fillings.find(f => f.id === id)?.name || "—";

  return (
    <article className="doc doc-resumen">
      <DocHeader subtitle="COTIZACIÓN" />
      <div className="doc-body">
        <div className="doc-meta">
          <div><span>FOLIO</span><strong>{s.folio}</strong></div>
          <div><span>FECHA</span><strong>{new Date().toLocaleDateString("es-MX")}</strong></div>
          <div><span>VÁLIDA HASTA</span><strong>{new Date(Date.now() + 7*86400000).toLocaleDateString("es-MX")}</strong></div>
        </div>

        <section className="doc-section">
          <h3>Cliente</h3>
          <div className="grid-2">
            <Row label="Nombre" value={s.client.name} />
            <Row label="Teléfono" value={s.client.phone} />
          </div>
        </section>

        <section className="doc-section">
          <h3>Pastel</h3>
          <div className="grid-2">
            <Row label="Número de personas" value={s.cake.people} />
            <Row label="Número de pisos" value={s.cake.tiers.length} />
            <Row label="Tema del pastel" value={s.cake.theme} />
            <Row label="Cobertura" value={D.coverings.find(c=>c.id===s.cake.covering)?.name} />
          </div>
          {s.cake.sameForAll ? (
            <div className="grid-2">
              <Row label="Sabor (todos los pisos)" value={flavorName(s.cake.tiers[0]?.flavor)} />
              <Row label="Relleno (todos los pisos)" value={fillName(s.cake.tiers[0]?.filling)} />
            </div>
          ) : (
            <div className="tier-table">
              <div className="tier-table-header">
                <span>Piso</span><span>Sabor</span><span>Relleno</span><span>Color</span>
              </div>
              {s.cake.tiers.map((t, i) => (
                <div key={i} className="tier-table-row">
                  <span>{i+1}</span>
                  <span>{flavorName(t.flavor)}</span>
                  <span>{fillName(t.filling)}</span>
                  <span><i className="swatch" style={{background: t.colorHex}}></i> {t.colorName || "—"}</span>
                </div>
              ))}
            </div>
          )}
        </section>

        {s.extras.items.length > 0 && (
          <section className="doc-section">
            <h3>Extras y decoraciones</h3>
            <div className="extras-list">
              {s.extras.items.map((e, i) => (
                <div key={i} className="extra-line">
                  <span>{e.qty}× {e.name}</span>
                  <span>{fmt(e.qty * e.price)}</span>
                </div>
              ))}
            </div>
          </section>
        )}

        <section className="doc-section">
          <h3>Entrega</h3>
          <div className="grid-2">
            <Row label="Fecha de entrega" value={fmtDate(s.delivery.date)} />
            <Row label="Hora de entrega" value={s.delivery.time} />
            <Row label="Lugar" value={s.delivery.locationName} />
            <Row label="Dirección" value={s.delivery.address} />
            <Row label="Distancia (km)" value={s.delivery.km ? `${s.delivery.km} km` : "—"} />
            <Row label="Tipo" value={s.delivery.foreign ? "Foráneo" : "Local"} />
          </div>
        </section>

        <section className="doc-section totals">
          <div className="totals-grid">
            <div><span>Pastel base ({s.cake.people} pers.)</span><strong>{fmt(totals.cakeBase)}</strong></div>
            {totals.specialPct > 0 && (
              <div><span>Sabores/rellenos especiales (+{Math.round(totals.specialPct*100)}%)</span><strong>{fmt(totals.specialSurcharge)}</strong></div>
            )}
            <div><span>Extras y decoraciones</span><strong>{fmt(totals.extrasSum)}</strong></div>
            <div><span>Envío</span><strong>{fmt(totals.shipping)}</strong></div>
            <div className="line"><span>Subtotal</span><strong>{fmt(totals.subtotal)}</strong></div>
            <div><span>IVA 16%</span><strong>{fmt(totals.iva)}</strong></div>
            <div className="grand"><span>Total</span><strong>{fmt(totals.total)}</strong></div>
            {totals.advance > 0 && <>
              <div><span>Anticipo</span><strong>{fmt(totals.advance)}</strong></div>
              <div className="grand alt"><span>Saldo a pagar</span><strong>{fmt(totals.balance)}</strong></div>
            </>}
          </div>
        </section>

        {s.notes && (
          <section className="doc-section">
            <h3>Comentarios</h3>
            <div className="notes-box">{s.notes}</div>
          </section>
        )}
      </div>
      <footer className="doc-footer">
        <div>Deus Cake Bakery · Gral. Miguel Negrete 73, Lomas del 5 de Mayo, Puebla · Tel. 2226282397</div>
      </footer>
    </article>
  );
}

// === Cliente ===
function DocCliente({ s, totals }) {
  return (
    <article className="doc doc-cliente">
      <DocHeader subtitle="PARA CLIENTES" />
      <div className="doc-body two-col">
        <div className="col-left">
          <div className="block">
            <h4 className="strip">DATOS DEL CLIENTE</h4>
            <Row label="NOMBRE" value={s.client.name} />
            <Row label="TELÉFONO" value={s.client.phone} />
          </div>

          <div className="block">
            <h4 className="strip">DATOS DE ENTREGA</h4>
            <Row label="FECHA DE ENTREGA" value={fmtDate(s.delivery.date)} danger />
            <Row label="HORA DE ENTREGA" value={s.delivery.time} danger />
            <Row label="NOMBRE SALÓN O CASA" value={s.delivery.locationName} />
            <Row label="FORÁNEO O LOCAL" value={s.delivery.foreign ? "FORÁNEO" : "LOCAL"} />
            <Row label="DIRECCIÓN DE ENTREGA" value={s.delivery.address} />
            <Row label="TIPO DE PASTEL" value={s.cake.theme} />
          </div>

          <div className="block address-block">
            <h4>DIRECCIÓN</h4>
            <p>GENERAL MIGUEL NEGRETE 73, LOMAS DEL 5 DE MAYO, PUEBLA.<br/>
            TELÉFONO: 2226282397 / TELÉFONO DE RESPALDO: 2226282397</p>
            <h4>CUENTAS</h4>
            <p>BANCO: BANCOMER<br/>
            NOMBRE: MARIA TERESA SANCHEZ<br/><br/>
            TRANSFERENCIA<br/>
            TARJETA: 4152 3141 6366 5766<br/>
            CUENTA: 0464525922<br/>
            CLABE: 012650004645259223</p>
            <p>OXXO<br/>OPCIÓN 1: 4152 3141 6366 5766</p>
          </div>
        </div>

        <div className="col-right">
          <div className="cake-portrait">
            {s.cake.preview}
          </div>
          <div className="block payment-block">
            <h4 className="strip">PAGO</h4>
            <div className="pay-row"><span>PRECIO</span><strong>{fmt(totals.cakeBase + totals.specialSurcharge + totals.extrasSum)}</strong></div>
            <div className="pay-row"><span>ENVÍO</span><strong>{fmt(totals.shipping)}</strong></div>
            <div className="pay-row"><span>ADELANTO</span><strong>{fmt(totals.advance)}</strong></div>
            <div className="pay-row line"><span>SUBTOTAL</span><strong>{fmt(totals.subtotal)}</strong></div>
            <div className="pay-row"><span>IVA</span><strong>{fmt(totals.iva)}</strong></div>
            <div className="pay-row total"><span>TOTAL</span><strong>{fmt(totals.total)}</strong></div>
          </div>
        </div>
      </div>
    </article>
  );
}

// === Cocina ===
function DocCocina({ s }) {
  const D = window.DEUS_DATA;
  const flavorName = (id) => D.flavors.find(f => f.id === id)?.name || "—";
  const fillName = (id) => D.fillings.find(f => f.id === id)?.name || "—";

  return (
    <article className="doc doc-cocina">
      <DocHeader subtitle="COCINA" />
      <div className="doc-body">
        <div className="grid-cocina-top">
          <div className="block">
            <h4 className="strip">DATOS ESPECÍFICOS</h4>
            <Row label="CÓDIGO DE CLIENTE" value={s.client.code} />
            <Row label="NÚMERO DE PERSONAS" value={s.cake.people} />
            <Row label="NÚMERO DE PISOS" value={s.cake.tiers.length} />
            <Row label="TEMA DEL PASTEL" value={s.cake.theme} />
            <Row label="TIPO DE HIDRATACIÓN" value={s.cake.hydration} />
          </div>
          <div className="block">
            <h4 className="strip">NOMBRE SOBRE EL PASTEL</h4>
            <Row label="CAKE TOPPER / DEFINIR" value={s.cake.topper.enabled ? "CAKE TOPPER" : "NO"} />
            <Row label="NOMBRE O LEYENDA" value={s.cake.topper.text} />
            <Row label="CAKE TOPPER CORTE DE PAPEL" value={s.cake.topper.paper ? "SÍ" : "NO"} />
            <Row label="CAKE TOPPER CORTE LÁSER" value={s.cake.topper.laser ? "SÍ" : "NO"} />
            <Row label="SI ES CORTE LÁSER, ¿QUÉ COLOR?" value={s.cake.topper.laserColor} />
            <Row label="MATERIAL / ESTILO / TAMAÑO" value={s.cake.topper.material} />
          </div>
          <div className="block">
            <h4 className="strip">FLORES</h4>
            <Row label="AZÚCAR O FONDANT" value={s.cake.flowers.fondant ? "SÍ" : "NO"} />
            <Row label="NATURALES" value={s.cake.flowers.natural ? "SÍ" : "NO"} />
            <Row label="COLOR DE LAS FLORES" value={s.cake.flowers.color} />
          </div>
          <div className="block">
            <h4 className="strip">TIPO DE MUÑECOS</h4>
            <Row label="FONDANT 3D" value={s.cake.figures.fondant3d ? "SÍ" : "NO"} />
            <Row label="2D SOBRE ARROZ" value={s.cake.figures.arroz ? "SÍ" : "NO"} />
            <Row label="IMPRESO" value={s.cake.figures.impreso ? "SÍ" : "NO"} />
            <Row label="GALLETA ROYAL ICING" value={s.cake.figures.galleta ? "SÍ" : "NO"} />
            <Row label="RELIEVE" value={s.cake.figures.relieve ? "SÍ" : "NO"} />
          </div>
        </div>

        <h4 className="strip wide">ESPECIFICACIONES DE CADA PISO</h4>
        <div className="tier-grid">
          {s.cake.tiers.map((t, i) => (
            <div key={i} className="tier-card">
              <div className="tier-head">PISO {i+1}{i === 0 ? " / EL DE ABAJO EN LA BASE" : ""}</div>
              <Row label="BUTTERCREAM O FONDANT" value={(D.coverings.find(c=>c.id===s.cake.covering)?.name || "").toUpperCase()} />
              <Row label="PISO NORMAL / DOBLE / EXTENDIDO" value={(D.tierTypes.find(x=>x.id===t.tierType)?.name || "").toUpperCase()} />
              <Row label="SABOR" value={flavorName(t.flavor)} danger />
              <Row label="RELLENO" value={fillName(t.filling)} danger />
              <Row label="COLOR" value={t.colorName} />
              <Row label="CÓDIGO PANTONE" value={t.pantone} />
              <Row label="ACABADO UNIÓN" value={t.union} />
              <Row label="ESPECIFICACIONES ESPECIALES" value={t.special} />
            </div>
          ))}
        </div>

        {s.notes && (
          <div className="block notes">
            <h4 className="strip">COMENTARIOS</h4>
            <div className="notes-box">{s.notes}</div>
          </div>
        )}
      </div>
    </article>
  );
}

// === Reparto ===
function DocReparto({ s, totals }) {
  return (
    <article className="doc doc-reparto">
      <DocHeader subtitle="REPARTO" />
      <div className="doc-body two-col">
        <div className="col-left">
          <div className="cake-portrait small">{s.cake.preview}</div>
        </div>
        <div className="col-right">
          <Row label="DIRECCIÓN DE ENTREGA" value={s.delivery.address} />
          <Row label="NOMBRE DEL SALÓN O CASA PARTICULAR" value={s.delivery.locationName} />
          <Row label="LOCAL O FORÁNEO" value={s.delivery.foreign ? "FORÁNEO" : "LOCAL"} danger />
          <Row label="HORARIO" value={`${s.delivery.time || "—"} · ${fmtDate(s.delivery.date)}`} danger />
          <Row label="NOMBRE DEL SOLICITANTE" value={s.client.name} />
          <Row label="TELÉFONO DEL SOLICITANTE" value={s.client.phone} />
          <Row label="NOMBRE DE QUIEN RECIBE" value={s.delivery.receiverName} />
          <Row label="TELÉFONO DE QUIEN RECIBE" value={s.delivery.receiverPhone} />

          <div className="cake-summary">
            <h4 className="strip">DETALLES DEL PASTEL</h4>
            <Row label="CAKE TOPPER" value={s.cake.topper.enabled ? "SÍ" : "NO"} />
            <Row label="NOMBRE EN EL PASTEL" value={s.cake.topper.text} />
            <Row label="FIGURAS" value={(s.cake.figures.fondant3d || s.cake.figures.impreso || s.cake.figures.galleta) ? "SÍ" : "NO"} />
            <Row label="NÚMERO DE PISOS" value={s.cake.tiers.length} />
            {s.cake.tiers.map((t, i) => (
              <Row key={i} label={`COLOR DEL PISO ${i+1}`} value={t.colorName} />
            ))}
            <div className="saldo">
              <span>SALDO A PAGAR</span>
              <strong>{fmt(totals.balance)}</strong>
            </div>
          </div>
        </div>
      </div>
      {s.notes && (
        <div className="comments-bar">
          <span>COMENTARIOS</span>
          <div className="notes-inline">{s.notes}</div>
        </div>
      )}
    </article>
  );
}

Object.assign(window, { DocResumen, DocCliente, DocCocina, DocReparto, fmt, fmtDate });
