// ===== Documentos imprimibles estilo Casepoint =====
// Reutiliza el patrón #print-area + @media print del index.

// Universal link a la orden — una futura app iOS/Android lo intercepta y abre la orden;
// si no hay app instalada, abre la versión web.
function orderUrl(order){ return `https://app.casepoint.com/orden/${String(order.num).padStart(6,"0")}`; }

function makeQR(text, cell = 4, margin = 2){
  try{
    if(typeof qrcode === "undefined") return null;
    const qr = qrcode(0, "M");
    qr.addData(text);
    qr.make();
    return qr.createDataURL(cell, margin);
  }catch(e){ return null; }
}

function QRCode({ text, size = 110, cell = 4 }){
  const [src, setSrc] = React.useState(null);
  React.useEffect(()=>{ setSrc(makeQR(text, cell)); }, [text, cell]);
  if(!src) return <div style={{ width:size, height:size, borderRadius:6, background:"var(--surface-2)", border:"1px solid var(--line)" }} />;
  return <img src={src} width={size} height={size} alt="Código QR de la orden" style={{ imageRendering:"pixelated", display:"block", borderRadius:4 }} />;
}

const SHOP = {
  name: "Taller Casepoint",
  legalName: "Casepoint · Reparación y accesorios",
  address: "Col. Escalón, San Salvador",
  phone: "+503 2200-0000",
  email: "contacto@casepoint.com",
};

function docLineItems(order){
  const parts = orderParts(order);
  const items = parts.map(p => ({ desc:p.name, qty:p.qty||1, unit:p.price||0, total:(p.price||0)*(p.qty||1) }));
  const partsCharge = items.reduce((s,i)=>s+i.total,0);
  const labor = Math.max(0, (+order.estimate||0) - partsCharge);
  if(labor>0 || items.length===0){
    items.unshift({ desc: order.diagnosis ? "Servicio de reparación" : (order.issue ? "Servicio / mano de obra" : "Servicio de reparación"), qty:1, unit:labor, total:labor });
  }
  return items;
}

function DocRow({ k, v, mono }){
  return (
    <div style={{ display:"flex", gap:8, fontSize:12, lineHeight:1.5 }}>
      <span style={{ color:"#555", minWidth:96 }}>{k}</span>
      <span className={mono?"mono":""} style={{ fontWeight:600, color:"#111" }}>{v}</span>
    </div>
  );
}

function DocSectionTitle({ children }){
  return (
    <div style={{ background:"#1f3a93", color:"#fff", fontSize:11.5, fontWeight:700, letterSpacing:"0.06em", padding:"5px 10px", borderRadius:4, marginBottom:8 }}>
      {children}
    </div>
  );
}

