// WorkOrders.jsx
'use strict';
const { useState, useEffect, useRef } = React;

const STATUSES = ['Aberta','Em andamento','Aguardando peça','Concluída','Entregue'];
const EQUIP_TYPES = ['Smartphone','Notebook','Desktop','Tablet','TV','Impressora','Outro'];
const equipIcon = { Smartphone:'Smartphone', Notebook:'Laptop', Desktop:'Monitor', TV:'Tv', Tablet:'Smartphone' };

// ── Print Template ──────────────────────────────────────────────────────────
function PrintOS({ os, company }) {
  if (!os) return null;
  const c = company || {};
  const printNode = (
    <div className="print-only" style={{ fontFamily:'Inter,system-ui,sans-serif', color:'#1E293B' }}>
      {/* Header */}
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:24, paddingBottom:18, marginBottom:22, borderBottom:'3px solid #0A1F44', position:'relative' }}>
        <div style={{ position:'absolute', left:0, right:0, bottom:-3, height:3, background:'linear-gradient(90deg, #FF6B35 0%, #FF6B35 18%, transparent 18%)' }} />
        <div style={{ flex:1, minWidth:0 }}>
          <img src="assets/juflow-logo-print.png" alt={c.name || 'Logo'} style={{ height:56, width:'auto', maxWidth:280, objectFit:'contain', display:'block', marginBottom:10 }} />
          <div style={{ fontSize:11, color:'#475569', lineHeight:1.65 }}>
            {c.cnpj && <div><b style={{ color:'#0A1F44' }}>CNPJ:</b> {c.cnpj}</div>}
            {c.address && <div>{c.address}</div>}
            <div style={{ marginTop:4, color:'#64748b' }}>
              {[c.phone, c.email, c.website].filter(Boolean).join(' • ')}
            </div>
          </div>
        </div>
        <div style={{ textAlign:'right', flexShrink:0 }}>
          <div style={{ fontSize:10, color:'#94a3b8', marginBottom:2, letterSpacing:'0.18em', fontWeight:700 }}>ORDEM DE SERVIÇO</div>
          <div style={{ fontSize:38, fontWeight:900, color:'#FF6B35', lineHeight:1 }}>#{os.num}</div>
          <div style={{ display:'inline-block', marginTop:10, padding:'8px 12px', background:'#F8FAFC', borderRadius:8, fontSize:11, color:'#475569', textAlign:'left', minWidth:160 }}>
            <div style={{ display:'flex', justifyContent:'space-between', gap:16 }}><span style={{ color:'#94a3b8' }}>Entrada</span><b style={{ color:'#0A1F44' }}>{fmtDate(os.entryDate)}</b></div>
            <div style={{ display:'flex', justifyContent:'space-between', gap:16, marginTop:3 }}><span style={{ color:'#94a3b8' }}>Prazo</span><b style={{ color:'#0A1F44' }}>{fmtDate(os.deadline)}</b></div>
            <div style={{ display:'flex', justifyContent:'space-between', gap:16, marginTop:3 }}><span style={{ color:'#94a3b8' }}>Status</span><b style={{ color:'#FF6B35' }}>{os.status}</b></div>
          </div>
        </div>
      </div>

      {/* Client + Equipment */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, marginBottom:24 }}>
        <div style={{ background:'#F8FAFC', borderRadius:12, padding:16 }}>
          <div style={{ fontWeight:700, fontSize:12, color:'#0A1F44', marginBottom:10, textTransform:'uppercase', letterSpacing:'0.05em' }}>Dados do Cliente</div>
          <div style={{ fontSize:12, lineHeight:1.8 }}>
            <div><b>Nome:</b> {os.clientName}</div>
            <div><b>Telefone:</b> {os.clientPhone||'—'}</div>
            <div><b>E-mail:</b> {os.clientEmail||'—'}</div>
          </div>
        </div>
        <div style={{ background:'#F8FAFC', borderRadius:12, padding:16 }}>
          <div style={{ fontWeight:700, fontSize:12, color:'#0A1F44', marginBottom:10, textTransform:'uppercase', letterSpacing:'0.05em' }}>Dados do Equipamento</div>
          <div style={{ fontSize:12, lineHeight:1.8 }}>
            <div><b>Tipo:</b> {os.equipment?.type}</div>
            <div><b>Marca/Modelo:</b> {os.equipment?.brand} {os.equipment?.model}</div>
            <div><b>Série:</b> {os.equipment?.serial||'—'}</div>
            <div><b>Acessórios:</b> {os.equipment?.accessories||'—'}</div>
          </div>
        </div>
      </div>

      {/* Defect + Diagnosis */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, marginBottom:24 }}>
        <div>
          <div style={{ fontWeight:700, fontSize:12, color:'#0A1F44', marginBottom:8, textTransform:'uppercase', letterSpacing:'0.05em' }}>Defeito Relatado</div>
          <div style={{ fontSize:12, lineHeight:1.7, color:'#374151', background:'#FEF9F6', border:'1px solid #FDBA8C', borderRadius:8, padding:12 }}>{os.defect||'—'}</div>
        </div>
        <div>
          <div style={{ fontWeight:700, fontSize:12, color:'#0A1F44', marginBottom:8, textTransform:'uppercase', letterSpacing:'0.05em' }}>Diagnóstico Técnico</div>
          <div style={{ fontSize:12, lineHeight:1.7, color:'#374151', background:'#F0FDF4', border:'1px solid #86EFAC', borderRadius:8, padding:12 }}>{os.diagnosis||'—'}</div>
        </div>
      </div>

      {/* Items table */}
      <div style={{ marginBottom:24 }}>
        <div style={{ fontWeight:700, fontSize:12, color:'#0A1F44', marginBottom:10, textTransform:'uppercase', letterSpacing:'0.05em' }}>Serviços e Peças</div>
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
          <thead>
            <tr style={{ background:'#0A1F44', color:'white' }}>
              <th style={{ padding:'8px 12px', textAlign:'left' }}>Descrição</th>
              <th style={{ padding:'8px 12px', textAlign:'center', width:60 }}>Qtd.</th>
              <th style={{ padding:'8px 12px', textAlign:'right', width:100 }}>Valor Unit.</th>
              <th style={{ padding:'8px 12px', textAlign:'right', width:100 }}>Total</th>
            </tr>
          </thead>
          <tbody>
            {(os.items||[]).map((item,i) => (
              <tr key={i} style={{ background: i%2===0?'white':'#F8FAFC' }}>
                <td style={{ padding:'7px 12px', borderBottom:'1px solid #E2E8F0' }}>{item.desc}</td>
                <td style={{ padding:'7px 12px', textAlign:'center', borderBottom:'1px solid #E2E8F0' }}>{item.qty}</td>
                <td style={{ padding:'7px 12px', textAlign:'right', borderBottom:'1px solid #E2E8F0' }}>{fmtCurrency(item.unit)}</td>
                <td style={{ padding:'7px 12px', textAlign:'right', borderBottom:'1px solid #E2E8F0' }}>{fmtCurrency(item.total)}</td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr style={{ background:'#F8FAFC', fontWeight:700 }}>
              <td colSpan={3} style={{ padding:'10px 12px', textAlign:'right', color:'#0A1F44' }}>TOTAL GERAL</td>
              <td style={{ padding:'10px 12px', textAlign:'right', color:'#FF6B35', fontSize:15 }}>{fmtCurrency(os.total||0)}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      {/* Signature + Footer */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:40, marginTop:40 }}>
        <div style={{ borderTop:'2px solid #CBD5E1', paddingTop:8, textAlign:'center' }}>
          <div style={{ fontSize:11, color:'#94a3b8' }}>Assinatura do Cliente</div>
        </div>
        <div style={{ borderTop:'2px solid #CBD5E1', paddingTop:8, textAlign:'center' }}>
          <div style={{ fontSize:11, color:'#94a3b8' }}>Assinatura do Técnico — {os.tech}</div>
        </div>
      </div>
      <div style={{ marginTop:30, paddingTop:16, borderTop:'1px solid #E2E8F0', fontSize:10, color:'#94a3b8', textAlign:'center', lineHeight:1.7 }}>
        Ao assinar este documento, o cliente declara estar ciente dos serviços realizados e concorda com os valores cobrados.
        {c.terms && <><br/>{c.terms}</>}
        <div style={{ marginTop:8, color:'#cbd5e1' }}>
          {[c.name, c.cnpj && ('CNPJ ' + c.cnpj), c.email, c.phone].filter(Boolean).join(' • ')}
        </div>
      </div>
    </div>
  );
  return ReactDOM.createPortal(printNode, document.body);
}

