/* ============================================================================
   dash-orders.jsx  —  Work orders: list, editor, invoice/receipt, messaging
============================================================================ */
(function(){
const { useState, useEffect } = React;
const { C, fmt$, dateStr, statusLabel, statusColor, calc, Btn, Tag, Card, Label, Row, Grid, Stat, H2, H3, Icon, useIsMobile } = window;
const uid2 = (p) => CheoDB.uid(p);

/* ── SMS helpers ── */
async function sendClientSMS(phone, message) {
  try {
    const res = await fetch('/api/send-sms', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ to: phone, message }),
    });
    return await res.json();
  } catch (e) {
    return { error: e.message };
  }
}

function buildSmsMsg(status, custName, veh, orderId, total, shopName) {
  const first = custName ? custName.split(' ')[0] : '';
  const car = veh ? `${veh.year} ${veh.make} ${veh.model}` : 'tu vehículo';
  const shop = shopName || 'Cheo Auto Repair';
  if (status === 'in_progress') {
    return `Hola ${first}, comenzamos a trabajar en tu ${car} (orden ${orderId}). Te avisamos cuando esté listo. Sigue el progreso en: cheoautorepair.com/customer 🔧`;
  }
  if (status === 'ready') {
    return `¡Hola ${first}! Tu ${car} (orden ${orderId}) está lista para recoger. Total: $${Number(total).toFixed(2)}. ¡Gracias por confiar en ${shop}! 🎉`;
  }
  return `Hola ${first}, actualización de tu ${car} (orden ${orderId}): estado actualizado. Detalles en: cheoautorepair.com/customer`;
}

