// ===== Cotizaciones: presupuestos independientes de una orden =====
// Sirve para: presupuestar antes de recibir el equipo, o cotizar la venta de un producto.

function quoteStatus(q){
  const created = new Date(q.createdAt);
  const until = new Date(created.getTime() + (q.validDays||15)*86400000);
  return { until, vigente: Date.now() <= until.getTime() };
}
function quoteTotal(q){ return (q.items||[]).reduce((s,i)=> s + (+i.qty||0)*(+i.price||0), 0); }

// ===== Vista principal =====
function Cotizaciones({ quotes, onCreate, onUpdate, onDelete, currentUser, onSaveClient, orders }){
  const [view, setView] = React.useState("list"); // list | new | detail
  const [selId, setSelId] = React.useState(null);
  const [q, setQ] = React.useState("");
  const isAdmin = currentUser.roleId === "admin";
  const sel = quotes.find(x=>x.id===selId);

  let rows = [...quotes].sort((a,b)=> new Date(b.createdAt)-new Date(a.createdAt));
  if(q.trim()){
    const s = q.trim().toLowerCase();
    rows = rows.filter(v => (v.num+" "+v.clientName+" "+(v.brand||"")+" "+(v.model||"")).toLowerCase().includes(s));
  }

  function openNew(){ setView("new"); }
  function openDetail(id){ setSelId(id); setView("detail"); }
  function back(){ setView("list"); setSelId(null); }
  function handleCreate(q){ onCreate(q); openDetail(q.id); }

  if(view==="new") return <QuoteForm quotes={quotes} currentUser={currentUser} onSaveClient={onSaveClient} onCreate={handleCreate} onCancel={back} />;
  if(view==="detail" && sel) return <QuoteDetail quote={sel} onBack={back} onDelete={()=>{ onDelete(sel.id); back(); }} isAdmin={isAdmin} />;

  return (
    <div style={{ animation:"fadeUp .35s ease" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:16, flexWrap:"wrap", gap:12 }}>
        <div style={{ position:"relative", flex:1, maxWidth:340 }}>
          <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="search" size={17} /></span>
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Buscar cotización, cliente o equipo…"
            style={{ width:"100%", padding:"9px 12px 9px 37px", fontSize:13.5, borderRadius:10, border:"1px solid var(--line)", background:"var(--surface-2)", outline:"none", color:"var(--ink)" }} />
        </div>
        <Btn icon="plus" onClick={openNew}>Nueva cotización</Btn>
      </div>

      <Card pad={0}>
        <div style={{ overflowX:"auto" }}>
          <table style={{ width:"100%", borderCollapse:"collapse", minWidth:760 }}>
            <thead>
              <tr style={{ height:38, background:"var(--surface-2)" }}>
                {["Cotización","Cliente","Detalle","Total","Validez",""].map((h,i)=>(
                  <th key={i} style={{ textAlign: i===3?"right":"left", padding:"0 16px", fontSize:11.5, fontWeight:700, letterSpacing:"0.04em", textTransform:"uppercase", color:"var(--faint)" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((v,idx)=>{
                const { until, vigente } = quoteStatus(v);
                const total = quoteTotal(v);
                return (
                  <tr key={v.id} onClick={()=>openDetail(v.id)} style={{ height:60, borderBottom: idx<rows.length-1?"1px solid var(--line-2)":"none", cursor:"pointer" }}
                    onMouseEnter={e=>e.currentTarget.style.background="var(--surface-2)"} onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                    <td style={{ padding:"0 16px" }}>
                      <span className="mono" style={{ fontSize:13.5, fontWeight:700, color:"var(--accent-ink)" }}>#{v.num}</span>
                      <div style={{ fontSize:11.5, color:"var(--faint)" }}>{fmtDate(v.createdAt)}</div>
                    </td>
                    <td style={{ padding:"0 16px" }}>
                      <div style={{ fontSize:13.5, fontWeight:600 }}>{v.clientName||"Cliente sin nombre"}</div>
                      {v.clientPhone && <div style={{ fontSize:11.5, color:"var(--muted)" }} className="mono">{v.clientPhone}</div>}
                    </td>
                    <td style={{ padding:"0 16px", fontSize:12.5, color:"var(--ink-2)" }}>
                      {v.kind==="reparacion" ? [v.brand,v.model].filter(Boolean).join(" ")||"Equipo" : "Producto / servicio"}
                      <div style={{ fontSize:11.5, color:"var(--faint)" }}>{(v.items||[]).length} línea{(v.items||[]).length!==1?"s":""}</div>
                    </td>
                    <td style={{ padding:"0 16px", textAlign:"right" }}><span className="mono" style={{ fontSize:14, fontWeight:700 }}>{fmtMoney(total)}</span></td>
                    <td style={{ padding:"0 16px" }}>
                      <span style={{ fontSize:11.5, fontWeight:700, padding:"3px 9px", borderRadius:99,
                        background: vigente?"var(--st-listo-soft)":"var(--danger-soft)", color: vigente?"var(--st-listo)":"var(--danger)" }}>
                        {vigente ? `Vigente hasta ${fmtDate(until)}` : "Vencida"}
                      </span>
                    </td>
                    <td style={{ padding:"0 12px" }} onClick={e=>e.stopPropagation()}>
                      <div style={{ display:"flex", gap:2, justifyContent:"flex-end" }}>
                        <IconBtn icon="eye" size={15} title="Ver / imprimir" onClick={()=>openDetail(v.id)} />
                      </div>
                    </td>
                  </tr>
                );
              })}
              {rows.length===0 && (
                <tr><td colSpan={6}>
                  <div style={{ padding:"52px", textAlign:"center", color:"var(--faint)" }}>
                    <Icon name="doc" size={32} style={{ opacity:0.4 }} />
                    <div style={{ fontSize:14, fontWeight:600, color:"var(--muted)", marginTop:8 }}>
                      {q ? "Sin resultados para tu búsqueda" : "Aún no hay cotizaciones"}
                    </div>
                    {!q && <div style={{ fontSize:13, marginTop:3 }}>Crea la primera con "Nueva cotización".</div>}
                  </div>
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

// ===== Formulario: nueva cotización =====
function QuoteForm({ quotes, currentUser, onSaveClient, onCreate, onCancel }){
  const nextNum = String(Math.max(...quotes.map(q=>+q.num).filter(n=>!isNaN(n)), 0) + 1);
  const [kind, setKind] = React.useState("reparacion"); // reparacion | producto
  const [clientMode, setClientMode] = React.useState("existing");
  const [clientId, setClientId] = React.useState("");
  const [clientQuery, setClientQuery] = React.useState("");
  const [newClient, setNewClient] = React.useState({ name:"", phone:"", email:"" });
  const [brand, setBrand] = React.useState("");
  const [model, setModel] = React.useState("");
  const [issue, setIssue] = React.useState("");
  const [items, setItems] = React.useState([{ desc:"", qty:1, price:"" }]);
  const [validDays, setValidDays] = React.useState(15);
  const [notes, setNotes] = React.useState("");
  const [touched, setTouched] = React.useState(false);

  function upItem(i, patch){ setItems(prev=>prev.map((it,idx)=> idx===i ? {...it, ...patch} : it)); }
  function addItem(){ setItems(prev=>[...prev, { desc:"", qty:1, price:"" }]); }
  function removeItem(i){ setItems(prev=> prev.length>1 ? prev.filter((_,idx)=>idx!==i) : prev); }

  const total = items.reduce((s,i)=> s + (+i.qty||0)*(+i.price||0), 0);
  const validItems = items.some(i=> i.desc.trim() && (+i.price||0) >= 0);
  const hasClientName = clientMode==="existing" ? !!clientId : !!newClient.name.trim();

  function submit(){
    setTouched(true);
    if(!hasClientName || !validItems) return;
    let cl = null;
    if(clientMode==="existing") cl = CLIENTS.find(c=>c.id===clientId);
    else if(newClient.name.trim()) cl = onSaveClient({ name:newClient.name.trim(), phone:newClient.phone.trim(), email:newClient.email.trim() });

    const quote = {
      id:"q"+Date.now(), num:nextNum, createdAt:new Date().toISOString(), createdBy:currentUser.name,
      kind, clientId: cl?.id||null, clientName: cl?.name||"", clientPhone: cl?.phone||"", clientEmail: cl?.email||"",
      brand: kind==="reparacion" ? brand.trim() : "", model: kind==="reparacion" ? model.trim() : "",
      issue: kind==="reparacion" ? issue.trim() : "",
      items: items.filter(i=>i.desc.trim()).map(i=>({ desc:i.desc.trim(), qty:+i.qty||1, price:+i.price||0 })),
      validDays: +validDays||15, notes: notes.trim(),
    };
    onCreate(quote);
  }

  return (
    <div style={{ animation:"fadeUp .35s ease", maxWidth:760 }}>
      <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:18 }}>
        <IconBtn icon="arrowLeft" title="Volver" onClick={onCancel} />
        <h2 style={{ fontSize:19, fontWeight:800, margin:0 }}>Nueva cotización</h2>
      </div>

      <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
        <Card>
          <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Tipo de cotización</h3>
          <div style={{ display:"flex", gap:8 }}>
            {[["reparacion","Reparación de equipo","tools"],["producto","Producto / servicio","box"]].map(([id,l,ic])=>{
              const active = kind===id;
              return (
                <button key={id} onClick={()=>setKind(id)} style={{ flex:1, display:"flex", alignItems:"center", gap:9, padding:"12px 14px", borderRadius:11, cursor:"pointer",
                  border:`1px solid ${active?"var(--accent)":"var(--line)"}`, background: active?"var(--accent-soft)":"var(--surface)", color: active?"var(--accent-ink)":"var(--ink-2)" }}>
                  <Icon name={ic} size={19} /> <span style={{ fontSize:14, fontWeight:700 }}>{l}</span>
                </button>
              );
            })}
          </div>
        </Card>

        <Card>
          <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:14 }}>
            <h3 style={{ fontSize:15, fontWeight:700, margin:0 }}>Cliente</h3>
            <div style={{ display:"flex", gap:4, background:"var(--surface-2)", padding:3, borderRadius:9 }}>
              {[["existing","Existente"],["new","Nuevo"]].map(([id,l])=>{
                const active = clientMode===id;
                return <button key={id} onClick={()=>setClientMode(id)} style={{ padding:"5px 12px", borderRadius:7, border:"none", fontSize:12.5, fontWeight:600, cursor:"pointer",
                  background: active?"var(--surface)":"transparent", color: active?"var(--ink)":"var(--muted)", boxShadow: active?"var(--shadow-sm)":"none" }}>{l}</button>;
              })}
            </div>
          </div>

          {clientMode==="existing" ? (
            <div>
              <div style={{ position:"relative", marginBottom:12 }}>
                <Icon name="search" size={17} style={{ position:"absolute", left:13, top:"50%", transform:"translateY(-50%)", color:"var(--faint)", pointerEvents:"none" }} />
                <input value={clientQuery} onChange={e=>setClientQuery(e.target.value)}
                  placeholder="Buscar por nombre, teléfono o cédula…"
                  style={{ ...inputStyle, paddingLeft:38, paddingRight:clientQuery?34:14 }} />
                {clientQuery && <button onClick={()=>setClientQuery("")} title="Limpiar"
                  style={{ position:"absolute", right:10, top:"50%", transform:"translateY(-50%)", border:"none", background:"transparent", cursor:"pointer", color:"var(--faint)", padding:2, display:"flex" }}><Icon name="x" size={16} /></button>}
              </div>
              {(()=>{
                const norm = s => (s||"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");
                const qq = norm(clientQuery.trim());
                const digits = clientQuery.replace(/\D/g,"");
                let list = CLIENTS;
                if(qq){
                  list = CLIENTS.filter(c=>{
                    const nameHit = norm(c.name).includes(qq);
                    const phoneHit = digits && ((c.phone||"").replace(/\D/g,"").includes(digits) || (c.phone2||"").replace(/\D/g,"").includes(digits));
                    const cedHit = digits && (c.cedula||"").replace(/\D/g,"").includes(digits);
                    return nameHit || phoneHit || cedHit;
                  });
                }
                const selClient = clientId ? CLIENTS.find(c=>c.id===clientId) : null;
                if(selClient && !list.some(c=>c.id===clientId)) list = [selClient, ...list];
                const total = list.length;
                const shown = list.slice(0,40);
                if(total===0) return (
                  <div style={{ padding:"18px 12px", textAlign:"center", fontSize:13, color:"var(--muted)" }}>
                    No se encontró ningún cliente con “{clientQuery}”.<br/>
                    <button onClick={()=>{ setClientMode("new"); setNewClient(nc=>({ ...nc, name: /\d/.test(clientQuery)?nc.name:clientQuery })); }}
                      style={{ marginTop:8, border:"none", background:"transparent", color:"var(--accent-ink)", fontWeight:700, fontSize:13, cursor:"pointer" }}>+ Crear cliente nuevo</button>
                  </div>
                );
                return (
                  <>
                    <div style={{ display:"flex", flexDirection:"column", gap:8, maxHeight:230, overflowY:"auto" }}>
                      {shown.map(c=>{
                        const sel = clientId===c.id;
                        return (
                          <button key={c.id} onClick={()=>setClientId(c.id)}
                            style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 12px", borderRadius:10, textAlign:"left",
                              border:`1px solid ${sel?"var(--accent)":"var(--line)"}`, background: sel?"var(--accent-soft)":"var(--surface)" }}>
                            <Avatar name={c.name} hue={256} size={34} />
                            <div style={{ flex:1, minWidth:0 }}>
                              <div style={{ fontSize:13.5, fontWeight:700 }}>{c.name}</div>
                              <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{c.phone}</div>
                            </div>
                            {sel && <Icon name="check" size={17} style={{ color:"var(--accent)" }} />}
                          </button>
                        );
                      })}
                    </div>
                    <div style={{ fontSize:12, color:"var(--faint)", marginTop:9 }}>
                      {qq ? `${total} resultado${total!==1?"s":""}${total>40?" · mostrando 40, afina la búsqueda":""}` : `${CLIENTS.length.toLocaleString("es")} clientes · escribe para buscar`}
                    </div>
                  </>
                );
              })()}
              {touched && !clientId && <div style={{ fontSize:12.5, color:"var(--danger)", marginTop:8 }}>Selecciona un cliente.</div>}
            </div>
          ) : (
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:13 }}>
              <Field label="Nombre completo" required>
                <TextInput value={newClient.name} onChange={e=>setNewClient({...newClient,name:e.target.value})} placeholder="Nombre del cliente"
                  style={touched&&!newClient.name.trim()?{borderColor:"var(--danger)"}:{}} />
              </Field>
              <Field label="Teléfono">
                <TextInput value={newClient.phone} onChange={e=>setNewClient({...newClient,phone:e.target.value})} placeholder="+503 7000-0000" />
              </Field>
              <Field label="Correo" style={{ gridColumn:"1 / -1" }}>
                <TextInput type="email" value={newClient.email} onChange={e=>setNewClient({...newClient,email:e.target.value})} placeholder="correo@ejemplo.com" />
              </Field>
            </div>
          )}
        </Card>

        {kind==="reparacion" && (
          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Equipo</h3>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:13, marginBottom:13 }}>
              <Field label="Marca"><TextInput value={brand} onChange={e=>setBrand(e.target.value)} placeholder="Apple, Samsung…" /></Field>
              <Field label="Modelo"><TextInput value={model} onChange={e=>setModel(e.target.value)} placeholder="iPhone 13, Galaxy A54…" /></Field>
            </div>
            <Field label="Falla reportada / trabajo a cotizar">
              <textarea value={issue} onChange={e=>setIssue(e.target.value)} rows={2} placeholder="Ej. pantalla rota, no enciende…"
                style={{ ...inputStyle, resize:"vertical", fontFamily:"var(--font)" }} />
            </Field>
          </Card>
        )}

        <Card>
          <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Líneas de la cotización</h3>
          <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 70px 110px 32px", gap:8, fontSize:11.5, fontWeight:700, color:"var(--faint)", textTransform:"uppercase", letterSpacing:"0.04em", padding:"0 2px" }}>
              <span>Descripción</span><span>Cant.</span><span>Precio unit.</span><span></span>
            </div>
            {items.map((it,i)=>(
              <div key={i} style={{ display:"grid", gridTemplateColumns:"1fr 70px 110px 32px", gap:8, alignItems:"center" }}>
                <input value={it.desc} onChange={e=>upItem(i,{desc:e.target.value})} placeholder="Ej. Cambio de pantalla, mano de obra…" style={inputStyle} />
                <input type="number" min={1} value={it.qty} onChange={e=>upItem(i,{qty:e.target.value})} style={{ ...inputStyle, textAlign:"center" }} />
                <div style={{ position:"relative" }}>
                  <span style={{ position:"absolute", left:11, top:"50%", transform:"translateY(-50%)", fontSize:13, color:"var(--faint)" }}>US$</span>
                  <input type="number" min={0} step="0.01" value={it.price} onChange={e=>upItem(i,{price:e.target.value})} placeholder="0.00" style={{ ...inputStyle, paddingLeft:36, fontFamily:"var(--mono)" }} />
                </div>
                <button onClick={()=>removeItem(i)} disabled={items.length===1} title="Quitar línea"
                  style={{ width:32, height:36, border:"none", background:"transparent", color: items.length===1?"var(--faint)":"var(--danger)", cursor: items.length===1?"default":"pointer", display:"flex", alignItems:"center", justifyContent:"center" }}>
                  <Icon name="trash" size={16} />
                </button>
              </div>
            ))}
          </div>
          <button onClick={addItem} style={{ marginTop:10, display:"inline-flex", alignItems:"center", gap:6, border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:13, fontWeight:700, cursor:"pointer" }}>
            <Icon name="plus" size={16} /> Añadir línea
          </button>
          {touched && !validItems && <div style={{ fontSize:12.5, color:"var(--danger)", marginTop:8 }}>Añade al menos una línea con descripción.</div>}
          <div style={{ display:"flex", justifyContent:"flex-end", marginTop:16, paddingTop:14, borderTop:"1px solid var(--line-2)" }}>
            <div style={{ fontSize:14, color:"var(--muted)", marginRight:10 }}>Total</div>
            <div className="mono" style={{ fontSize:22, fontWeight:800 }}>{fmtMoney(total)}</div>
          </div>
        </Card>

        <Card>
          <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Validez y notas</h3>
          <div style={{ display:"grid", gridTemplateColumns:"160px 1fr", gap:13 }}>
            <Field label="Válida por (días)">
              <input type="number" min={1} value={validDays} onChange={e=>setValidDays(e.target.value)} style={inputStyle} />
            </Field>
            <Field label="Notas / condiciones" hint="Opcional">
              <input value={notes} onChange={e=>setNotes(e.target.value)} placeholder="Ej. no incluye garantía extendida…" style={inputStyle} />
            </Field>
          </div>
        </Card>

        <div style={{ display:"flex", justifyContent:"flex-end", gap:10 }}>
          <Btn variant="secondary" onClick={onCancel}>Cancelar</Btn>
          <Btn icon="check" onClick={submit}>Guardar cotización</Btn>
        </div>
      </div>
    </div>
  );
}