// ── OS Modal (create/edit) ──────────────────────────────────────────────────
function OSModal({ open, onClose, onSave, clients, services, editOS }) {
  const empty = { clientId:'', clientName:'', clientPhone:'', clientEmail:'',
    equipment:{ type:'Smartphone', brand:'', model:'', serial:'', password:'', accessories:'' },
    defect:'', diagnosis:'', items:[], status:'Aberta', entryDate:new Date().toISOString().split('T')[0],
    deadline:'', notes:'', tech:'Carlos Ferreira' };
  const [form, setForm]  = useState(empty);
  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (open) setForm(editOS ? { ...editOS } : { ...empty, items:[] });
  }, [open, editOS]);

  const set = (key, val) => setForm(f => ({ ...f, [key]: val }));
  const setEquip = (key, val) => setForm(f => ({ ...f, equipment: { ...f.equipment, [key]: val } }));

  const addItem = () => setForm(f => ({ ...f, items:[...f.items,{ desc:'', qty:1, unit:0, total:0 }] }));
  const removeItem = i => setForm(f => ({ ...f, items: f.items.filter((_,idx)=>idx!==i) }));
  const setItem = (i, key, val) => setForm(f => {
    const items = f.items.map((item, idx) => {
      if (idx !== i) return item;
      const updated = { ...item, [key]: key==='qty'||key==='unit' ? parseFloat(val)||0 : val };
      updated.total = updated.qty * updated.unit;
      return updated;
    });
    return { ...f, items };
  });

  const total = form.items.reduce((s,i) => s + (i.total||0), 0);

  const onClientChange = id => {
    const c = clients.find(x => x.id === id);
    if (c) set('clientId', id); setForm(f=>({...f, clientId:id, clientName:c?.name||'', clientPhone:c?.phone||'', clientEmail:c?.email||''}));
  };

  const addServiceItem = svcId => {
    const s = services.find(x => x.id === svcId);
    if (!s) return;
    setForm(f=>({...f, items:[...f.items,{ desc:s.name, qty:1, unit:s.basePrice, total:s.basePrice }]}));
  };

  const validate = () => {
    const e = {};
    if (!form.clientId) e.clientId = 'Selecione um cliente';
    if (!form.equipment.brand) e.brand = 'Informe a marca';
    if (!form.equipment.model) e.model = 'Informe o modelo';
    if (!form.defect) e.defect = 'Descreva o defeito';
    if (!form.deadline) e.deadline = 'Informe o prazo';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSave = (print=false) => {
    if (!validate()) return;
    onSave({ ...form, total }, print);
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} title={editOS ? `Editar OS #${editOS.num}` : 'Nova Ordem de Serviço'} width="max-w-4xl">
      <div className="space-y-6">
        {/* Client */}
        <section>
          <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 mb-3">Cliente</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <FormField label="Cliente" required error={errors.clientId} className="md:col-span-1">
              <Select value={form.clientId} onChange={e=>onClientChange(e.target.value)} error={!!errors.clientId}>
                <option value="">Selecionar cliente...</option>
                {clients.map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
              </Select>
            </FormField>
            <FormField label="Telefone"><Input value={form.clientPhone} onChange={e=>set('clientPhone',e.target.value)} placeholder="(11) 99999-9999"/></FormField>
            <FormField label="E-mail"><Input value={form.clientEmail} onChange={e=>set('clientEmail',e.target.value)} placeholder="cliente@email.com"/></FormField>
          </div>
        </section>

        {/* Equipment */}
        <section>
          <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400 mb-3">Equipamento</h3>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            <FormField label="Tipo"><Select value={form.equipment.type} onChange={e=>setEquip('type',e.target.value)}>{EQUIP_TYPES.map(t=><option key={t}>{t}</option>)}</Select></FormField>
            <FormField label="Marca" required error={errors.brand}><Input value={form.equipment.brand} onChange={e=>setEquip('brand',e.target.value)} placeholder="Samsung, Apple..."/></FormField>
            <FormField label="Modelo" required error={errors.model}><Input value={form.equipment.model} onChange={e=>setEquip('model',e.target.value)} placeholder="Galaxy S23..."/></FormField>
            <FormField label="Nº de Série"><Input value={form.equipment.serial} onChange={e=>setEquip('serial',e.target.value)} placeholder="SN123456"/></FormField>
            <FormField label="Senha/Padrão"><Input value={form.equipment.password} onChange={e=>setEquip('password',e.target.value)} placeholder="1234"/></FormField>
            <FormField label="Acessórios"><Input value={form.equipment.accessories} onChange={e=>setEquip('accessories',e.target.value)} placeholder="Carregador, capa..."/></FormField>
          </div>
        </section>

        {/* Defect + Diagnosis */}
        <section>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField label="Defeito Relatado pelo Cliente" required error={errors.defect}>
              <Textarea rows={3} value={form.defect} onChange={e=>set('defect',e.target.value)} placeholder="Descreva o problema relatado pelo cliente..."/>
            </FormField>
            <FormField label="Diagnóstico Técnico">
              <Textarea rows={3} value={form.diagnosis} onChange={e=>set('diagnosis',e.target.value)} placeholder="Diagnóstico após avaliação técnica..."/>
            </FormField>
          </div>
        </section>

        {/* Items */}
        <section>
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-bold uppercase tracking-wider text-slate-400">Serviços e Peças</h3>
            <div className="flex gap-2">
              <Select className="w-48 text-xs py-1.5" onChange={e=>{addServiceItem(e.target.value);e.target.value=''}}>
                <option value="">+ Adicionar do catálogo</option>
                {services.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}
              </Select>
              <Btn size="sm" icon="Plus" onClick={addItem} variant="outline">Item manual</Btn>
            </div>
          </div>
          <div className="border border-slate-200 rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead><tr className="bg-slate-50 border-b border-slate-100">
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-400 uppercase">Descrição</th>
                <th className="px-3 py-2 text-center text-xs font-semibold text-slate-400 uppercase w-20">Qtd.</th>
                <th className="px-3 py-2 text-right text-xs font-semibold text-slate-400 uppercase w-32">Val. Unit. (R$)</th>
                <th className="px-3 py-2 text-right text-xs font-semibold text-slate-400 uppercase w-28">Total</th>
                <th className="w-10"/>
              </tr></thead>
              <tbody>
                {form.items.length === 0
                  ? <tr><td colSpan={5} className="px-4 py-6 text-center text-sm text-slate-300">Nenhum item adicionado — use o catálogo ou clique em "Item manual"</td></tr>
                  : form.items.map((item,i)=>(
                    <tr key={i} className="border-b border-slate-50">
                      <td className="px-2 py-1.5"><Input value={item.desc} onChange={e=>setItem(i,'desc',e.target.value)} placeholder="Descrição do serviço ou peça"/></td>
                      <td className="px-2 py-1.5"><Input type="number" min="1" value={item.qty} onChange={e=>setItem(i,'qty',e.target.value)} className="text-center"/></td>
                      <td className="px-2 py-1.5"><Input type="number" min="0" step="0.01" value={item.unit} onChange={e=>setItem(i,'unit',e.target.value)} className="text-right"/></td>
                      <td className="px-3 py-1.5 text-right font-semibold text-slate-700">{fmtCurrency(item.total)}</td>
                      <td className="px-2 py-1.5"><button onClick={()=>removeItem(i)} className="p-1 rounded-lg text-red-400 hover:bg-red-50 hover:text-red-600 transition-colors"><Icon name="Trash2" size={14}/></button></td>
                    </tr>
                  ))
                }
              </tbody>
              <tfoot>
                <tr className="bg-slate-50">
                  <td colSpan={3} className="px-3 py-2.5 text-right text-sm font-bold" style={{ color:'#0A1F44' }}>Total Geral</td>
                  <td className="px-3 py-2.5 text-right text-base font-bold" style={{ color:'#FF6B35' }}>{fmtCurrency(total)}</td>
                  <td/>
                </tr>
              </tfoot>
            </table>
          </div>
        </section>

        {/* Status + deadline */}
        <section>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <FormField label="Status">
              <Select value={form.status} onChange={e=>set('status',e.target.value)}>
                {STATUSES.map(s=><option key={s}>{s}</option>)}
              </Select>
            </FormField>
            <FormField label="Entrada"><Input type="date" value={form.entryDate} onChange={e=>set('entryDate',e.target.value)}/></FormField>
            <FormField label="Prazo Previsto" required error={errors.deadline}><Input type="date" value={form.deadline} onChange={e=>set('deadline',e.target.value)}/></FormField>
            <FormField label="Técnico Responsável">
              <Select value={form.tech} onChange={e=>set('tech',e.target.value)}>
                {['Carlos Ferreira','Ana Paula Souza','Ricardo Alves'].map(t=><option key={t}>{t}</option>)}
              </Select>
            </FormField>
          </div>
          <div className="mt-4">
            <FormField label="Observações"><Textarea rows={2} value={form.notes} onChange={e=>set('notes',e.target.value)} placeholder="Informações adicionais..."/></FormField>
          </div>
        </section>

        {/* Actions */}
        <div className="flex flex-col sm:flex-row gap-3 pt-2 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="sm:mr-auto">Cancelar</Btn>
          <Btn variant="ghost" icon="Printer" onClick={()=>handleSave(true)}>Salvar e Imprimir</Btn>
          <Btn icon="Save" onClick={()=>handleSave(false)}>Salvar OS</Btn>
        </div>
      </div>
    </Modal>
  );
}