// kind: "ingreso" | "retiro"
function OrderReceipt({ order, kind = "ingreso" }){
  const c = getClient(order.clientId);
  const dev = getDevice(order.device);
  const t = getTech(order.techId);
  const items = docLineItems(order);
  const subtotal = items.reduce((s,i)=>s+i.total,0);
  const paid = orderPaid(order);
  const balance = orderBalance(order);
  const now = new Date();
  const title = kind==="retiro" ? "COMPROBANTE RETIRO DE EQUIPO" : "COMPROBANTE DE INGRESO";
  const shop = { ...SHOP, ...((typeof window!=="undefined" && window.CP_SHOP) || {}) };
  const banner = kind==="retiro" ? "RETIRO DE EQUIPO" : "INGRESO DE EQUIPO A REPARACIÓN";
  const disclaimer = kind==="retiro"
    ? "Mediante el presente documento confirmo haber retirado y recibido el equipo que se describe a continuación. Declarando haber leído y estar completamente de acuerdo con la descripción del presente informe del trabajo realizado. Firmando el presente documento en total conformidad."
    : "Mediante el presente documento se deja constancia del ingreso del equipo descrito a continuación para su diagnóstico y/o reparación. El cliente declara estar de acuerdo con las condiciones del servicio y autoriza la revisión del equipo.";

  return (
    <div id="print-area" className="doc" style={{ fontFamily:"var(--font)", color:"#111", background:"#fff", padding:"4px 2px" }}>
      {/* header */}
      <div style={{ display:"flex", alignItems:"flex-start", justifyContent:"space-between", gap:20, paddingBottom:14, borderBottom:"2px solid #1f3a93" }}>
        <img src="casepoint-logo.png" alt="Casepoint" style={{ width:188, height:"auto" }} />
        <div style={{ textAlign:"right" }}>
          <div style={{ fontSize:16, fontWeight:800, color:"#1f3a93", letterSpacing:"-0.01em" }}>{title}</div>
          <div style={{ fontSize:11.5, color:"#555", marginTop:4 }}>Fecha impresión: {now.toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"numeric"})} {now.toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit"})}</div>
          <div style={{ display:"inline-block", marginTop:6, fontSize:13, fontWeight:800, color:"#111", border:"1.5px solid #1f3a93", borderRadius:5, padding:"3px 12px" }}>Orden N° {String(order.num).padStart(6,"0")}</div>
        </div>
      </div>

      {/* shop line */}
      <div style={{ fontSize:11, color:"#666", margin:"8px 0 14px", textAlign:"center" }}>
        {shop.name} · {shop.address} · {shop.phone} · {shop.email}
      </div>

      {/* banner */}
      <div style={{ background:"#eef2fb", border:"1px solid #cdd9f3", borderRadius:6, padding:"8px 12px", marginBottom:10 }}>
        <div style={{ fontSize:13, fontWeight:800, color:"#1f3a93", marginBottom:4 }}>{banner}</div>
        <div style={{ fontSize:10.5, color:"#444", lineHeight:1.5 }}>{disclaimer}</div>
      </div>

      {/* two columns */}
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16, marginBottom:14 }}>
        <div>
          <DocSectionTitle>DATOS DEL CLIENTE</DocSectionTitle>
          <div style={{ display:"flex", flexDirection:"column", gap:3 }}>
            <DocRow k="Cliente:" v={c.name} />
            {c.cedula && <DocRow k="Cédula/RUC:" v={c.cedula} mono />}
            <DocRow k="Teléfono:" v={c.phone||"—"} mono />
            <DocRow k="Correo:" v={c.email||"—"} />
          </div>
        </div>
        <div>
          <DocSectionTitle>DATOS DEL EQUIPO</DocSectionTitle>
          <div style={{ display:"flex", flexDirection:"column", gap:3 }}>
            <DocRow k="Marca:" v={order.brand||"—"} />
            <DocRow k="Modelo:" v={order.model||"—"} />
            <DocRow k="Serie/IMEI:" v={order.serial||"—"} mono />
            <DocRow k="Fecha ingreso:" v={fmtDateTime(order.createdAt)} />
            <DocRow k="Presupuesto:" v={fmtMoney(order.estimate)} mono />
          </div>
        </div>
      </div>

      {/* trabajo / falla */}
      <div style={{ fontSize:12, marginBottom:12 }}>
        <span style={{ color:"#555" }}>Trabajo solicitado: </span>
        <span style={{ fontWeight:600 }}>{order.issue || "—"}</span>
      </div>

      {/* line items table */}
      <table style={{ width:"100%", borderCollapse:"collapse", fontSize:11.5, marginBottom:2 }}>
        <thead>
          <tr style={{ background:"#1f3a93", color:"#fff" }}>
            <th style={{ textAlign:"left", padding:"6px 9px", fontWeight:700 }}>Descripción productos / servicios aplicados</th>
            <th style={{ textAlign:"center", padding:"6px 6px", fontWeight:700, width:48 }}>Cant.</th>
            <th style={{ textAlign:"right", padding:"6px 9px", fontWeight:700, width:84 }}>P. Unitario</th>
            <th style={{ textAlign:"right", padding:"6px 9px", fontWeight:700, width:90 }}>Precio final</th>
          </tr>
        </thead>
        <tbody>
          {items.map((it,i)=>(
            <tr key={i} style={{ borderBottom:"1px solid #e3e3e3" }}>
              <td style={{ padding:"7px 9px" }}>{it.desc}</td>
              <td style={{ padding:"7px 6px", textAlign:"center" }} className="mono">{it.qty.toFixed(2)}</td>
              <td style={{ padding:"7px 9px", textAlign:"right" }} className="mono">{fmtMoney(it.unit)}</td>
              <td style={{ padding:"7px 9px", textAlign:"right", fontWeight:600 }} className="mono">{fmtMoney(it.total)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* totals */}
      <div style={{ display:"flex", justifyContent:"flex-end", marginBottom:14 }}>
        <div style={{ width:240 }}>
          <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, padding:"4px 9px" }}>
            <span style={{ color:"#555" }}>Subtotal</span><span className="mono" style={{ fontWeight:600 }}>{fmtMoney(subtotal)}</span>
          </div>
          {paid>0 && (
            <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, padding:"4px 9px" }}>
              <span style={{ color:"#555" }}>Abonado</span><span className="mono" style={{ fontWeight:600, color:"#1a7a44" }}>−{fmtMoney(paid)}</span>
            </div>
          )}
          <div style={{ display:"flex", justifyContent:"space-between", fontSize:14, padding:"7px 9px", background:"#1f3a93", color:"#fff", borderRadius:4, marginTop:3 }}>
            <span style={{ fontWeight:700 }}>{paid>0?"SALDO":"TOTAL"}</span><span className="mono" style={{ fontWeight:800 }}>{fmtMoney(paid>0?balance:subtotal)}</span>
          </div>
        </div>
      </div>

      {/* notas */}
      {order.log && order.log.length>0 && (
        <div style={{ marginBottom:14 }}>
          <DocSectionTitle>NOTAS</DocSectionTitle>
          <table style={{ width:"100%", borderCollapse:"collapse", fontSize:11 }}>
            <tbody>
              {order.log.filter(l=>!/Estado cambiado|Orden creada/.test(l.text)).slice(-4).map((l,i)=>(
                <tr key={i} style={{ borderBottom:"1px solid #eee" }}>
                  <td style={{ padding:"4px 8px", width:90, color:"#777", whiteSpace:"nowrap" }} className="mono">{fmtDate(l.t)}</td>
                  <td style={{ padding:"4px 8px" }}>{l.text}</td>
                </tr>
              ))}
              {order.diagnosis && (
                <tr style={{ borderBottom:"1px solid #eee" }}>
                  <td style={{ padding:"4px 8px", color:"#777" }} className="mono">{fmtDate(order.createdAt)}</td>
                  <td style={{ padding:"4px 8px" }}>{order.diagnosis}</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* observaciones */}
      <div style={{ marginBottom:16 }}>
        <div style={{ fontSize:11, color:"#555", marginBottom:5 }}>(Cliente) Observaciones / Reclamo</div>
        <div style={{ borderBottom:"1px solid #bbb", height:18 }} />
        <div style={{ borderBottom:"1px solid #bbb", height:18 }} />
      </div>

      {kind==="retiro" && (
        <div style={{ fontSize:9.5, color:"#666", lineHeight:1.5, marginBottom:18, fontStyle:"italic" }}>
          IMPORTANTE: De ser retirado por una persona que no sea {c.name}, deberá presentar un comprobante de autorización firmado, el cual se adjuntará a este documento.
        </div>
      )}

      {/* signatures */}
      <div style={{ display:"grid", gridTemplateColumns: kind==="retiro" ? "1fr 1fr 1fr" : "1fr 1fr", gap:24, marginTop:30 }}>
        {(kind==="retiro"
          ? [["Firma, "+c.name,"Aclaración"],["Firma, Empleado responsable", t?t.name:"Aclaración"],["Firma, Autorizado a retirar","Aclaración"]]
          : [["Firma, "+c.name,"Aclaración"],["Firma, Empleado responsable", t?t.name:"Aclaración"]]
        ).map(([a,b],i)=>(
          <div key={i} style={{ textAlign:"center" }}>
            <div style={{ borderTop:"1px solid #333", paddingTop:5, fontSize:10.5, color:"#333" }}>{a}</div>
            <div style={{ fontSize:9.5, color:"#999", marginTop:2 }}>{b}</div>
          </div>
        ))}
      </div>

      {/* footer con QR */}
      <div style={{ marginTop:26, paddingTop:14, borderTop:"1px solid #ddd", display:"flex", alignItems:"center", gap:16 }}>
        <div style={{ flexShrink:0, textAlign:"center" }}>
          <QRCode text={orderUrl(order)} size={92} cell={3} />
        </div>
        <div style={{ fontSize:9.5, color:"#888", lineHeight:1.6 }}>
          <div style={{ fontSize:11, fontWeight:700, color:"#1f3a93", marginBottom:2 }}>Escanea para seguir tu orden</div>
          Con la app Casepoint, el cliente y el técnico pueden escanear este código y entrar directo a la orden N° {String(order.num).padStart(6,"0")}.<br/>
          Este documento contiene información de propiedad exclusiva de CASEPOINT. Documento generado por la plataforma de gestión Casepoint.
        </div>
      </div>
    </div>
  );
}

// Modal wrapper that shows the document with print controls
function DocModal({ order, kind, onClose }){
  function print(){ window.print(); }
  return (
    <div onClick={onClose} style={{ position:"fixed", inset:0, zIndex:95, background:"oklch(0.2 0.03 262 / 0.5)", display:"flex", alignItems:"flex-start", justifyContent:"center", padding:"30px 20px", overflowY:"auto", animation:"fadeIn .15s ease" }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:"100%", maxWidth:720, animation:"popIn .18s ease" }}>
        {/* controls (hidden on print) */}
        <div className="doc-controls" style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:12 }}>
          <span style={{ color:"#fff", fontSize:13.5, fontWeight:600 }}>Vista previa del documento</span>
          <div style={{ display:"flex", gap:10 }}>
            <Btn variant="secondary" size="sm" onClick={onClose}>Cerrar</Btn>
            <Btn size="sm" icon="print" onClick={print}>Imprimir / Guardar PDF</Btn>
          </div>
        </div>
        <div style={{ background:"#fff", borderRadius:10, boxShadow:"var(--shadow-lg)", padding:"34px 38px" }}>
          <OrderReceipt order={order} kind={kind} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OrderReceipt, DocModal, SHOP, docLineItems, QRCode, orderUrl, makeQR });