/* resize an uploaded image to a localStorage-friendly dataURL */
function fileToThumb(file, cb) {
  const reader = new FileReader();
  reader.onload = e => {
    const img = new Image();
    img.onload = () => {
      const max = 1000;
      let { width:w, height:h } = img;
      if (w > max || h > max) { const r = Math.min(max/w, max/h); w = Math.round(w*r); h = Math.round(h*r); }
      const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
      cv.getContext('2d').drawImage(img, 0, 0, w, h);
      cb(cv.toDataURL('image/jpeg', 0.7));
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

const inp = {background:'oklch(0.11 0.015 222)',border:`1.5px solid ${C.dark4}`,borderRadius:8,padding:'9px 12px',color:C.white,fontSize:'0.875rem',outline:'none',width:'100%',fontFamily:'inherit'};
function Field({label,children}) { return <div><Label>{label}</Label>{children}</div>; }
function TextInput(props){ return <input {...props} style={{...inp,...(props.style||{})}}/>; }
function Select({value,onChange,children,...rest}){ return <select value={value} onChange={onChange} style={inp} {...rest}>{children}</select>; }

/* ──────────────────────────────────────────────────────────────────────────
   WORK ORDER FORM
─────────────────────────────────────────────────────────────────────────── */
function OrderForm({order, customers, settings, onSave, onCancel}) {
  const blank = {
    id:null, date:new Date().toISOString().slice(0,10), status:'waiting', customer_id:'', vehicle_id:'',
    mechanic:'César (Cheo)', repairs:[{id:uid2('r'),name:'',parts:[{id:uid2('p'),desc:'',qty:1,price:''}],labor:''}],
    extras:[], tax_enabled:false, tax_rate:settings.tax_rate||6.5, paid:false, photos:[], notes:'', timeline:[]
  };
  const [form,setForm]=useState(order||blank);
  const [smsToggle,setSmsToggle]=useState(false);
  const [smsSending,setSmsSending]=useState(false);
  const [smsResult,setSmsResult]=useState(null);
  const [extraCusts,setExtraCusts]=useState([]);
  const [newCustModal,setNewCustModal]=useState(false);
  const [nc,setNc]=useState({name:'',phone:'',year:'',make:'',model:'',plate:''});
  const allCustomers=[...customers,...extraCusts.filter(ec=>!customers.find(c=>c.id===ec.id))];
  const selCust=allCustomers.find(c=>c.id===form.customer_id);
  const tots=calc(form);

  const upd=patch=>{
    setForm(f=>{
      const next={...f,...patch};
      if(patch.status!==undefined){
        const autoSend=['in_progress','ready'].includes(patch.status);
        setSmsToggle(autoSend);
        setSmsResult(null);
      }
      return next;
    });
  };
  const updRepair=(ri,patch)=>setForm(f=>({...f,repairs:f.repairs.map((r,i)=>i===ri?{...r,...patch}:r)}));
  const updPart=(ri,pi,patch)=>setForm(f=>({...f,repairs:f.repairs.map((r,i)=>i===ri?{...r,parts:r.parts.map((p,j)=>j===pi?{...p,...patch}:p)}:r)}));
  const addRepair=()=>upd({repairs:[...form.repairs,{id:uid2('r'),name:'',parts:[{id:uid2('p'),desc:'',qty:1,price:''}],labor:''}]});
  const removeRepair=ri=>upd({repairs:form.repairs.filter((_,i)=>i!==ri)});
  const addPart=ri=>updRepair(ri,{parts:[...form.repairs[ri].parts,{id:uid2('p'),desc:'',qty:1,price:''}]});
  const removePart=(ri,pi)=>updRepair(ri,{parts:form.repairs[ri].parts.filter((_,j)=>j!==pi)});
  const addExtra=()=>upd({extras:[...form.extras,{id:uid2('e'),desc:'',price:''}]});
  const removeExtra=ei=>upd({extras:form.extras.filter((_,i)=>i!==ei)});
  const updExtra=(ei,patch)=>setForm(f=>({...f,extras:f.extras.map((e,i)=>i===ei?{...e,...patch}:e)}));

  // timeline editor
  const addStep=()=>upd({timeline:[...(form.timeline||[]),{id:uid2('t'),at:'',title:'',body:'',icon:'check',state:'done'}]});
  const updStep=(i,patch)=>upd({timeline:form.timeline.map((s,j)=>j===i?{...s,...patch}:s)});
  const removeStep=i=>upd({timeline:form.timeline.filter((_,j)=>j!==i)});

  const onPhoto=e=>{
    const files=[...e.target.files];
    files.forEach(f=>fileToThumb(f,url=>setForm(prev=>({...prev,photos:[...(prev.photos||[]),url]}))));
    e.target.value='';
  };
  const removePhoto=i=>upd({photos:form.photos.filter((_,j)=>j!==i)});

  const saveNewCust=()=>{
    if(!nc.name.trim())return;
    const vId=uid2('v');
    const vehicle={id:vId,year:nc.year,make:nc.make,model:nc.model,plate:nc.plate,color:'',vin:''};
    CheoDB.saveCustomerWithVehicles({name:nc.name.trim(),phone:nc.phone.trim(),email:'',address:'',company:false},[vehicle])
      .then(savedCust=>{
        setExtraCusts(prev=>[...prev,{...savedCust,vehicles:[{...vehicle,customer_id:savedCust.id}]}]);
        upd({customer_id:savedCust.id,vehicle_id:vId});
        setNewCustModal(false);
        setNc({name:'',phone:'',year:'',make:'',model:'',plate:''});
      });
  };

  const save=async()=>{
    const entry={...form};
    if(!entry.id){ entry.id=await CheoDB.nextWorkOrderId(); }
    if(!entry.timeline || !entry.timeline.length){
      entry.timeline=[{id:uid2('t'),at:'Hoy '+new Date().toLocaleTimeString('es',{hour:'2-digit',minute:'2-digit'}),title:'Orden creada',body:'Vehículo registrado en el taller.',icon:'check',state:'done'}];
    }
    if(smsToggle && selCust && selCust.phone){
      setSmsSending(true);
      const veh=selCust.vehicles.find(v=>v.id===entry.vehicle_id);
      const msg=buildSmsMsg(entry.status,selCust.name,veh,entry.id||'?',calc(entry).total,settings.shop_name);
      const r=await sendClientSMS(selCust.phone,msg);
      setSmsSending(false);
      setSmsResult(r.success?'ok':'err');
    }
    onSave(entry);
  };

  const th={fontSize:'0.66rem',fontWeight:700,letterSpacing:'0.06em',textTransform:'uppercase',color:C.muted,padding:'6px 8px'};
  const stateColor={done:C.teal,active:C.green,pending:C.muted};

  return (
    <div style={{maxWidth:840,margin:'0 auto',padding:'0 0 4rem'}}>
      <Row style={{marginBottom:'1.5rem'}}>
        <H2 style={{flex:1}}>{form.id?`Orden ${form.id}`:'Nueva Orden de Trabajo'}</H2>
        <Btn variant="ghost" onClick={onCancel} small>Cancelar</Btn>
        <Btn onClick={save}>Guardar Orden</Btn>
      </Row>

      <Card>
        <Grid cols="1fr 1fr 1fr" mCols="1fr" gap="1rem">
          <Field label="Fecha"><TextInput type="date" value={form.date} onChange={e=>upd({date:e.target.value})}/></Field>
          <Field label="Estado">
            <Select value={form.status} onChange={e=>upd({status:e.target.value})}>
              <option value="waiting">En espera</option>
              <option value="in_progress">En reparación</option>
              <option value="ready">Listo para recoger</option>
              <option value="completed">Entregado</option>
              <option value="cancelled">Cancelado</option>
            </Select>
          </Field>
          <Field label="Mecánico"><TextInput value={form.mechanic} onChange={e=>upd({mechanic:e.target.value})}/></Field>
        </Grid>
        <Grid cols="1fr 1fr" mCols="1fr" gap="1rem" style={{marginTop:'1rem'}}>
          <Field label="Cliente">
            <div style={{display:'flex',gap:'0.5rem'}}>
              <Select value={form.customer_id} onChange={e=>upd({customer_id:e.target.value,vehicle_id:''})} style={{flex:1}}>
                <option value="">— Seleccionar cliente —</option>
                {allCustomers.map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
              </Select>
              <button onClick={()=>setNewCustModal(true)} title="Crear nuevo cliente" style={{flexShrink:0,background:C.tealBg,border:`1px solid ${C.teal}55`,color:C.tealL,borderRadius:8,padding:'0 12px',cursor:'pointer',fontWeight:700,fontSize:'0.8rem',display:'flex',alignItems:'center',gap:5,whiteSpace:'nowrap'}}>
                <Icon name="plus" size={13}/> Nuevo
              </button>
            </div>
          </Field>
          <Field label="Vehículo">
            <Select value={form.vehicle_id} onChange={e=>upd({vehicle_id:e.target.value})} disabled={!selCust}>
              <option value="">— Seleccionar vehículo —</option>
              {selCust && selCust.vehicles.map(v=><option key={v.id} value={v.id}>{v.year} {v.make} {v.model}{v.plate?` · ${v.plate}`:''}</option>)}
            </Select>
          </Field>
        </Grid>
      </Card>

      {/* Repairs */}
      <Row style={{marginBottom:'0.75rem',justifyContent:'space-between'}}>
        <H3>Reparaciones</H3><Btn onClick={addRepair} small variant="ghost"><Icon name="plus" size={14}/> Reparación</Btn>
      </Row>
      {form.repairs.map((rep,ri)=>(
        <Card key={rep.id}>
          <Row style={{marginBottom:'1rem'}}>
            <TextInput value={rep.name} onChange={e=>updRepair(ri,{name:e.target.value})} placeholder="Nombre (ej: Reemplazo de Turbo)" style={{flex:1,fontWeight:600}}/>
            {form.repairs.length>1&&<Btn variant="danger" small onClick={()=>removeRepair(ri)}><Icon name="x" size={13}/></Btn>}
          </Row>
          <Label>Piezas / Partes</Label>
          <table style={{width:'100%',borderCollapse:'collapse'}}>
            <thead><tr style={{borderBottom:`1px solid ${C.dark4}`}}>
              <th style={{...th,textAlign:'left',width:'48%'}}>Descripción</th><th style={{...th,width:'12%'}}>Cant.</th>
              <th style={{...th,width:'18%'}}>P/U</th><th style={{...th,width:'16%',textAlign:'right'}}>Total</th><th style={{...th,width:'6%'}}></th>
            </tr></thead>
            <tbody>
              {rep.parts.map((pt,pi)=>(
                <tr key={pt.id}>
                  <td style={{padding:'4px 6px 4px 0'}}><TextInput value={pt.desc} onChange={e=>updPart(ri,pi,{desc:e.target.value})} placeholder="Pieza"/></td>
                  <td style={{padding:'4px'}}><TextInput type="number" min="1" value={pt.qty} onChange={e=>updPart(ri,pi,{qty:Number(e.target.value)})} style={{textAlign:'center'}}/></td>
                  <td style={{padding:'4px'}}><TextInput type="number" step="0.01" value={pt.price} onChange={e=>updPart(ri,pi,{price:e.target.value})} placeholder="0.00" style={{textAlign:'right'}}/></td>
                  <td style={{padding:'4px 0 4px 8px',textAlign:'right',color:C.white,fontWeight:600,fontSize:'0.875rem',whiteSpace:'nowrap'}}>{fmt$(pt.qty*(Number(pt.price)||0))}</td>
                  <td style={{padding:'4px 0 4px 6px'}}><button onClick={()=>removePart(ri,pi)} style={{background:'none',border:'none',color:C.muted,cursor:'pointer',fontSize:'1rem'}}>×</button></td>
                </tr>
              ))}
            </tbody>
          </table>
          <button onClick={()=>addPart(ri)} style={{background:'none',border:`1px dashed ${C.dark4}`,borderRadius:6,color:C.muted,cursor:'pointer',padding:'6px 14px',fontSize:'0.78rem',marginTop:'0.5rem',width:'100%'}}>+ Agregar pieza</button>
          <Row gap="1rem" style={{marginTop:'1rem'}}>
            <div style={{flex:'0 0 200px'}}><Label>Labor / Mano de obra ($)</Label><TextInput type="number" step="0.01" value={rep.labor} onChange={e=>updRepair(ri,{labor:e.target.value})} placeholder="0.00"/></div>
            <div style={{flex:1}}/>
            <div style={{textAlign:'right',paddingTop:'1.2rem'}}>
              <span style={{fontSize:'0.78rem',color:C.muted}}>Subtotal: </span>
              <span style={{fontWeight:700,color:C.white}}>{fmt$(rep.parts.reduce((s,p)=>s+p.qty*(Number(p.price)||0),0)+Number(rep.labor||0))}</span>
            </div>
          </Row>
        </Card>
      ))}

      {/* Extras */}
      <Row style={{marginBottom:'0.75rem',justifyContent:'space-between'}}><H3>Extras / Insumos</H3><Btn onClick={addExtra} small variant="ghost"><Icon name="plus" size={14}/> Extra</Btn></Row>
      <Card>
        {form.extras.length===0&&<p style={{color:C.muted,fontSize:'0.84rem'}}>Sin extras. Agrega spray, guantes, u otro insumo.</p>}
        {form.extras.map((ex,ei)=>(
          <Row key={ex.id} gap="0.75rem" style={{marginBottom:'0.5rem'}}>
            <TextInput value={ex.desc} onChange={e=>updExtra(ei,{desc:e.target.value})} placeholder="Descripción" style={{flex:1}}/>
            <TextInput type="number" step="0.01" value={ex.price} onChange={e=>updExtra(ei,{price:e.target.value})} placeholder="$0.00" style={{width:110,textAlign:'right'}}/>
            <button onClick={()=>removeExtra(ei)} style={{background:'none',border:'none',color:C.muted,cursor:'pointer',fontSize:'1.2rem'}}>×</button>
          </Row>
        ))}
      </Card>

      {/* Photos */}
      <Row style={{marginBottom:'0.75rem',justifyContent:'space-between'}}>
        <H3>Fotos del trabajo</H3>
        <label style={{cursor:'pointer'}}>
          <span style={{display:'inline-flex',alignItems:'center',gap:7,background:'transparent',border:`1px solid ${C.dark4}`,color:C.muted,borderRadius:7,padding:'6px 14px',fontSize:'0.78rem',fontWeight:700}}><Icon name="camera" size={14}/> Subir foto</span>
          <input type="file" accept="image/*" multiple onChange={onPhoto} style={{display:'none'}}/>
        </label>
      </Row>
      <Card>
        {(!form.photos||form.photos.length===0)&&<p style={{color:C.muted,fontSize:'0.84rem'}}>Las fotos que subas aquí se muestran también al cliente en su Portal.</p>}
        {form.photos&&form.photos.length>0&&(
          <div style={{display:'flex',gap:'0.6rem',flexWrap:'wrap'}}>
            {form.photos.map((p,i)=>(
              <div key={i} style={{position:'relative'}}>
                <img src={p} alt="" style={{width:120,height:90,objectFit:'cover',borderRadius:10,border:`1px solid ${C.dark4}`}}/>
                <button onClick={()=>removePhoto(i)} style={{position:'absolute',top:-7,right:-7,width:22,height:22,borderRadius:'50%',background:C.red,color:'#fff',border:'none',cursor:'pointer',fontSize:'0.8rem',display:'flex',alignItems:'center',justifyContent:'center'}}>×</button>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* Timeline editor */}
      <Row style={{marginBottom:'0.75rem',justifyContent:'space-between'}}>
        <H3>Progreso (lo ve el cliente)</H3><Btn onClick={addStep} small variant="ghost"><Icon name="plus" size={14}/> Paso</Btn>
      </Row>
      <Card>
        {(!form.timeline||form.timeline.length===0)&&<p style={{color:C.muted,fontSize:'0.84rem'}}>Agrega pasos para que el cliente siga su reparación en vivo.</p>}
        {form.timeline&&form.timeline.map((s,i)=>(
          <div key={s.id} style={{borderLeft:`3px solid ${stateColor[s.state]}`,paddingLeft:'0.85rem',marginBottom:'0.85rem'}}>
            <Grid cols="120px 1fr 130px auto" mCols="1fr 1fr" gap="0.6rem" style={{alignItems:'center',marginBottom:'0.4rem'}}>
              <TextInput value={s.at} onChange={e=>updStep(i,{at:e.target.value})} placeholder="Hoy 2:00pm"/>
              <TextInput value={s.title} onChange={e=>updStep(i,{title:e.target.value})} placeholder="Título del paso" style={{fontWeight:600}}/>
              <Select value={s.state} onChange={e=>updStep(i,{state:e.target.value,icon:e.target.value==='active'?'wrench':e.target.value==='pending'?'clock':'check'})}>
                <option value="done">Completado</option><option value="active">En progreso</option><option value="pending">Pendiente</option>
              </Select>
              <button onClick={()=>removeStep(i)} style={{background:'none',border:'none',color:C.muted,cursor:'pointer',fontSize:'1.1rem'}}>×</button>
            </Grid>
            <TextInput value={s.body} onChange={e=>updStep(i,{body:e.target.value})} placeholder="Detalle para el cliente"/>
          </div>
        ))}
      </Card>

      {/* SMS toggle */}
      {selCust&&selCust.phone&&(
        <Card style={{background:'oklch(0.14 0.03 196)',border:`1px solid ${smsToggle?C.teal:C.dark3}`}}>
          <Row gap="1rem" style={{alignItems:'flex-start'}}>
            <label style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer',flex:1}}>
              <input type="checkbox" checked={smsToggle} onChange={e=>{setSmsToggle(e.target.checked);setSmsResult(null);}} style={{width:18,height:18,accentColor:C.teal,flexShrink:0}}/>
              <div>
                <div style={{fontWeight:700,color:C.white,fontSize:'0.9rem'}}>Enviar SMS al cliente al guardar</div>
                <div style={{fontSize:'0.78rem',color:C.muted,marginTop:2}}>
                  {['in_progress','ready'].includes(form.status)
                    ? `Se activa automáticamente para "${form.status==='in_progress'?'En reparación':'Listo para recoger'}"`
                    : 'Actívalo manualmente para enviar una actualización'}
                </div>
              </div>
            </label>
            <div style={{textAlign:'right',flexShrink:0}}>
              <div style={{fontSize:'0.75rem',color:C.muted}}>Para:</div>
              <div style={{fontSize:'0.82rem',color:C.tealL,fontWeight:600}}>{selCust.phone}</div>
            </div>
          </Row>
          {smsToggle&&(
            <div style={{marginTop:'0.75rem',padding:'0.65rem 0.85rem',background:'oklch(0.11 0.02 196)',borderRadius:8,fontSize:'0.78rem',color:C.muted,fontStyle:'italic'}}>
              "{buildSmsMsg(form.status,selCust.name,selCust.vehicles.find(v=>v.id===form.vehicle_id),form.id||'#nuevo',calc(form).total,settings.shop_name)}"
            </div>
          )}
          {smsSending&&<div style={{marginTop:'0.5rem',fontSize:'0.78rem',color:C.teal,display:'flex',alignItems:'center',gap:6}}><span style={{animation:'pulse 1s infinite'}}>●</span> Enviando SMS…</div>}
          {smsResult==='ok'&&<div style={{marginTop:'0.5rem',fontSize:'0.78rem',color:C.green}}>✓ SMS enviado correctamente</div>}
          {smsResult==='err'&&<div style={{marginTop:'0.5rem',fontSize:'0.78rem',color:C.red}}>✕ Error al enviar SMS — revisa la configuración de Twilio</div>}
        </Card>
      )}

      {/* Tax + paid + summary */}
      <Card style={{background:C.dark3}}>
        <Row style={{marginBottom:'1rem',flexWrap:'wrap',gap:'1rem'}}>
          <label style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer'}}>
            <input type="checkbox" checked={form.tax_enabled} onChange={e=>upd({tax_enabled:e.target.checked})} style={{width:18,height:18,accentColor:C.teal}}/>
            <span style={{fontWeight:600,color:C.white}}>Aplicar impuesto</span>
          </label>
          {form.tax_enabled&&<Row gap="0.5rem"><TextInput type="number" step="0.01" value={form.tax_rate} onChange={e=>upd({tax_rate:Number(e.target.value)})} style={{width:80,textAlign:'center'}}/><span style={{color:C.muted}}>%</span></Row>}
          <label style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer',marginLeft:'auto'}}>
            <input type="checkbox" checked={form.paid} onChange={e=>upd({paid:e.target.checked})} style={{width:18,height:18,accentColor:C.green}}/>
            <span style={{fontWeight:600,color:form.paid?C.green:C.white}}>Pagado</span>
          </label>
        </Row>
        <div style={{borderTop:`1px solid ${C.dark4}`,paddingTop:'1rem',display:'flex',flexDirection:'column',gap:'0.4rem',alignItems:'flex-end'}}>
          {[['Piezas',tots.parts],['Labor',tots.labor],['Extras',tots.extras]].map(([l,v])=><Row key={l} gap="2rem"><span style={{color:C.muted,fontSize:'0.875rem'}}>{l}</span><span style={{color:C.white,minWidth:72,textAlign:'right'}}>{fmt$(v)}</span></Row>)}
          <Row gap="2rem"><span style={{color:C.muted,fontSize:'0.875rem'}}>Subtotal</span><span style={{color:C.white,fontWeight:600,minWidth:72,textAlign:'right'}}>{fmt$(tots.sub)}</span></Row>
          {form.tax_enabled&&<Row gap="2rem"><span style={{color:C.amber,fontSize:'0.875rem'}}>Impuesto ({form.tax_rate}%)</span><span style={{color:C.amber,minWidth:72,textAlign:'right'}}>{fmt$(tots.tax)}</span></Row>}
          <Row gap="2rem" style={{borderTop:`1px solid ${C.dark4}`,paddingTop:'0.75rem',marginTop:'0.25rem'}}>
            <span style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:700,fontSize:'1.1rem',color:C.white}}>TOTAL</span>
            <span style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:800,fontSize:'1.4rem',color:C.tealL,minWidth:72,textAlign:'right'}}>{fmt$(tots.total)}</span>
          </Row>
        </div>
      </Card>

      <Card><Label>Notas internas</Label><textarea value={form.notes} onChange={e=>upd({notes:e.target.value})} rows={3} placeholder="Observaciones, seguimiento…" style={{...inp,resize:'vertical'}}/></Card>

      <Row style={{justifyContent:'flex-end',gap:'0.75rem'}}><Btn variant="ghost" onClick={onCancel}>Cancelar</Btn><Btn onClick={save}>Guardar Orden de Trabajo</Btn></Row>

      {/* ── NUEVO CLIENTE MODAL ── */}
      {newCustModal&&(
        <div style={{position:'fixed',inset:0,background:'oklch(0 0 0 / .65)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:'1rem'}} onClick={e=>{if(e.target===e.currentTarget)setNewCustModal(false);}}>
          <div style={{background:C.dark2,border:`1px solid ${C.dark3}`,borderRadius:18,padding:'1.75rem',width:'100%',maxWidth:500,maxHeight:'90vh',overflow:'auto',boxShadow:'0 32px 80px oklch(0 0 0 / .5)'}}>
            <Row style={{marginBottom:'1.25rem'}}>
              <H3 style={{flex:1}}>Nuevo Cliente</H3>
              <button onClick={()=>setNewCustModal(false)} style={{background:'none',border:'none',color:C.muted,cursor:'pointer',fontSize:'1.5rem',lineHeight:1,padding:'0 4px'}}>×</button>
            </Row>

            <Grid cols="1fr 1fr" mCols="1fr" gap="0.75rem" style={{marginBottom:'1rem'}}>
              <Field label="Nombre *"><TextInput value={nc.name} onChange={e=>setNc(x=>({...x,name:e.target.value}))} placeholder="María García" autoFocus/></Field>
              <Field label="Teléfono"><TextInput type="tel" value={nc.phone} onChange={e=>setNc(x=>({...x,phone:e.target.value}))} placeholder="407-123-4567"/></Field>
            </Grid>

            <div style={{borderTop:`1px solid ${C.dark4}`,paddingTop:'1rem',marginBottom:'1rem'}}>
              <Label style={{marginBottom:'0.6rem'}}>Vehículo <span style={{fontWeight:400,textTransform:'none',letterSpacing:0}}>(opcional — puedes agregarlo después)</span></Label>
              <Grid cols="1fr 1fr" mCols="1fr" gap="0.75rem">
                <Field label="Año"><TextInput value={nc.year} onChange={e=>setNc(x=>({...x,year:e.target.value}))} placeholder="2020"/></Field>
                <Field label="Marca"><TextInput value={nc.make} onChange={e=>setNc(x=>({...x,make:e.target.value}))} placeholder="Toyota"/></Field>
                <Field label="Modelo"><TextInput value={nc.model} onChange={e=>setNc(x=>({...x,model:e.target.value}))} placeholder="Corolla"/></Field>
                <Field label="Placa"><TextInput value={nc.plate} onChange={e=>setNc(x=>({...x,plate:e.target.value}))} placeholder="ABC-123" style={{fontFamily:'monospace',letterSpacing:'0.05em'}}/></Field>
              </Grid>
            </div>

            <Row style={{justifyContent:'flex-end',gap:'0.75rem'}}>
              <Btn variant="ghost" onClick={()=>setNewCustModal(false)}>Cancelar</Btn>
              <Btn onClick={saveNewCust} disabled={!nc.name.trim()}>Crear y seleccionar</Btn>
            </Row>
          </div>
        </div>
      )}
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────────────────
   ORDERS LIST
─────────────────────────────────────────────────────────────────────────── */
function OrdersView({orders, customers, settings, onSave, onDelete}) {
  const [sub,setSub]=useState(null);
  const custName=id=>{const c=customers.find(c=>c.id===id);return c?c.name:'—';};
  const vehName=(cid,vid)=>{const c=customers.find(x=>x.id===cid);const v=c&&c.vehicles.find(x=>x.id===vid);return v?`${v.year} ${v.make} ${v.model} · ${v.plate}`:'—';};

  if(sub&&sub.mode==='form') return <OrderForm order={sub.order} customers={customers} settings={settings} onCancel={()=>setSub(null)} onSave={o=>{onSave(o);setSub(null);}}/>;
  if(sub&&sub.mode==='detail') return <OrderDetail order={orders.find(o=>o.id===sub.order.id)||sub.order} customers={customers} settings={settings} onBack={()=>setSub(null)} onEdit={()=>setSub({mode:'form',order:orders.find(o=>o.id===sub.order.id)||sub.order})} onSave={onSave} onDelete={()=>{onDelete(sub.order.id);setSub(null);}}/>;

  const today=new Date().toISOString().slice(0,10);
  const active=orders.filter(o=>['waiting','in_progress','ready'].includes(o.status));
  const done=orders.filter(o=>['completed','cancelled'].includes(o.status));

  const list=(title,arr)=>arr.length>0&&(
    <div style={{marginBottom:'1.5rem'}}>
      <div style={{fontSize:'0.72rem',fontWeight:700,letterSpacing:'0.1em',textTransform:'uppercase',color:C.muted,marginBottom:'0.75rem'}}>{title}</div>
      {arr.map(o=>{const tots=calc(o);return (
        <div key={o.id} onClick={()=>setSub({mode:'detail',order:o})} style={{background:C.dark2,border:`1px solid ${C.dark3}`,borderRadius:12,padding:'1rem 1.25rem',marginBottom:'0.5rem',cursor:'pointer',transition:'border-color .2s',display:'grid',gridTemplateColumns:'auto 1fr auto auto',gap:'1rem',alignItems:'center'}} onMouseEnter={e=>e.currentTarget.style.borderColor=C.teal} onMouseLeave={e=>e.currentTarget.style.borderColor=C.dark3}>
          <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:700,fontSize:'1rem',color:C.tealL,minWidth:74}}>{o.id}</div>
          <div><div style={{fontWeight:600,color:C.white,marginBottom:2}}>{custName(o.customer_id)}</div><div style={{fontSize:'0.8rem',color:C.muted}}>{vehName(o.customer_id,o.vehicle_id)}</div></div>
          <Row gap="0.5rem">{!o.paid&&['completed'].includes(o.status)&&<Tag label="Por pagar" color={C.amber}/>}<Tag label={statusLabel(o.status)} color={statusColor(o.status)}/></Row>
          <div style={{textAlign:'right'}}><div style={{fontWeight:700,color:C.white}}>{fmt$(tots.total)}</div><div style={{fontSize:'0.75rem',color:C.muted}}>{dateStr(o.date)}</div></div>
        </div>
      );})}
    </div>
  );

  return (
    <div>
      <Row style={{marginBottom:'1.5rem'}}><H2 style={{flex:1}}>Órdenes de Trabajo</H2><Btn onClick={()=>setSub({mode:'form',order:null})}><Icon name="plus" size={15}/> Nueva Orden</Btn></Row>
      <Grid cols="repeat(3,1fr)" gap="1rem" style={{marginBottom:'1.5rem'}}>
        <Stat label="Activas" value={active.length} color={C.teal}/>
        <Stat label={`Hoy`} value={orders.filter(o=>o.date===today).length} color={C.amber}/>
        <Stat label="Entregadas" value={done.length} color={C.green}/>
      </Grid>
      {list('Activas',active)}
      {list('Historial',done)}
      {orders.length===0&&<Card><p style={{color:C.muted,textAlign:'center',padding:'1rem'}}>No hay órdenes todavía. Crea la primera con “Nueva Orden”.</p></Card>}
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────────────────
   ORDER DETAIL / INVOICE
─────────────────────────────────────────────────────────────────────────── */
function OrderDetail({order, customers, settings, onBack, onEdit, onSave, onDelete}) {
  const cust=customers.find(c=>c.id===order.customer_id);
  const veh=cust&&cust.vehicles.find(v=>v.id===order.vehicle_id);
  const tots=calc(order);
  const phone=(cust&&cust.phone||'').replace(/\D/g,'');
  const waPhone=phone.length===10?'1'+phone:phone;
  const [smsBusy,setSmsBusy]=useState(false);
  const [smsOk,setSmsOk]=useState(null);
  const doSendSMS=async()=>{
    if(!cust||!cust.phone)return;
    setSmsBusy(true);setSmsOk(null);
    const msg=buildSmsMsg(order.status,cust.name,veh,order.id,tots.total,settings.shop_name);
    const r=await sendClientSMS(cust.phone,msg);
    setSmsBusy(false);setSmsOk(r.success?true:false);
  };

  const statusMsg={
    waiting:'está en espera de diagnóstico',in_progress:'está en reparación',
    ready:'¡ya está listo para recoger!',completed:'fue entregado',cancelled:'fue cancelado'
  }[order.status];
  const updateText=`Hola${cust?' '+cust.name.split(' ')[0]:''}, soy de ${settings.shop_name}. Tu ${veh?veh.year+' '+veh.make+' '+veh.model:'vehículo'} (orden ${order.id}) ${statusMsg}. Total: ${fmt$(tots.total)}. Sigue el detalle en tu portal. ¡Gracias!`;
  const reviewText=`Hola${cust?' '+cust.name.split(' ')[0]:''}, gracias por confiar en ${settings.shop_name}. Si quedaste satisfecho, ¿nos dejarías una reseña de 5 estrellas? Significa mucho para el taller. 🙏`;

  const markPaid=()=>{
    const o={...order,paid:true};
    onSave(o,{addIncome:true});
  };

  const s={row:{display:'flex',justifyContent:'space-between',padding:'5px 0',fontSize:'0.875rem'}};
  return (
    <div style={{maxWidth:680,margin:'0 auto',padding:'0 0 4rem'}}>
      <Row style={{marginBottom:'1.25rem',flexWrap:'wrap',gap:'0.5rem'}} className="no-print">
        <Btn variant="ghost" onClick={onBack} small><Icon name="back" size={14}/> Volver</Btn>
        <div style={{flex:1}}/>
        {waPhone&&<a href={`https://wa.me/${waPhone}?text=${encodeURIComponent(updateText)}`} target="_blank" rel="noopener" style={{textDecoration:'none'}}><Btn variant="success" small><Icon name="chat" size={14}/> WhatsApp</Btn></a>}
        {phone&&<Btn variant="ghost" small onClick={doSendSMS} disabled={smsBusy}>{smsBusy?'Enviando…':smsOk===true?'✓ SMS enviado':smsOk===false?'✕ Error SMS':'Enviar SMS'}</Btn>}
        <Btn variant="ghost" onClick={()=>window.print()} small><Icon name="print" size={14}/> Imprimir</Btn>
        <Btn onClick={onEdit} small>Editar</Btn>
      </Row>

      <div id="invoice">
        <Card>
          <div style={{textAlign:'center',borderBottom:`1px solid ${C.dark4}`,paddingBottom:'1rem',marginBottom:'1rem'}}>
            <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:900,fontSize:'1.9rem',color:C.white}}>CHEO<span style={{color:C.teal}}>AUTO</span> REPAIR</div>
            <div style={{fontSize:'0.8rem',color:C.muted,marginTop:4}}>{settings.address} · {settings.phone}</div>
          </div>
          <Grid cols="1fr 1fr" gap="1rem" style={{marginBottom:'1rem'}}>
            <div><Label>Cliente</Label><div style={{fontWeight:600,color:C.white}}>{cust?cust.name:'—'}</div><div style={{fontSize:'0.82rem',color:C.muted}}>{cust&&cust.phone}</div></div>
            <div><Label>Vehículo</Label><div style={{fontWeight:600,color:C.white}}>{veh?`${veh.year} ${veh.make} ${veh.model}`:'—'}</div><div style={{fontSize:'0.82rem',color:C.muted,fontFamily:'monospace',letterSpacing:'0.06em'}}>{veh&&veh.plate}</div></div>
            <div><Label>Orden #</Label><div style={{color:C.tealL,fontWeight:700}}>{order.id}</div></div>
            <div><Label>Fecha</Label><div style={{color:C.white}}>{dateStr(order.date)}</div></div>
          </Grid>
          <Row gap="0.5rem"><Tag label={statusLabel(order.status)} color={statusColor(order.status)}/><Tag label={order.paid?'Pagado':'Por pagar'} color={order.paid?C.green:C.amber}/></Row>
        </Card>

        {order.repairs.map((rep,ri)=>(
          <Card key={rep.id}>
            <div style={{fontWeight:700,color:C.white,marginBottom:'1rem'}}>🔧 {rep.name||`Reparación ${ri+1}`}</div>
            <table style={{width:'100%',borderCollapse:'collapse'}}>
              <thead><tr style={{borderBottom:`1px solid ${C.dark4}`}}>
                <th style={{textAlign:'left',padding:'5px 0',fontSize:'0.66rem',fontWeight:700,letterSpacing:'0.06em',textTransform:'uppercase',color:C.muted}}>Pieza</th>
                <th style={{textAlign:'center',padding:'5px 8px',fontSize:'0.66rem',fontWeight:700,textTransform:'uppercase',color:C.muted,width:50}}>Cant.</th>
                <th style={{textAlign:'right',padding:'5px 0',fontSize:'0.66rem',fontWeight:700,textTransform:'uppercase',color:C.muted,width:90}}>P/U</th>
                <th style={{textAlign:'right',padding:'5px 0 5px 16px',fontSize:'0.66rem',fontWeight:700,textTransform:'uppercase',color:C.muted,width:90}}>Total</th>
              </tr></thead>
              <tbody>
                {rep.parts.map(pt=>(
                  <tr key={pt.id} style={{borderBottom:`1px solid ${C.dark3}`}}>
                    <td style={{padding:'7px 0',color:C.white,fontSize:'0.875rem'}}>{pt.desc}</td>
                    <td style={{textAlign:'center',padding:'7px 8px',color:C.muted,fontSize:'0.875rem'}}>{pt.qty}</td>
                    <td style={{textAlign:'right',padding:'7px 0',color:C.muted,fontSize:'0.875rem'}}>{fmt$(pt.price)}</td>
                    <td style={{textAlign:'right',padding:'7px 0 7px 16px',color:C.white,fontWeight:600,fontSize:'0.875rem'}}>{fmt$(pt.qty*(Number(pt.price)||0))}</td>
                  </tr>
                ))}
                <tr><td colSpan={3} style={{padding:'7px 0',color:C.muted,fontSize:'0.875rem'}}>Labor / Mano de obra</td><td style={{textAlign:'right',padding:'7px 0 7px 16px',color:C.white,fontWeight:600,fontSize:'0.875rem'}}>{fmt$(rep.labor||0)}</td></tr>
              </tbody>
            </table>
          </Card>
        ))}

        {order.extras.length>0&&<Card><div style={{fontWeight:700,color:C.white,marginBottom:'0.75rem'}}>Extras / Insumos</div>{order.extras.map(ex=><div key={ex.id} style={{...s.row,color:C.muted}}><span>{ex.desc}</span><span style={{color:C.white}}>{fmt$(ex.price)}</span></div>)}</Card>}

        <Card style={{background:C.dark3}}>
          {[['Piezas',tots.parts],['Labor',tots.labor],['Extras',tots.extras]].map(([l,v])=><div key={l} style={{...s.row,color:C.muted}}><span>{l}</span><span style={{color:C.white}}>{fmt$(v)}</span></div>)}
          <div style={{...s.row,fontWeight:600,color:C.white,borderTop:`1px solid ${C.dark4}`,paddingTop:8,marginTop:4}}><span>Subtotal</span><span>{fmt$(tots.sub)}</span></div>
          {order.tax_enabled&&<div style={{...s.row,color:C.amber}}><span>Impuesto ({order.tax_rate}%)</span><span>{fmt$(tots.tax)}</span></div>}
          <div style={{display:'flex',justifyContent:'space-between',borderTop:`1px solid ${C.dark4}`,paddingTop:10,marginTop:6}}>
            <span style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:700,fontSize:'1.2rem',color:C.white}}>TOTAL</span>
            <span style={{fontFamily:"'Barlow Condensed',sans-serif",fontWeight:800,fontSize:'1.5rem',color:C.tealL}}>{fmt$(tots.total)}</span>
          </div>
        </Card>

        {order.notes&&<Card><Label>Notas</Label><p style={{color:C.muted,fontSize:'0.875rem',lineHeight:1.65}}>{order.notes}</p></Card>}
        <div style={{textAlign:'center',color:C.muted,fontSize:'0.78rem',marginTop:'0.5rem'}}>Gracias por confiar en {settings.shop_name}. Garantía en mano de obra. {settings.phone}</div>
      </div>

      <Row style={{marginTop:'1.5rem',gap:'0.75rem',flexWrap:'wrap'}} className="no-print">
        {!order.paid&&<Btn variant="success" onClick={markPaid}><Icon name="check" size={15}/> Marcar Pagado{tots.total?` · ${fmt$(tots.total)}`:''}</Btn>}
        {waPhone&&<a href={`https://wa.me/${waPhone}?text=${encodeURIComponent(reviewText)}`} target="_blank" rel="noopener" style={{textDecoration:'none'}}><Btn variant="ghost"><Icon name="star" size={14}/> Pedir reseña</Btn></a>}
        <div style={{flex:1}}/>
        <Btn variant="danger" onClick={()=>{if(confirm('¿Eliminar esta orden?'))onDelete();}}>Eliminar</Btn>
      </Row>
    </div>
  );
}

Object.assign(window, { OrdersView });
})();