// ── OS Detail Modal ────────────────────────────────────────────────────────
function OSDetailModal({ open, onClose, os, onPrint, onEdit, onDelete }) {
  if (!os) return null;
  return (
    <Modal open={open} onClose={onClose} title={`Ordem de Serviço #${os.num}`} width="max-w-2xl">
      <div className="space-y-5">
        <div className="flex flex-wrap gap-3">
          <StatusBadge status={os.status}/>
          <span className="text-sm text-slate-400">Entrada: {fmtDate(os.entryDate)}</span>
          <span className="text-sm text-slate-400">Prazo: {fmtDate(os.deadline)}</span>
          <span className="text-sm text-slate-400">Técnico: {os.tech}</span>
        </div>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div className="p-4 rounded-xl" style={{background:'#F8FAFC'}}>
            <p className="text-xs font-bold text-slate-400 uppercase mb-2">Cliente</p>
            <p className="font-semibold" style={{color:'#0A1F44'}}>{os.clientName}</p>
            {os.clientPhone && <p className="text-slate-500">{os.clientPhone}</p>}
          </div>
          <div className="p-4 rounded-xl" style={{background:'#F8FAFC'}}>
            <p className="text-xs font-bold text-slate-400 uppercase mb-2">Equipamento</p>
            <p className="font-semibold" style={{color:'#0A1F44'}}>{os.equipment?.brand} {os.equipment?.model}</p>
            <p className="text-slate-500">{os.equipment?.type} • Série: {os.equipment?.serial||'—'}</p>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div><p className="text-xs font-bold text-slate-400 uppercase mb-1">Defeito</p><p className="text-slate-700">{os.defect||'—'}</p></div>
          <div><p className="text-xs font-bold text-slate-400 uppercase mb-1">Diagnóstico</p><p className="text-slate-700">{os.diagnosis||'—'}</p></div>
        </div>
        <div className="border border-slate-100 rounded-xl overflow-hidden">
          <table className="w-full text-sm"><thead><tr className="bg-slate-50"><th className="px-4 py-2 text-left text-xs font-semibold text-slate-400">Descrição</th><th className="px-4 py-2 text-center text-xs font-semibold text-slate-400 w-16">Qtd.</th><th className="px-4 py-2 text-right text-xs font-semibold text-slate-400 w-28">Total</th></tr></thead>
            <tbody>{(os.items||[]).map((item,i)=><tr key={i} className="border-t border-slate-50"><td className="px-4 py-2.5">{item.desc}</td><td className="px-4 py-2.5 text-center">{item.qty}</td><td className="px-4 py-2.5 text-right font-medium">{fmtCurrency(item.total)}</td></tr>)}</tbody>
            <tfoot><tr className="bg-slate-50 border-t border-slate-100"><td colSpan={2} className="px-4 py-2.5 text-right font-bold" style={{color:'#0A1F44'}}>Total</td><td className="px-4 py-2.5 text-right text-base font-bold" style={{color:'#FF6B35'}}>{fmtCurrency(os.total||0)}</td></tr></tfoot>
          </table>
        </div>
        {os.notes && <div className="p-3 rounded-xl bg-amber-50 text-sm text-amber-800"><b>Obs:</b> {os.notes}</div>}
        <div className="flex flex-wrap gap-2 pt-3 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="sm:mr-auto">Fechar</Btn>
          <Btn variant="ghost" icon="Trash2" onClick={()=>{ if (onDelete){ onClose(); onDelete(os); } }} className="text-red-500 hover:bg-red-50">Excluir</Btn>
          <Btn variant="ghost" icon="Edit" onClick={()=>{onClose();onEdit(os);}}>Editar</Btn>
          <Btn icon="Printer" onClick={()=>onPrint(os)}>Imprimir PDF</Btn>
        </div>
      </div>
    </Modal>
  );
}