// ===== Documento imprimible de cotización =====
function QuoteReceipt({ quote }){
  const items = quote.items||[];
  const total = quoteTotal(quote);
  const { until } = quoteStatus(quote);
  const now = new Date();
  const shop = { ...SHOP, ...((typeof window!=="undefined" && window.CP_SHOP) || {}) };
  const equipo = [quote.brand, quote.model].filter(Boolean).join(" ");

  return (
    <div id="print-area" className="doc" style={{ fontFamily:"var(--font)", color:"#111", background:"#fff", padding:"4px 2px" }}>
      <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" }}>COTIZACIÓN</div>
          <div style={{ fontSize:11.5, color:"#555", marginTop:4 }}>Fecha: {fmtDate(quote.createdAt)}</div>
          <div style={{ display:"inline-block", marginTop:6, fontSize:13, fontWeight:800, color:"#111", border:"1.5px solid #1f3a93", borderRadius:5, padding:"3px 12px" }}>N° {String(quote.num).padStart(4,"0")}</div>
        </div>
      </div>

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

      <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={quote.clientName||"—"} />
            <DocRow k="Teléfono:" v={quote.clientPhone||"—"} mono />
            {quote.clientEmail && <DocRow k="Correo:" v={quote.clientEmail} />}
          </div>
        </div>
        <div>
          <DocSectionTitle>{quote.kind==="reparacion" ? "DATOS DEL EQUIPO" : "DETALLE"}</DocSectionTitle>
          <div style={{ display:"flex", flexDirection:"column", gap:3 }}>
            {quote.kind==="reparacion" ? (
              <>
                <DocRow k="Equipo:" v={equipo||"—"} />
                <DocRow k="Falla:" v={quote.issue||"—"} />
              </>
            ) : <DocRow k="Tipo:" v="Producto / servicio" />}
            <DocRow k="Válida hasta:" v={fmtDate(until)} />
          </div>
        </div>
      </div>

      <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</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||0).toFixed(2)}</td>
              <td style={{ padding:"7px 9px", textAlign:"right" }} className="mono">{fmtMoney(it.price)}</td>
              <td style={{ padding:"7px 9px", textAlign:"right", fontWeight:600 }} className="mono">{fmtMoney((+it.qty||0)*(+it.price||0))}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div style={{ display:"flex", justifyContent:"flex-end", marginBottom:14 }}>
        <div style={{ width:240 }}>
          <div style={{ display:"flex", justifyContent:"space-between", fontSize:14, padding:"7px 9px", background:"#1f3a93", color:"#fff", borderRadius:4, marginTop:3 }}>
            <span style={{ fontWeight:700 }}>TOTAL</span><span className="mono" style={{ fontWeight:800 }}>{fmtMoney(total)}</span>
          </div>
        </div>
      </div>

      {quote.notes && (
        <div style={{ fontSize:11.5, color:"#444", marginBottom:14, lineHeight:1.5 }}>
          <span style={{ color:"#555" }}>Notas: </span>{quote.notes}
        </div>
      )}

      <div style={{ fontSize:9.5, color:"#666", lineHeight:1.5, marginBottom:18, fontStyle:"italic" }}>
        Esta cotización no constituye una orden de trabajo. Precios sujetos a cambio sin previo aviso una vez vencida la validez indicada arriba.
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:24, marginTop:20 }}>
        <div style={{ textAlign:"center" }}>
          <div style={{ borderTop:"1px solid #333", paddingTop:5, fontSize:10.5, color:"#333" }}>Firma, {quote.clientName||"Cliente"}</div>
          <div style={{ fontSize:9.5, color:"#999", marginTop:2 }}>Conforme con la cotización</div>
        </div>
        <div style={{ textAlign:"center" }}>
          <div style={{ borderTop:"1px solid #333", paddingTop:5, fontSize:10.5, color:"#333" }}>Firma, Empleado responsable</div>
          <div style={{ fontSize:9.5, color:"#999", marginTop:2 }}>{quote.createdBy||"Aclaración"}</div>
        </div>
      </div>

      <div style={{ marginTop:26, paddingTop:14, borderTop:"1px solid #ddd", fontSize:9.5, color:"#888", lineHeight:1.6, textAlign:"center" }}>
        Documento generado por la plataforma de gestión Casepoint · No representa un comprobante fiscal.
      </div>
    </div>
  );
}