// ── WorkOrders Page ────────────────────────────────────────────────────────
function WorkOrders({ workOrders, clients, services, company, onAdd, onUpdate, onDelete, addToast }) {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('Todos');
  const [showModal, setShowModal]   = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const [editOS, setEditOS]         = useState(null);
  const [detailOS, setDetailOS]     = useState(null);
  const [printOS, setPrintOS]       = useState(null);
  const [confirm, setConfirm]       = useState(null);
  const [loading, setLoading]       = useState(true);

  useEffect(() => { const t = setTimeout(()=>setLoading(false), 600); return ()=>clearTimeout(t); }, []);
  useEffect(() => { if (printOS) { const t = setTimeout(()=>{ window.print(); setPrintOS(null); },150); return()=>clearTimeout(t); } }, [printOS]);

  const filtered = workOrders.filter(o => {
    const q = search.toLowerCase();
    const matchQ = !q || o.num?.includes(q) || o.clientName?.toLowerCase().includes(q) || o.equipment?.brand?.toLowerCase().includes(q) || o.equipment?.model?.toLowerCase().includes(q);
    const matchS = statusFilter==='Todos' || o.status===statusFilter;
    return matchQ && matchS;
  }).sort((a,b) => b.num?.localeCompare(a.num));

  const handleSave = (data, print) => {
    if (editOS) { onUpdate(editOS.id, { ...data }); addToast({ type:'success', msg:`OS #${editOS.num} atualizada!` }); }
    else {
      const id = 'OS-' + String(workOrders.length+1).padStart(4,'0');
      const num = String(workOrders.length+1).padStart(4,'0');
      const full = { ...data, id, num };
      onAdd(full);
      addToast({ type:'success', msg:`OS #${num} criada com sucesso!` });
      if (print) setTimeout(()=>setPrintOS(full),200);
    }
  };

  const handlePrint = os => { setPrintOS(os); };
  const openEdit = os => { setEditOS(os); setShowModal(true); };

  const counts = STATUSES.reduce((acc,s) => { acc[s]=workOrders.filter(o=>o.status===s).length; return acc; },{});

  return (
    <div className="anim-fade">
      <PrintOS os={printOS} company={company}/>

      <PageHeader title="Ordens de Serviço" subtitle={`${workOrders.length} ordens no total`}
        action={<Btn icon="Plus" onClick={()=>{setEditOS(null);setShowModal(true);}}>Nova OS</Btn>}/>

      {/* Status pills */}
      <div className="flex flex-wrap gap-2 mb-4">
        {['Todos',...STATUSES].map(s=>(
          <button key={s} onClick={()=>setStatusFilter(s)}
            className={`px-3 py-1.5 rounded-full text-xs font-semibold transition-all ${statusFilter===s?'text-white shadow-sm':'text-slate-500 bg-white border border-slate-200 hover:border-slate-300'}`}
            style={statusFilter===s?{background:'#0A1F44'}:{}}>
            {s}{s!=='Todos'&&<span className="ml-1.5 opacity-60">{counts[s]||0}</span>}
          </button>
        ))}
      </div>

      {/* Table card */}
      <Card>
        <div className="flex flex-col sm:flex-row gap-3 p-4 border-b border-slate-50">
          <SearchInput value={search} onChange={setSearch} placeholder="Buscar por Nº, cliente, equipamento..." className="flex-1"/>
          <div className="text-xs text-slate-400 self-center whitespace-nowrap">{filtered.length} resultado(s)</div>
        </div>

        {loading ? (
          Array.from({length:6}).map((_,i)=><SkeletonRow key={i}/>)
        ) : filtered.length===0 ? (
          <EmptyState icon="FileText" title="Nenhuma OS encontrada" message="Tente ajustar os filtros ou crie uma nova ordem de serviço." actionLabel="Nova OS" onAction={()=>setShowModal(true)}/>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead><tr className="border-b border-slate-100">
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider">Nº OS</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider">Cliente</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider hidden md:table-cell">Equipamento</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider">Status</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase tracking-wider hidden sm:table-cell">Valor</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider hidden lg:table-cell">Entrada</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase tracking-wider">Ações</th>
              </tr></thead>
              <tbody>
                {filtered.map(os=>(
                  <tr key={os.id}
                    onClick={()=>{setDetailOS(os);setShowDetail(true);}}
                    className="border-b border-slate-50 hover:bg-slate-50 active:bg-slate-100 transition-colors group cursor-pointer">
                    <td className="px-4 py-3.5"><span className="font-bold text-sm" style={{color:'#0A1F44'}}>#{os.num}</span></td>
                    <td className="px-4 py-3.5">
                      <div className="font-semibold text-slate-800 text-sm">{os.clientName}</div>
                      <div className="text-xs text-slate-400 flex items-center gap-1 mt-0.5">
                        <Icon name={equipIcon[os.equipment?.type]||'Monitor'} size={11} color="#94A3B8"/>
                        {os.equipment?.type}
                        <span className="sm:hidden ml-1.5 font-semibold" style={{color:'#FF6B35'}}>· {fmtCurrency(os.total||0)}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3.5 hidden md:table-cell">
                      <div className="text-sm text-slate-700">{os.equipment?.brand} {os.equipment?.model}</div>
                    </td>
                    <td className="px-4 py-3.5"><StatusBadge status={os.status}/></td>
                    <td className="px-4 py-3.5 text-right hidden sm:table-cell"><span className="font-semibold text-slate-700">{fmtCurrency(os.total||0)}</span></td>
                    <td className="px-4 py-3.5 hidden lg:table-cell text-slate-500 text-sm">{fmtDate(os.entryDate)}</td>
                    <td className="px-2 py-3.5">
                      {/* Desktop: ações rápidas (stopPropagation pra nao abrir o detail tambem) */}
                      <div className="hidden md:flex items-center justify-end gap-1">
                        <button onClick={(e)=>{e.stopPropagation();setDetailOS(os);setShowDetail(true);}} title="Visualizar"
                          className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors">
                          <Icon name="Eye" size={14}/>
                        </button>
                        <button onClick={(e)=>{e.stopPropagation();openEdit(os);}} title="Editar"
                          className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-amber-600 hover:bg-amber-50 transition-colors">
                          <Icon name="Edit" size={14}/>
                        </button>
                        <button onClick={(e)=>{e.stopPropagation();handlePrint(os);}} title="Imprimir PDF"
                          className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-green-600 hover:bg-green-50 transition-colors">
                          <Icon name="Printer" size={14}/>
                        </button>
                        <button onClick={(e)=>{e.stopPropagation();setConfirm(os.id);}} title="Excluir"
                          className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors">
                          <Icon name="Trash2" size={14}/>
                        </button>
                      </div>
                      {/* Mobile: chevron indicando que a linha e tocavel */}
                      <div className="md:hidden flex items-center justify-end pr-1">
                        <Icon name="ChevronRight" size={18} color="#94A3B8"/>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <OSModal open={showModal} onClose={()=>{setShowModal(false);setEditOS(null);}} onSave={handleSave} clients={clients} services={services} editOS={editOS}/>
      <OSDetailModal open={showDetail} onClose={()=>{setShowDetail(false);setDetailOS(null);}} os={detailOS}
        onPrint={handlePrint}
        onEdit={os=>{setEditOS(os);setShowModal(true);}}
        onDelete={os=>setConfirm(os.id)}/>
      <ConfirmDialog open={!!confirm} onClose={()=>setConfirm(null)}
        onConfirm={()=>{onDelete(confirm);addToast({type:'info',msg:'OS excluída.'});setConfirm(null);}}
        message="Deseja excluir esta OS? Esta ação não pode ser desfeita."/>
    </div>
  );
}

Object.assign(window, { WorkOrders });