// ===== Detalle de cotización: imprimir / enviar por correo =====
function QuoteDetail({ quote, onBack, onDelete, isAdmin }){
  const [showPrint, setShowPrint] = React.useState(false);
  const [showConfirm, setShowConfirm] = React.useState(false);
  const [emailState, setEmailState] = React.useState(null); // null | "sending" | "ok" | error msg
  const { until, vigente } = quoteStatus(quote);
  const total = quoteTotal(quote);

  async function sendEmail(){
    if(!quote.clientEmail){ setEmailState("Este cliente no tiene correo registrado."); return; }
    setEmailState("sending");
    try{
      const r = await fetch("/api/email/quote", {
        method:"POST", credentials:"include", headers:{ "Content-Type":"application/json" },
        body: JSON.stringify({ to:quote.clientEmail, clientName:quote.clientName, num:quote.num,
          brand:quote.brand, model:quote.model, items:quote.items, validUntil: until.toISOString(), notes:quote.notes }),
      });
      const d = await r.json().catch(()=>({}));
      if(d && d.ok) setEmailState("ok");
      else setEmailState(d?.message || "No se pudo enviar el correo.");
    }catch(e){ setEmailState("Sin conexión con el servidor."); }
  }

  return (
    <div style={{ animation:"fadeUp .35s ease", maxWidth:760 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:16, flexWrap:"wrap", gap:10 }}>
        <div style={{ display:"flex", alignItems:"center", gap:10 }}>
          <IconBtn icon="arrowLeft" title="Volver" onClick={onBack} />
          <div>
            <h2 style={{ fontSize:19, fontWeight:800, margin:0 }}>Cotización #{quote.num}</h2>
            <div style={{ fontSize:12.5, color:"var(--muted)" }}>{quote.clientName} · {fmtMoney(total)}</div>
          </div>
        </div>
        <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
          <Btn variant="secondary" size="sm" icon="print" onClick={()=>setShowPrint(true)}>Imprimir / PDF</Btn>
          <Btn variant="secondary" size="sm" icon="sms" onClick={sendEmail} disabled={emailState==="sending"}>
            {emailState==="sending" ? "Enviando…" : "Enviar por correo"}
          </Btn>
          {isAdmin && <Btn variant="danger" size="sm" icon="trash" onClick={()=>setShowConfirm(true)}>Eliminar</Btn>}
        </div>
      </div>

      {emailState && emailState!=="sending" && (
        <div style={{ marginBottom:16, padding:"11px 14px", borderRadius:10, fontSize:13, fontWeight:600,
          background: emailState==="ok" ? "var(--st-listo-soft)" : "var(--st-entrada-soft)",
          color: emailState==="ok" ? "var(--st-listo)" : "var(--st-entrada)" }}>
          {emailState==="ok" ? `Correo enviado a ${quote.clientEmail}` : emailState}
        </div>
      )}

      <div style={{ marginBottom:14 }}>
        <span style={{ fontSize:12, fontWeight:700, padding:"4px 11px", borderRadius:99,
          background: vigente?"var(--st-listo-soft)":"var(--danger-soft)", color: vigente?"var(--st-listo)":"var(--danger)" }}>
          {vigente ? `Vigente hasta ${fmtDate(until)}` : `Vencida el ${fmtDate(until)}`}
        </span>
      </div>

      <div style={{ background:"#fff", borderRadius:12, border:"1px solid var(--line)", padding:"28px 30px", boxShadow:"var(--shadow-sm)" }}>
        <QuoteReceipt quote={quote} />
      </div>

      {showPrint && (
        <div onClick={()=>setShowPrint(false)} 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" }}>
            <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={()=>setShowPrint(false)}>Cerrar</Btn>
                <Btn size="sm" icon="print" onClick={()=>window.print()}>Imprimir / Guardar PDF</Btn>
              </div>
            </div>
            <div style={{ background:"#fff", borderRadius:10, boxShadow:"var(--shadow-lg)", padding:"34px 38px" }}>
              <QuoteReceipt quote={quote} />
            </div>
          </div>
        </div>
      )}

      {showConfirm && (
        <ModalShell title="Eliminar cotización" onClose={()=>setShowConfirm(false)} maxWidth={420}>
          <div style={{ padding:"20px 22px", fontSize:14, color:"var(--ink-2)", lineHeight:1.55 }}>
            ¿Eliminar la cotización <strong>#{quote.num}</strong> de {quote.clientName}? Esta acción no se puede deshacer.
          </div>
          <div style={{ display:"flex", justifyContent:"flex-end", gap:10, padding:"16px 22px", borderTop:"1px solid var(--line)" }}>
            <Btn variant="secondary" onClick={()=>setShowConfirm(false)}>Cancelar</Btn>
            <Btn variant="danger" icon="trash" onClick={onDelete}>Sí, eliminar</Btn>
          </div>
        </ModalShell>
      )}
    </div>
  );
}

Object.assign(window, { Cotizaciones, quoteStatus, quoteTotal });
