// EUTPeru — Compras: Dashboard, Historial, Órdenes de Compra
const { useState, useEffect } = React;
const G = window.C;
const { T, Modal, FInput, FSelect, FTextarea, Row, Btn, Table, Card, Tabs, PageHeader, Tag, KPICard, BarChart, fmtS } = window;

const MMAP = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];

function parseDateParts(dateStr) {
  // DD/MM/YYYY → { dd, mm, yyyy }
  const [d, m, y] = (dateStr||'').split('/');
  return { dd:+d||0, mm:+m||0, yyyy:+y||0 };
}

// ── Donut simple para compras por proveedor ──────────────────
function MiniDonut({ slices, size=100 }) {
  const total = slices.reduce((s,x)=>s+x.v,0)||1;
  let cum=0;
  const cx=size/2, cy=size/2, r=size*0.4, ri=size*0.22;
  const paths = slices.map(s=>{
    const a0=(cum/total)*Math.PI*2-Math.PI/2;
    cum+=s.v;
    const a1=(cum/total)*Math.PI*2-Math.PI/2;
    const x1=cx+r*Math.cos(a0),y1=cy+r*Math.sin(a0);
    const x2=cx+r*Math.cos(a1),y2=cy+r*Math.sin(a1);
    const xi1=cx+ri*Math.cos(a1),yi1=cy+ri*Math.sin(a1);
    const xi2=cx+ri*Math.cos(a0),yi2=cy+ri*Math.sin(a0);
    const lg=a1-a0>Math.PI?1:0;
    return <path key={s.label} d={`M${x1} ${y1}A${r} ${r} 0 ${lg} 1 ${x2} ${y2}L${xi1} ${yi1}A${ri} ${ri} 0 ${lg} 0 ${xi2} ${yi2}Z`} fill={s.color} opacity={0.9}/>;
  });
  return <svg width={size} height={size}>{paths}<circle cx={cx} cy={cy} r={ri-1} fill={G.card}/></svg>;
}

const SUPPLIER_COLORS = ['#6DBF2E','#29B6F6','#FFA726','#AB47BC','#FF7043','#26A69A','#E53935','#42A5F5'];

// ── STATUS BADGE de OC ──────────────────────────────────────
function OCBadge({ status }) {
  const map = {
    borrador: { l:'Borrador', c:'#888', bg:'#88888822' },
    enviada:  { l:'Enviada',  c:'#FFA726', bg:'#FFA72622' },
    recibida: { l:'Recibida', c:'#6DBF2E', bg:'#6DBF2E22' },
  };
  const s = map[status] || map.borrador;
  return <span style={{background:s.bg,color:s.c,padding:'2px 8px',borderRadius:3,fontSize:11,fontWeight:600,border:`1px solid ${s.c}33`}}>{s.l}</span>;
}

// ── DASHBOARD DE COMPRAS ─────────────────────────────────────
function DashboardCompras({ entradas, pos, filterYear, filterMonth, setFilterYear, setFilterMonth, availYears }) {
  const now = new Date();
  const selSt = {background:G.card2,border:`1px solid ${G.border}`,color:G.text,padding:'5px 8px',borderRadius:5,fontSize:12,cursor:'pointer'};
  const hasFilter = filterYear !== 'todos' || filterMonth !== 'todos';

  // Entradas filtradas para KPIs, top productos y top proveedores
  const filteredEntradas = entradas.filter(e => {
    const { mm, yyyy } = parseDateParts(e.date);
    const matchY = filterYear === 'todos' || yyyy === +filterYear;
    const matchM = filterMonth === 'todos' || mm === +filterMonth;
    return matchY && matchM;
  });

  // Bar chart: año seleccionado → todos sus meses; si no → últimos 12 meses
  const barData = [];
  if (filterYear !== 'todos') {
    for (let i = 0; i < 12; i++) {
      const v = entradas
        .filter(e => { const p = parseDateParts(e.date); return p.mm === i+1 && p.yyyy === +filterYear; })
        .reduce((s, e) => s + e.total, 0);
      barData.push({ m: MMAP[i], v });
    }
  } else {
    for (let i = 11; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const mm = d.getMonth() + 1;
      const yy = d.getFullYear();
      const v = entradas
        .filter(e => { const p = parseDateParts(e.date); return p.mm === mm && p.yyyy === yy; })
        .reduce((s, e) => s + e.total, 0);
      barData.push({ m: MMAP[d.getMonth()], v });
    }
  }

  // KPIs
  const totalPeriodo = filteredEntradas.reduce((s, e) => s + e.total, 0);
  const pendOC = pos.filter(p => p.status !== 'recibida').length;
  const labelPeriodo = hasFilter ? 'Total período' : 'Total histórico';

  // Mes actual para KPI "este mes" (solo si no hay filtro de mes)
  const nowMm = now.getMonth() + 1;
  const nowYy = now.getFullYear();
  const thisMesTotal = entradas
    .filter(e => { const p = parseDateParts(e.date); return p.mm === nowMm && p.yyyy === nowYy; })
    .reduce((s, e) => s + e.total, 0);
  const prevMesTotal = entradas
    .filter(e => { const p = parseDateParts(e.date); return p.mm === (nowMm === 1 ? 12 : nowMm-1) && p.yyyy === (nowMm === 1 ? nowYy-1 : nowYy); })
    .reduce((s, e) => s + e.total, 0);
  const pctChange = prevMesTotal > 0 ? ((thisMesTotal - prevMesTotal) / prevMesTotal * 100).toFixed(1) : null;

  // Top products y suppliers del período filtrado
  const itemMap = {};
  filteredEntradas.forEach(e => {
    (e.items || []).forEach(item => {
      const k = item.productName || 'Sin nombre';
      if (!itemMap[k]) itemMap[k] = { name: k, qty: 0, costo: 0 };
      itemMap[k].qty   += item.qty || 0;
      itemMap[k].costo += (item.qty || 0) * parseFloat(item.cost || 0);
    });
  });
  const topProds = Object.values(itemMap).sort((a,b) => b.qty - a.qty).slice(0, 8);
  const maxQty   = Math.max(...topProds.map(p => p.qty), 1);

  const supMap = {};
  filteredEntradas.forEach(e => {
    if (!e.partner) return;
    if (!supMap[e.partner]) supMap[e.partner] = { name: e.partner, total: 0, compras: 0 };
    supMap[e.partner].total   += e.total;
    supMap[e.partner].compras++;
  });
  const topSup    = Object.values(supMap).sort((a, b) => b.total - a.total).slice(0, 6);
  const supSlices = topSup.map((s, i) => ({ label: s.name, v: s.total, color: SUPPLIER_COLORS[i % SUPPLIER_COLORS.length] }));

  return (
    <div>
      {/* Filtros */}
      <div style={{display:'flex',gap:8,alignItems:'center',marginBottom:16,flexWrap:'wrap'}}>
        <select value={filterYear} onChange={e=>setFilterYear(e.target.value)}
          style={{...selSt, borderColor: filterYear!=='todos'?G.accent:G.border}}>
          {availYears.map(y=><option key={y} value={y}>{y==='todos'?'Todos los años':y}</option>)}
        </select>
        <select value={filterMonth} onChange={e=>setFilterMonth(e.target.value)}
          style={{...selSt, borderColor: filterMonth!=='todos'?G.accent:G.border}}>
          <option value="todos">Todos los meses</option>
          {MMAP.map((m,i)=><option key={i+1} value={i+1}>{m}</option>)}
        </select>
        {hasFilter && (
          <button onClick={()=>{setFilterYear('todos');setFilterMonth('todos');}}
            style={{background:G.error+'22',border:`1px solid ${G.error}44`,color:G.error,padding:'5px 8px',borderRadius:5,fontSize:11,cursor:'pointer'}}>
            ✕ Limpiar
          </button>
        )}
      </div>

      {/* KPIs */}
      <div style={{display:'flex',gap:12,marginBottom:20,flexWrap:'wrap'}}>
        {!hasFilter && (
          <KPICard label="Compras este mes" value={fmtS(thisMesTotal)} color={G.warning} icon="📦"
            sub={pctChange !== null ? `${pctChange >= 0 ? '+' : ''}${pctChange}% vs mes anterior` : undefined}/>
        )}
        <KPICard label={labelPeriodo} value={fmtS(totalPeriodo)} color='#29B6F6' icon="🏭"/>
        <KPICard label="Entradas registradas" value={filteredEntradas.length} color={G.accent} icon="📥"/>
        <KPICard label="OC pendientes" value={pendOC} color={pendOC > 0 ? G.warning : G.textSec} icon="📋"/>
      </div>

      {/* Bar chart mensual */}
      <Card title={filterYear!=='todos' ? `Compras mes a mes — ${filterYear}` : 'Compras mes a mes (últimos 12 meses)'} style={{marginBottom:20}}>
        <BarChart data={barData} height={140}/>
        <div style={{display:'flex',justifyContent:'space-between',marginTop:8}}>
          {barData.filter((_,i) => i % 3 === 0 || i === barData.length-1).map((d,i) => (
            <div key={i} style={{textAlign:'center'}}>
              <div style={{fontSize:10,color:G.textSec}}>{d.m}</div>
              {d.v > 0 && <div style={{fontSize:9,color:G.warning}}>{fmtS(d.v)}</div>}
            </div>
          ))}
        </div>
      </Card>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,marginBottom:20}}>
        {/* Top productos */}
        <Card title="Productos más comprados (por cantidad)">
          {topProds.length === 0
            ? <div style={{color:G.textSec,fontSize:12,padding:'8px 0'}}>Sin datos</div>
            : topProds.map((p, i) => (
              <div key={i} style={{marginBottom:10}}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
                  <span style={{fontSize:12,color:G.text,flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={p.name}>{p.name}</span>
                  <span style={{fontSize:12,fontWeight:700,color:G.accent,marginLeft:8,flexShrink:0}}>{p.qty} ud.</span>
                </div>
                <div style={{height:5,background:G.border,borderRadius:3,overflow:'hidden'}}>
                  <div style={{height:'100%',width:`${(p.qty/maxQty*100).toFixed(1)}%`,background:G.accent,borderRadius:3,transition:'width 0.5s'}}/>
                </div>
                <div style={{fontSize:10,color:G.textSec,marginTop:1}}>Costo acumulado: {fmtS(p.costo)}</div>
              </div>
            ))
          }
        </Card>

        {/* Top proveedores */}
        <Card title="Proveedores — gasto total">
          {topSup.length === 0
            ? <div style={{color:G.textSec,fontSize:12,padding:'8px 0'}}>Sin datos</div>
            : (
              <div style={{display:'flex',gap:16,alignItems:'center',flexWrap:'wrap'}}>
                <MiniDonut slices={supSlices} size={110}/>
                <div style={{flex:1,minWidth:120}}>
                  {topSup.map((s, i) => (
                    <div key={i} style={{display:'flex',alignItems:'center',gap:6,marginBottom:6}}>
                      <div style={{width:8,height:8,borderRadius:'50%',background:SUPPLIER_COLORS[i % SUPPLIER_COLORS.length],flexShrink:0}}/>
                      <span style={{fontSize:11,color:G.textSec,flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{s.name}</span>
                      <span style={{fontSize:11,fontWeight:700,color:G.warning,flexShrink:0}}>{fmtS(s.total)}</span>
                    </div>
                  ))}
                </div>
              </div>
            )
          }
        </Card>
      </div>
    </div>
  );
}

// ── HISTORIAL DE COMPRAS ─────────────────────────────────────
function HistorialCompras({ entradas, onNew, currentUser, onDelete, filterYear, filterMonth, setFilterYear, setFilterMonth, availYears }) {
  const [searchProv, setSearchProv] = useState('');
  const [delTarget, setDelTarget] = useState(null);
  const [delReason, setDelReason] = useState('');
  const [revertStock, setRevertStock] = useState(true);
  const [deleting, setDeleting] = useState(false);

  const canDelete = currentUser?.role === 'Administrador' || !!currentUser?.perms?.eliminarMovimientos;

  const filtered = entradas.filter(e => {
    const { mm, yyyy } = parseDateParts(e.date);
    const matchY = filterYear === 'todos' || yyyy === +filterYear;
    const matchM = filterMonth === 'todos' || mm === +filterMonth;
    const matchP = !searchProv || (e.partner||'').toLowerCase().includes(searchProv.toLowerCase());
    return matchY && matchM && matchP;
  });

  const openDel = (row) => { setDelTarget(row); setDelReason(''); setRevertStock(true); };
  const closeDel = () => { setDelTarget(null); setDelReason(''); };

  const confirmDelete = async () => {
    if (!delReason.trim()) return;
    setDeleting(true);
    const res = await window.api(`/movements/${delTarget.id}`, {
      method: 'DELETE',
      body: JSON.stringify({ reason: delReason.trim(), revertStock }),
    });
    setDeleting(false);
    if (res && res.ok) {
      onDelete(delTarget.id);
      closeDel();
    }
  };

  const cols = [
    {key:'date',    label:'Fecha',    w:100, render:r=><span style={{fontSize:11,color:G.textSec}}>{r.date}</span>},
    {key:'partner', label:'Proveedor',       render:r=><span style={{color:G.accent,fontWeight:500}}>{r.partner||'—'}</span>},
    {key:'products',label:'Productos',       render:r=><span style={{fontSize:11,color:G.textSec}}>{r.products||'—'}</span>},
    {key:'qty',     label:'Cant.',    w:60,  render:r=><span style={{fontWeight:600}}>{r.qty}</span>},
    {key:'total',   label:'Total',    w:120, render:r=><span style={{color:G.warning,fontWeight:700}}>{fmtS(r.total)}</span>},
    ...(canDelete ? [{key:'del', label:'', w:60, render:r=>(
      <Btn sm variant="danger" onClick={()=>openDel(r)}>✕</Btn>
    )}] : []),
  ];

  return (
    <div>
      <div style={{display:'flex',gap:8,alignItems:'center',marginBottom:14,flexWrap:'wrap'}}>
        <input value={searchProv} onChange={e=>setSearchProv(e.target.value)} placeholder="🔍 Buscar proveedor…"
          style={{background:G.card2,border:`1px solid ${searchProv?G.accent:G.border}`,borderRadius:5,color:G.text,padding:'5px 10px',fontSize:12,outline:'none',width:200}}/>
        {searchProv && <button onClick={()=>setSearchProv('')} style={{background:'none',border:'none',color:G.textSec,cursor:'pointer',fontSize:13}}>✕</button>}
        <select value={filterYear} onChange={e=>setFilterYear(e.target.value)}
          style={{background:G.card2,border:`1px solid ${filterYear!=='todos'?G.accent:G.border}`,color:G.text,padding:'5px 8px',borderRadius:5,fontSize:12,cursor:'pointer'}}>
          {availYears.map(y=><option key={y} value={y}>{y==='todos'?'Todos los años':y}</option>)}
        </select>
        <select value={filterMonth} onChange={e=>setFilterMonth(e.target.value)}
          style={{background:G.card2,border:`1px solid ${filterMonth!=='todos'?G.accent:G.border}`,color:G.text,padding:'5px 8px',borderRadius:5,fontSize:12,cursor:'pointer'}}>
          <option value="todos">Todos los meses</option>
          {MMAP.map((m,i)=><option key={i+1} value={i+1}>{m}</option>)}
        </select>
        {(filterYear!=='todos'||filterMonth!=='todos') && (
          <button onClick={()=>{setFilterYear('todos');setFilterMonth('todos');}}
            style={{background:G.error+'22',border:`1px solid ${G.error}44`,color:G.error,padding:'5px 8px',borderRadius:5,fontSize:11,cursor:'pointer'}}>
            ✕ Limpiar
          </button>
        )}
        <div style={{flex:1}}/>
        <Btn onClick={onNew}>+ Registrar Compra</Btn>
      </div>
      <Card noPad>
        <Table cols={cols} rows={filtered} emptyMsg="Sin compras registradas"/>
      </Card>

      {delTarget && (
        <Modal title="Eliminar Compra / Entrada de Stock" onClose={closeDel} width={440}>
          <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'12px 14px',marginBottom:14}}>
            <div style={{fontSize:12,color:G.textSec,marginBottom:4}}>Proveedor: <b style={{color:G.text}}>{delTarget.partner||'—'}</b></div>
            <div style={{fontSize:12,color:G.textSec,marginBottom:4}}>Fecha: <b style={{color:G.text}}>{delTarget.date}</b></div>
            <div style={{fontSize:12,color:G.textSec}}>Total: <b style={{color:G.warning}}>{fmtS(delTarget.total)}</b></div>
          </div>
          <div style={{marginBottom:12}}>
            <label style={{fontSize:12,color:G.textSec,display:'block',marginBottom:4}}>Motivo de eliminación *</label>
            <textarea value={delReason} onChange={e=>setDelReason(e.target.value)} rows={3} placeholder="Describe el motivo…"
              style={{width:'100%',boxSizing:'border-box',background:G.bg,border:`1px solid ${delReason.trim()?G.accent:G.border}`,borderRadius:5,color:G.text,padding:'7px 10px',fontSize:12,outline:'none',resize:'vertical',fontFamily:"'Inter',sans-serif"}}/>
          </div>
          <label style={{display:'flex',alignItems:'center',gap:8,fontSize:12,color:G.textSec,marginBottom:16,cursor:'pointer'}}>
            <input type="checkbox" checked={revertStock} onChange={e=>setRevertStock(e.target.checked)} style={{accentColor:G.accent}}/>
            Revertir stock (descontar las unidades ingresadas)
          </label>
          <div style={{display:'flex',justifyContent:'flex-end',gap:8}}>
            <Btn variant="secondary" onClick={closeDel}>Cancelar</Btn>
            <Btn variant="danger" onClick={confirmDelete} disabled={deleting||!delReason.trim()}>
              {deleting ? 'Eliminando…' : 'Eliminar'}
            </Btn>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ── FORM COMPRA (MODAL) ──────────────────────────────────────
function HistoricoPreciosCompras({ entradas }) {
  const [selectedProduct, setSelectedProduct] = useState('');
  const [search, setSearch] = useState('');

  const priceRows = [];
  entradas.forEach(e => {
    (e.items || []).forEach(item => {
      const cost = parseFloat(item.cost || 0);
      if (!cost) return;
      priceRows.push({
        movementId: e.id,
        date: e.date,
        partner: e.partner || '—',
        productId: item.productId || '',
        productName: item.productName || 'Sin nombre',
        qty: item.qty || 0,
        cost,
        total: cost * (item.qty || 0),
      });
    });
  });

  const productMap = {};
  priceRows.forEach(r => {
    const key = r.productId || r.productName;
    if (!productMap[key]) productMap[key] = { id:key, name:r.productName, rows:[] };
    productMap[key].rows.push(r);
  });
  const productOptions = Object.values(productMap)
    .filter(p => !search || p.name.toLowerCase().includes(search.toLowerCase()))
    .sort((a,b)=>a.name.localeCompare(b.name));

  const activeId = selectedProduct && productMap[selectedProduct] ? selectedProduct : (productOptions[0]?.id || '');
  const active = productMap[activeId];
  const selectOptions = active && !productOptions.some(p=>p.id===active.id) ? [active, ...productOptions] : productOptions;
  const rows = (active?.rows || []).slice().sort((a,b)=>{
    const pa = parseDateParts(a.date);
    const pb = parseDateParts(b.date);
    return (pb.yyyy*10000+pb.mm*100+pb.dd) - (pa.yyyy*10000+pa.mm*100+pa.dd);
  });
  const costs = rows.map(r=>r.cost);
  const minCost = costs.length ? Math.min(...costs) : 0;
  const maxCost = costs.length ? Math.max(...costs) : 0;
  const avgCost = costs.length ? costs.reduce((s,c)=>s+c,0) / costs.length : 0;
  const lastCost = rows[0]?.cost || 0;
  const prevCost = rows[1]?.cost || 0;
  const delta = prevCost ? ((lastCost - prevCost) / prevCost * 100) : null;

  const cols = [
    {key:'date',label:'Fecha',w:100,render:r=><span style={{fontSize:11,color:G.textSec}}>{r.date}</span>},
    {key:'partner',label:'Proveedor',render:r=><span style={{fontSize:12,color:G.text}}>{r.partner}</span>},
    {key:'qty',label:'Cant.',w:70,render:r=><span style={{fontWeight:700}}>{r.qty}</span>},
    {key:'cost',label:'Precio unit.',w:120,render:r=><span style={{fontWeight:700,color:G.warning}}>{fmtS(r.cost)}</span>},
    {key:'total',label:'Total compra',w:120,render:r=><span style={{color:G.textSec}}>{fmtS(r.total)}</span>},
  ];

  return (
    <div>
      <div style={{display:'flex',gap:8,alignItems:'center',marginBottom:14,flexWrap:'wrap'}}>
        <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar producto..."
          style={{background:G.card2,border:`1px solid ${search?G.accent:G.border}`,borderRadius:5,color:G.text,padding:'5px 10px',fontSize:12,outline:'none',width:220}}/>
        <select value={activeId} onChange={e=>setSelectedProduct(e.target.value)} style={{background:G.card2,border:`1px solid ${G.border}`,color:G.text,padding:'5px 8px',borderRadius:5,fontSize:12,cursor:'pointer',minWidth:260}}>
          {selectOptions.length===0
            ? <option value="">Sin productos con historial</option>
            : selectOptions.map(p=><option key={p.id} value={p.id}>{p.name}</option>)
          }
        </select>
      </div>

      <div style={{display:'flex',gap:12,marginBottom:16,flexWrap:'wrap'}}>
        <KPICard label="Último precio" value={fmtS(lastCost)} color={G.warning} sub={delta!==null?`${delta>=0?'+':''}${delta.toFixed(1)}% vs anterior`:undefined}/>
        <KPICard label="Precio promedio" value={fmtS(avgCost)} color={G.accent}/>
        <KPICard label="Precio mínimo" value={fmtS(minCost)} color={G.textSec}/>
        <KPICard label="Precio máximo" value={fmtS(maxCost)} color={G.error}/>
      </div>

      <Card title={active ? `Evolución de precios — ${active.name}` : 'Evolución de precios'} noPad>
        <Table cols={cols} rows={rows} emptyMsg="Sin historial de precios para este producto"/>
      </Card>
    </div>
  );
}

// ── FORM COMPRA (MODAL) ─────────────────────────────────────
function FormCompra({ contacts, products, onSave, onClose }) {
  const [form, setForm] = useState({supplierId:'',date:'',lines:[]});
  const [search, setSearch] = useState('');
  const [saving, setSaving] = useState(false);
  const sf = (k,v) => setForm(f=>({...f,[k]:v}));
  const suppliers = (contacts||[]).filter(c=>c.type==='proveedor');
  const inputSt   = {background:G.bg,border:`1px solid ${G.border}`,borderRadius:5,color:G.text,padding:'7px 11px',fontSize:12,outline:'none',fontFamily:"'Inter',sans-serif"};
  const subtotal  = form.lines.reduce((s,l)=>s+(+l.qty||0)*(+l.cost||0),0);

  const filteredProds = (products||[]).filter(p=>(p.name||'').toLowerCase().includes(search.toLowerCase())||(p.brand||'').toLowerCase().includes(search.toLowerCase()));

  const addProduct = (p) => {
    if(form.lines.find(l=>l.productId===p.id)) return;
    setForm(f=>({...f,lines:[...f.lines,{productId:p.id,name:p.name,um:p.um||'UND',qty:1,cost:p.buy||''}]}));
    setSearch('');
  };

  const setLineQty = (pid,qty) => setForm(f=>({...f,lines:f.lines.map(l=>l.productId!==pid?l:{...l,qty:+qty||0})}));
  const setLineCost = (pid,cost) => setForm(f=>({...f,lines:f.lines.map(l=>l.productId!==pid?l:{...l,cost})}));
  const remLine = (pid) => setForm(f=>({...f,lines:f.lines.filter(l=>l.productId!==pid)}));

  const save = async () => {
    const lines = form.lines.filter(l=>l.productId&&l.qty);
    if (!lines.length) return;
    setSaving(true);
    const payloadDate = form.date||new Date().toISOString().split('T')[0];
    console.log('[FormCompra] Fecha seleccionada:', form.date);
    console.log('[FormCompra] Fecha enviada al backend:', payloadDate);
    const res = await window.api('/movements',{method:'POST',body:JSON.stringify({
      type:'entrada',
      supplierId: form.supplierId?+form.supplierId:null,
      date: payloadDate,
      lines: lines.map(l=>({productId:+l.productId,qty:+l.qty,cost:+l.cost||null})),
    })});
    setSaving(false);
    if (res && res.ok) {
      const result = await res.json();
      console.log('[FormCompra] Respuesta del backend - fecha:', result.date);
      onSave(result);
    }
  };

  return (
    <Modal title="Registrar Compra / Entrada de Stock" onClose={onClose} width={640}>
      <Row>
        <FSelect label="Proveedor" value={form.supplierId} onChange={e=>sf('supplierId',e.target.value)}
          options={[{value:'',label:'Sin proveedor'},...suppliers.map(s=>({value:s.id,label:s.name}))]}/>
        <FInput label="Fecha de compra" type="date" value={form.date} onChange={e=>sf('date',e.target.value)}/>
      </Row>
      <div style={{...T.sm,marginBottom:8,textTransform:'uppercase',letterSpacing:0.5}}>Productos</div>
      <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar y agregar producto…" style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:5,color:G.text,padding:'7px 12px',fontSize:13,width:'100%',outline:'none',fontFamily:"'Inter',sans-serif",boxSizing:'border-box',marginBottom:8}}/>
      {search && (
        <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,marginBottom:10,maxHeight:140,overflowY:'auto'}}>
          {filteredProds.slice(0,6).map(p=>{
            const exists = form.lines.find(l=>l.productId===p.id);
            return (
              <div key={p.id} onClick={()=>!exists&&addProduct(p)} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'7px 12px',cursor:exists?'default':'pointer',borderBottom:`1px solid ${G.border}22`,opacity:exists?0.5:1}} onMouseEnter={e=>!exists&&(e.currentTarget.style.background=G.card2)} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <div>
                  <div style={{fontSize:12,color:G.text}}>{p.name}</div>
                  <div style={{fontSize:10,color:G.textSec}}>{p.brand} · {p.um||'UND'}</div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div style={{color:G.accent,fontWeight:600,fontSize:12}}>{fmtS(p.buy||0)}</div>
                  {exists && <span style={{fontSize:10,color:G.textSec}}>Ya agregado</span>}
                </div>
              </div>
            );
          })}
          {filteredProds.length===0 && <div style={{padding:12,color:G.textSec,fontSize:12}}>Sin resultados</div>}
        </div>
      )}
      {form.lines.length>0 && (
        <table style={{width:'100%',borderCollapse:'collapse',marginBottom:14}}>
          <thead><tr>
            {['ITEM','DESCRIPCIÓN','U.M.','CANT.','COSTO','TOTAL',''].map(h=><th key={h} style={{padding:'5px 8px',textAlign:'left',fontSize:9,color:G.textSec,fontWeight:700,textTransform:'uppercase',borderBottom:`1px solid ${G.border}`}}>{h}</th>)}
          </tr></thead>
          <tbody>
            {form.lines.map((l,i)=>{
              const lineTotal = (+l.qty||0)*(+l.cost||0);
              return (
                <tr key={l.productId}>
                  <td style={{padding:'6px 8px',fontSize:12,color:G.textSec}}>{i+1}</td>
                  <td style={{padding:'6px 8px',fontSize:12,color:G.text}}>{l.name}</td>
                  <td style={{padding:'6px 8px',fontSize:11,color:G.textSec}}>{l.um}</td>
                  <td style={{padding:'6px 8px'}}><input type="number" min={1} value={l.qty} onChange={e=>setLineQty(l.productId,e.target.value)} style={{width:50,background:G.bg,border:`1px solid ${G.border}`,borderRadius:4,color:G.text,padding:'3px 6px',fontSize:12,textAlign:'center'}}/></td>
                  <td style={{padding:'6px 8px'}}><input type="number" step="0.01" value={l.cost} onChange={e=>setLineCost(l.productId,e.target.value)} style={{width:80,background:G.bg,border:`1px solid ${G.border}`,borderRadius:4,color:G.text,padding:'3px 6px',fontSize:12}}/></td>
                  <td style={{padding:'6px 8px',fontSize:12,fontWeight:700,color:G.text}}>{fmtS(lineTotal)}</td>
                  <td style={{padding:'6px 8px'}}><button onClick={()=>remLine(l.productId)} style={{background:'none',border:'none',color:G.error,cursor:'pointer',fontSize:13}}>✕</button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
      {form.lines.length===0 && <div style={{color:G.textSec,fontSize:12,textAlign:'center',padding:20}}>Busca y agrega productos usando el campo de arriba</div>}
      <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'8px 14px',marginBottom:14,display:'flex',justifyContent:'space-between'}}>
        <span style={{...T.sm}}>Total compra:</span>
        <span style={{color:G.warning,fontWeight:700}}>{fmtS(subtotal)}</span>
      </div>
      <div style={{display:'flex',justifyContent:'flex-end',gap:8}}>
        <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
        <Btn onClick={save} disabled={saving}>{saving?'Guardando…':'Guardar Compra'}</Btn>
      </div>
    </Modal>
  );
}

// ── PDF para Orden de Compra ──────────────────────────────────
function OCPDF({ po, onClose, currentUser }) {
  const printPDF = () => {
    const el = document.getElementById('oc-print-area');
    const win = window.open('','_blank','width=900,height=700');
    win.document.write(`<!DOCTYPE html><html><head><title>Orden de Compra OC-${po.id}</title>
    <style>
      body{margin:0;padding:20px;font-family:Arial,sans-serif;font-size:12px;color:#111;}
      @page{size:A4;margin:15mm;}
      @media print{@page{margin:1cm;}body{padding:0;}}
      table{border-collapse:collapse;width:100%;}
      th,td{padding:6px 10px;}
    </style></head><body>${el.innerHTML}</body></html>`);
    win.document.close();
    win.focus();
    setTimeout(()=>{ win.print(); win.close(); }, 400);
  };

  const statusLabel = { borrador:'Borrador', enviada:'Enviada', recibida:'Recibida' };
  const subtotal = (po.items||[]).reduce((s,it)=>s+(+it.total||0),0);
  const emisorNombre = currentUser ? `${currentUser.name||''} ${currentUser.apellidos||''}`.trim() : '—';
  const fechaHoy = new Date().toLocaleDateString('es-PE', {day:'2-digit',month:'2-digit',year:'numeric'});

  return (
    <div style={{position:'fixed',inset:0,background:'#000000e0',zIndex:1000,display:'flex',flexDirection:'column'}} onClick={onClose}>
      <div style={{height:50,background:G.card,borderBottom:`1px solid ${G.border}`,display:'flex',alignItems:'center',padding:'0 20px',gap:12,flexShrink:0}} onClick={e=>e.stopPropagation()}>
        <span style={{fontFamily:"'Barlow Condensed',sans-serif",fontSize:16,fontWeight:700,color:G.text,flex:1}}>Orden de Compra — OC-{po.id}</span>
        <Btn onClick={printPDF}>⬇ Descargar PDF</Btn>
        <button onClick={onClose} style={{background:'none',border:'none',color:G.textSec,fontSize:18,cursor:'pointer',padding:'4px 8px'}}>✕</button>
      </div>
      <div style={{flex:1,overflow:'auto',padding:32,display:'flex',justifyContent:'center'}} onClick={e=>e.stopPropagation()}>
        <div id="oc-print-area" style={{background:'#fff',color:'#111',width:794,minHeight:1123,padding:'40px 48px',fontFamily:'Arial,sans-serif',fontSize:12,lineHeight:1.5,boxShadow:'0 8px 40px #00000060'}}>

          {/* Header empresa */}
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:24,paddingBottom:16,borderBottom:'3px solid #6DBF2E'}}>
            <div>
              <div style={{fontWeight:800,fontSize:22,color:'#1a1a1a',letterSpacing:1}}>EUTPERU</div>
              <div style={{fontSize:10,color:'#4A8A1F',fontWeight:700,letterSpacing:0.5,marginTop:2}}>EQUIPOS E IMPLEMENTOS DE SEGURIDAD</div>
            </div>
            <div style={{textAlign:'right',fontSize:11}}>
              <div style={{fontWeight:700,fontSize:14,marginBottom:4}}>E.U.T. PERÚ EIRL</div>
              <div>RUC: 20611733985</div>
              <div>Tel/WhatsApp: +51 986 401 657</div>
              <div>eutperu@gmail.com | logistica@eutperu.com</div>
            </div>
          </div>

          {/* Título del documento */}
          <div style={{textAlign:'center',marginBottom:20}}>
            <div style={{fontSize:16,fontWeight:700,color:'#1a1a1a',letterSpacing:2,textTransform:'uppercase'}}>ORDEN DE COMPRA N° OC-{po.id}</div>
          </div>

          {/* Proveedor + Detalles OC */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,marginBottom:20}}>
            <div style={{border:'1px solid #ddd',borderRadius:4,padding:'12px 16px'}}>
              <div style={{fontWeight:700,color:'#6DBF2E',fontSize:11,marginBottom:8,textTransform:'uppercase',letterSpacing:0.5}}>Proveedor</div>
              <div><b>Razón Social:</b> {po.supplier||'—'}</div>
              {po.supplierRuc && <div><b>RUC:</b> {po.supplierRuc}</div>}
              {po.supplierPhone && <div><b>Teléfono:</b> {po.supplierPhone}</div>}
              {po.supplierEmail && <div><b>Email:</b> {po.supplierEmail}</div>}
            </div>
            <div style={{border:'1px solid #ddd',borderRadius:4,padding:'12px 16px'}}>
              <div style={{fontWeight:700,color:'#6DBF2E',fontSize:11,marginBottom:8,textTransform:'uppercase',letterSpacing:0.5}}>Detalle OC</div>
              <div><b>N°:</b> OC-{po.id}</div>
              <div><b>Fecha:</b> {po.date}</div>
              <div><b>Estado:</b> <span style={{textTransform:'capitalize'}}>{statusLabel[po.status]||po.status}</span></div>
              <div><b>Condición de Pago:</b> {po.creditDays>0?`${po.creditDays} días`:'Contado'}</div>
              {po.invoiceNum && <div><b>Factura proveedor:</b> {po.invoiceNum}</div>}
            </div>
          </div>

          {/* Tabla de ítems */}
          <table style={{width:'100%',borderCollapse:'collapse',marginBottom:12}}>
            <thead>
              <tr style={{background:'#6DBF2E',color:'#fff'}}>
                {['ITEM','DESCRIPCIÓN','U.M.','CANTIDAD','COSTO UNIT.','TOTAL'].map(h=>(
                  <th key={h} style={{padding:'8px 10px',textAlign:h==='ITEM'||h==='U.M.'||h==='CANTIDAD'?'center':'left',fontSize:10,fontWeight:700,letterSpacing:0.5}}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(po.items||[]).map((it,i)=>(
                <tr key={i} style={{background:i%2===0?'#f9f9f9':'#fff',borderBottom:'1px solid #e0e0e0'}}>
                  <td style={{padding:'7px 10px',textAlign:'center'}}>{i+1}</td>
                  <td style={{padding:'7px 10px'}}>{it.productName}</td>
                  <td style={{padding:'7px 10px',textAlign:'center'}}>{it.um||'UND'}</td>
                  <td style={{padding:'7px 10px',textAlign:'center',fontWeight:600}}>{it.qty}</td>
                  <td style={{padding:'7px 10px',textAlign:'right'}}>S/ {(+it.cost).toFixed(2)}</td>
                  <td style={{padding:'7px 10px',textAlign:'right',fontWeight:600}}>S/ {(+it.total).toFixed(2)}</td>
                </tr>
              ))}
              {Array.from({length:Math.max(0,8-(po.items||[]).length)}).map((_,i)=>(
                <tr key={`e${i}`} style={{borderBottom:'1px solid #f0f0f0'}}>
                  <td style={{padding:'7px 10px'}}>&nbsp;</td><td/><td/><td/><td/><td/>
                </tr>
              ))}
            </tbody>
          </table>

          {/* Total */}
          <div style={{display:'flex',justifyContent:'flex-end',marginBottom:20}}>
            <table style={{width:240}}>
              <tbody>
                <tr><td style={{padding:'4px 10px',color:'#555'}}>SUBTOTAL</td><td style={{padding:'4px 10px',textAlign:'right',fontWeight:600}}>S/ {subtotal.toFixed(2)}</td></tr>
                <tr><td style={{padding:'4px 10px',color:'#555'}}>{po.creditDays>0?`Crédito ${po.creditDays} días`:'Pago al contado'}</td><td/></tr>
                <tr style={{background:'#6DBF2E',color:'#fff'}}>
                  <td style={{padding:'6px 10px',fontWeight:700,borderRadius:'4px 0 0 4px'}}>TOTAL</td>
                  <td style={{padding:'6px 10px',textAlign:'right',fontWeight:700,fontSize:15,borderRadius:'0 4px 4px 0'}}>S/ {(+po.total).toFixed(2)}</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* Notas */}
          {po.notes && (
            <div style={{border:'1px solid #ddd',borderRadius:4,padding:'10px 14px',marginBottom:16,fontSize:11,color:'#555'}}>
              <b>Notas / Instrucciones al proveedor:</b> {po.notes}
            </div>
          )}

          {/* Firmas */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:20,marginTop:24}}>
            <div style={{border:'1px solid #ccc',borderRadius:4,padding:'12px 16px',minHeight:80}}>
              <div style={{fontWeight:700,fontSize:11,marginBottom:6}}>EMITIDO POR:</div>
              <div style={{fontSize:12,fontWeight:600,marginBottom:2}}>{emisorNombre}</div>
              <div style={{fontSize:11,color:'#555',marginBottom:24}}>Fecha: {fechaHoy}</div>
              <div style={{borderTop:'1px solid #999',paddingTop:6,fontSize:10,color:'#555'}}>E.U.T. PERÚ EIRL — Firma y Sello</div>
            </div>
            <div style={{border:'1px solid #ccc',borderRadius:4,padding:'12px 16px',minHeight:80}}>
              <div style={{fontWeight:700,fontSize:11,marginBottom:4}}>CONFIRMADO POR PROVEEDOR:</div>
              <div style={{fontSize:10,color:'#666',marginBottom:20}}>Fecha: ________________</div>
              <div style={{borderTop:'1px solid #999',paddingTop:6,fontSize:10,color:'#555'}}>Nombre, Firma y Sello</div>
            </div>
          </div>

          {/* Footer */}
          <div style={{borderTop:'2px solid #6DBF2E',paddingTop:10,marginTop:20,fontSize:10,color:'#666',textAlign:'center'}}>
            E.U.T. PERÚ EIRL — RUC 20611733985 — Tel: +51 986 401 657 — eutperu@gmail.com | logistica@eutperu.com
            <br/>Documento generado el {new Date().toLocaleDateString('es-PE')}
          </div>

        </div>
      </div>
    </div>
  );
}

// ── ÓRDENES DE COMPRA ────────────────────────────────────────
function OrdenesCompra({ pos, setPOs, contacts, products, currentUser, onReceive }) {
  const [showNew,     setShowNew]     = useState(false);
  const [viewDetail,  setViewDetail]  = useState(null);
  const [viewPDF,     setViewPDF]     = useState(null);
  const [receiveOC,   setReceiveOC]   = useState(null); // OC being confirmed received
  const [invoiceNum,  setInvoiceNum]  = useState('');
  const [isHistorical, setIsHistorical] = useState(false); // Solo admins: usar fecha de OC como fecha de entrada
  const [receiving,   setReceiving]   = useState(false);
  const isAdmin = currentUser?.role === 'Administrador';
  const [form, setForm] = useState({supplierId:'',date:'',creditDays:'',notes:'',lines:[]});
  const [search, setSearch] = useState('');
  const [saving, setSaving] = useState(false);
  const sf = (k,v) => setForm(f=>({...f,[k]:v}));
  const suppliers = (contacts||[]).filter(c=>c.type==='proveedor');
  const inputSt   = {background:G.bg,border:`1px solid ${G.border}`,borderRadius:5,color:G.text,padding:'7px 11px',fontSize:12,outline:'none',fontFamily:"'Inter',sans-serif"};
  const subtotal  = form.lines.reduce((s,l)=>s+(+l.qty||0)*(+l.cost||0),0);

  const filteredProds = (products||[]).filter(p=>(p.name||'').toLowerCase().includes(search.toLowerCase())||(p.brand||'').toLowerCase().includes(search.toLowerCase()));

  const addProduct = (p) => {
    if(form.lines.find(l=>l.productId===p.id)) return;
    setForm(f=>({...f,lines:[...f.lines,{productId:p.id,name:p.name,um:p.um||'UND',qty:1,cost:p.buy||''}]}));
    setSearch('');
  };

  const setLineQty = (pid,qty) => setForm(f=>({...f,lines:f.lines.map(l=>l.productId!==pid?l:{...l,qty:+qty||0})}));
  const setLineCost = (pid,cost) => setForm(f=>({...f,lines:f.lines.map(l=>l.productId!==pid?l:{...l,cost})}));
  const remLine = (pid) => setForm(f=>({...f,lines:f.lines.filter(l=>l.productId!==pid)}));

  // Auto-fill creditDays from supplier
  const onSupplierChange = (e) => {
    const id = e.target.value;
    sf('supplierId', id);
    if(id) {
      const sup = suppliers.find(s=>+s.id===+id);
      if(sup) sf('creditDays', String(sup.credit||0));
    } else {
      sf('creditDays','');
    }
  };

  const saveOC = async () => {
    const lines = form.lines.filter(l=>l.productId&&l.qty);
    if (!lines.length) return;
    setSaving(true);
    const res = await window.api('/purchase-orders',{method:'POST',body:JSON.stringify({
      supplierId:  form.supplierId?+form.supplierId:null,
      date:        form.date||new Date().toISOString().split('T')[0],
      notes:       form.notes,
      creditDays:  form.creditDays!==''?+form.creditDays:undefined,
      lines:       lines.map(l=>({productId:+l.productId,qty:+l.qty,cost:+l.cost||0})),
    })});
    setSaving(false);
    if(res && res.ok){
      const created = await res.json();
      setPOs(ps=>[created,...ps]);
      setShowNew(false);
      setForm({supplierId:'',date:'',creditDays:'',notes:'',lines:[]});
    }
  };

  const updateStatus = async (po, newStatus, extraData={}) => {
    const res = await window.api(`/purchase-orders/${po.id}/status`,{method:'PATCH',body:JSON.stringify({status:newStatus,...extraData})});
    if(res && res.ok){
      const updated = await res.json();
      setPOs(ps=>ps.map(p=>p.id===updated.id?updated:p));
      if(viewDetail?.id===updated.id) setViewDetail(updated);
      if(newStatus === 'recibida') onReceive?.();
    }
  };

  const startReceive = (po) => {
    setReceiveOC(po);
    setInvoiceNum('');
    setIsHistorical(false); // Reset por defecto
  };

  const confirmReceive = async () => {
    if(!receiveOC) return;
    setReceiving(true);
    await updateStatus(receiveOC, 'recibida', {invoiceNum: invoiceNum||null, isHistorical: isAdmin ? isHistorical : false});
    setReceiving(false);
    setReceiveOC(null);
    setInvoiceNum('');
    setIsHistorical(false);
  };

  const deleteOC = async (po) => {
    if(!confirm(`¿Eliminar OC #${po.id}?`)) return;
    const res = await window.api(`/purchase-orders/${po.id}`,{method:'DELETE'});
    if(res && res.ok) setPOs(ps=>ps.filter(p=>p.id!==po.id));
  };

  const cols = [
    {key:'id',       label:'OC #',     w:60,  render:r=><span style={{color:G.accent,fontWeight:700,cursor:'pointer'}} onClick={()=>setViewDetail(r)}>#{r.id}</span>},
    {key:'date',     label:'Fecha',    w:100, render:r=><span style={{fontSize:11,color:G.textSec}}>{r.date}</span>},
    {key:'supplier', label:'Proveedor',       render:r=><span style={{fontWeight:500}}>{r.supplier||'—'}</span>},
    {key:'credit',   label:'Crédito',  w:80,  render:r=><span style={{fontSize:11,color:G.textSec}}>{r.creditDays>0?`${r.creditDays}d`:'Contado'}</span>},
    {key:'total',    label:'Total',    w:110, render:r=><span style={{color:G.warning,fontWeight:700}}>{fmtS(r.total)}</span>},
    {key:'status',   label:'Estado',   w:100, render:r=><OCBadge status={r.status}/>},
    {key:'acts',     label:'',         w:200, render:r=>(
      <div style={{display:'flex',gap:4,justifyContent:'flex-end'}}>
        <Btn sm variant="ghost" onClick={()=>setViewDetail(r)}>Ver</Btn>
        <Btn sm variant="ghost" onClick={()=>setViewPDF(r)} title="PDF">📄</Btn>
        {r.status==='borrador' && <Btn sm variant="accent" onClick={()=>updateStatus(r,'enviada')}>Enviar</Btn>}
        {r.status==='enviada'  && <Btn sm variant="primary" onClick={()=>startReceive(r)}>Recibir</Btn>}
        {r.status==='borrador' && <Btn sm variant="danger" onClick={()=>deleteOC(r)}>✕</Btn>}
      </div>
    )},
  ];

  const [filterSt, setFilterSt] = useState('todas');
  const filteredPOs = pos.filter(p=>filterSt==='todas'||p.status===filterSt);

  return (
    <div>
      <div style={{display:'flex',gap:8,alignItems:'center',marginBottom:14,flexWrap:'wrap'}}>
        {['todas','borrador','enviada','recibida'].map(s=>(
          <button key={s} onClick={()=>setFilterSt(s)} style={{background:filterSt===s?G.accent+'22':G.card2,border:`1px solid ${filterSt===s?G.accent:G.border}`,color:filterSt===s?G.accent:G.textSec,padding:'4px 12px',borderRadius:4,fontSize:12,fontWeight:600,cursor:'pointer',textTransform:'capitalize'}}>
            {s==='todas'?'Todas':s.charAt(0).toUpperCase()+s.slice(1)}
          </button>
        ))}
        <div style={{flex:1}}/>
        <Btn onClick={()=>setShowNew(true)}>+ Nueva OC</Btn>
      </div>
      <Card noPad>
        <Table cols={cols} rows={filteredPOs} emptyMsg="Sin órdenes de compra"/>
      </Card>

      {/* Modal nueva OC */}
      {showNew && (
        <Modal title="Nueva Orden de Compra" onClose={()=>setShowNew(false)} width={660}>
          <Row>
            <FSelect label="Proveedor *" value={form.supplierId} onChange={onSupplierChange}
              options={[{value:'',label:'Seleccionar proveedor…'},...suppliers.map(s=>({value:s.id,label:s.name}))]}/>
            <FInput label="Fecha" type="date" value={form.date} onChange={e=>sf('date',e.target.value)}/>
          </Row>
          <Row>
            <FSelect label="Condición de pago" value={form.creditDays} onChange={e=>sf('creditDays',e.target.value)}
              options={[{value:'0',label:'Contado'},{value:'15',label:'15 días'},{value:'30',label:'30 días'},{value:'45',label:'45 días'},{value:'60',label:'60 días'},{value:'90',label:'90 días'}]}/>
            <div style={{display:'flex',alignItems:'flex-end',paddingBottom:2}}>
              {form.creditDays>0
                ? <span style={{fontSize:12,color:G.warning}}>Pago a {form.creditDays} días desde recepción</span>
                : <span style={{fontSize:12,color:G.textSec}}>Pago al contado</span>
              }
            </div>
          </Row>
          <div style={{...T.sm,marginBottom:8,textTransform:'uppercase',letterSpacing:0.5}}>Productos</div>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar y agregar producto…" style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:5,color:G.text,padding:'7px 12px',fontSize:13,width:'100%',outline:'none',fontFamily:"'Inter',sans-serif",boxSizing:'border-box',marginBottom:8}}/>
          {search && (
            <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,marginBottom:10,maxHeight:140,overflowY:'auto'}}>
              {filteredProds.slice(0,6).map(p=>{
                const exists = form.lines.find(l=>l.productId===p.id);
                return (
                  <div key={p.id} onClick={()=>!exists&&addProduct(p)} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'7px 12px',cursor:exists?'default':'pointer',borderBottom:`1px solid ${G.border}22`,opacity:exists?0.5:1}} onMouseEnter={e=>!exists&&(e.currentTarget.style.background=G.card2)} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                    <div>
                      <div style={{fontSize:12,color:G.text}}>{p.name}</div>
                      <div style={{fontSize:10,color:G.textSec}}>{p.brand} · {p.um||'UND'}</div>
                    </div>
                    <div style={{textAlign:'right'}}>
                      <div style={{color:G.accent,fontWeight:600,fontSize:12}}>{fmtS(p.buy||0)}</div>
                      {exists && <span style={{fontSize:10,color:G.textSec}}>Ya agregado</span>}
                    </div>
                  </div>
                );
              })}
              {filteredProds.length===0 && <div style={{padding:12,color:G.textSec,fontSize:12}}>Sin resultados</div>}
            </div>
          )}
          {form.lines.length>0 && (
            <table style={{width:'100%',borderCollapse:'collapse',marginBottom:12}}>
              <thead><tr>
                {['ITEM','DESCRIPCIÓN','U.M.','CANT.','COSTO','TOTAL',''].map(h=><th key={h} style={{padding:'5px 8px',textAlign:'left',fontSize:9,color:G.textSec,fontWeight:700,textTransform:'uppercase',borderBottom:`1px solid ${G.border}`}}>{h}</th>)}
              </tr></thead>
              <tbody>
                {form.lines.map((l,i)=>{
                  const lineTotal = (+l.qty||0)*(+l.cost||0);
                  return (
                    <tr key={l.productId}>
                      <td style={{padding:'6px 8px',fontSize:12,color:G.textSec}}>{i+1}</td>
                      <td style={{padding:'6px 8px',fontSize:12,color:G.text}}>{l.name}</td>
                      <td style={{padding:'6px 8px',fontSize:11,color:G.textSec}}>{l.um}</td>
                      <td style={{padding:'6px 8px'}}><input type="number" min={1} value={l.qty} onChange={e=>setLineQty(l.productId,e.target.value)} style={{width:50,background:G.bg,border:`1px solid ${G.border}`,borderRadius:4,color:G.text,padding:'3px 6px',fontSize:12,textAlign:'center'}}/></td>
                      <td style={{padding:'6px 8px'}}><input type="number" step="0.01" value={l.cost} onChange={e=>setLineCost(l.productId,e.target.value)} style={{width:80,background:G.bg,border:`1px solid ${G.border}`,borderRadius:4,color:G.text,padding:'3px 6px',fontSize:12}}/></td>
                      <td style={{padding:'6px 8px',fontSize:12,fontWeight:700,color:G.text}}>{fmtS(lineTotal)}</td>
                      <td style={{padding:'6px 8px'}}><button onClick={()=>remLine(l.productId)} style={{background:'none',border:'none',color:G.error,cursor:'pointer',fontSize:13}}>✕</button></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
          {form.lines.length===0 && <div style={{color:G.textSec,fontSize:12,textAlign:'center',padding:20}}>Busca y agrega productos usando el campo de arriba</div>}
          <FTextarea label="Notas (opcional)" value={form.notes} onChange={e=>sf('notes',e.target.value)} rows={2} placeholder="Instrucciones al proveedor…"/>
          <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'8px 14px',marginBottom:14,display:'flex',justifyContent:'space-between'}}>
            <span style={{...T.sm}}>Total OC:</span>
            <span style={{color:G.warning,fontWeight:700}}>{fmtS(subtotal)}</span>
          </div>
          <div style={{display:'flex',justifyContent:'flex-end',gap:8}}>
            <Btn variant="secondary" onClick={()=>setShowNew(false)}>Cancelar</Btn>
            <Btn onClick={saveOC} disabled={saving||!form.supplierId}>{saving?'Guardando…':'Guardar OC'}</Btn>
          </div>
        </Modal>
      )}

      {/* Modal confirmar recepción (pedir N° factura) */}
      {receiveOC && (
        <Modal title={`Confirmar recepción — OC #${receiveOC.id}`} onClose={()=>{setReceiveOC(null);setIsHistorical(false);}} width={440}>
          <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'12px 14px',marginBottom:16}}>
            <div style={{fontSize:12,color:G.textSec,marginBottom:6}}>Proveedor: <b style={{color:G.text}}>{receiveOC.supplier}</b></div>
            <div style={{fontSize:12,color:G.textSec}}>Total: <b style={{color:G.warning}}>{fmtS(receiveOC.total)}</b>
              {receiveOC.creditDays>0 && <span style={{marginLeft:8,fontSize:11}}>(Crédito {receiveOC.creditDays} días)</span>}
            </div>
          </div>
          <FInput label="N° de Factura del proveedor (opcional)" value={invoiceNum} onChange={e=>setInvoiceNum(e.target.value)} placeholder="Ej: F001-00123456"/>
          {isAdmin && (
            <label style={{display:'flex',alignItems:'center',gap:8,marginBottom:14,cursor:'pointer',padding:'8px 10px',background:G.card2,borderRadius:5}}>
              <input type="checkbox" checked={isHistorical} onChange={e=>setIsHistorical(e.target.checked)} style={{accentColor:G.accent}} />
              <span style={{fontSize:12,color:G.text}}>
                <b>Compra histórica</b> — Usar fecha de OC ({receiveOC.date}) como fecha de entrada de stock
              </span>
            </label>
          )}
          <div style={{fontSize:11,color:G.textSec,marginBottom:16}}>
            Al confirmar: se registrará la entrada de stock {isHistorical ? `con fecha ${receiveOC.date}` : 'con fecha de hoy'} y {receiveOC.creditDays>0?`se generará un gasto a ${receiveOC.creditDays} días.`:'se generará el gasto como pagado.'}
          </div>
          <div style={{display:'flex',justifyContent:'flex-end',gap:8}}>
            <Btn variant="secondary" onClick={()=>{setReceiveOC(null);setIsHistorical(false);}}>Cancelar</Btn>
            <Btn onClick={confirmReceive} disabled={receiving}>{receiving?'Procesando…':'Confirmar recepción'}</Btn>
          </div>
        </Modal>
      )}

      {/* Modal detalle OC */}
      {viewDetail && (
        <Modal title={`Orden de Compra #${viewDetail.id}`} onClose={()=>setViewDetail(null)} width={560}>
          <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'12px 16px',marginBottom:16}}>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
              <div><div style={{...T.sm}}>Proveedor</div><div style={{fontWeight:600}}>{viewDetail.supplier||'—'}</div></div>
              <div><div style={{...T.sm}}>Fecha</div><div>{viewDetail.date}</div></div>
              <div><div style={{...T.sm}}>Estado</div><OCBadge status={viewDetail.status}/></div>
              <div><div style={{...T.sm}}>Total</div><div style={{fontWeight:700,color:G.warning,fontSize:15}}>{fmtS(viewDetail.total)}</div></div>
              <div><div style={{...T.sm}}>Condición pago</div><div style={{fontSize:12}}>{viewDetail.creditDays>0?`${viewDetail.creditDays} días`:'Contado'}</div></div>
              {viewDetail.invoiceNum && <div><div style={{...T.sm}}>Factura proveedor</div><div style={{fontSize:12,color:G.accent,fontWeight:600}}>{viewDetail.invoiceNum}</div></div>}
            </div>
            {viewDetail.notes && <div style={{marginTop:10,fontSize:12,color:G.textSec}}>📝 {viewDetail.notes}</div>}
          </div>
          <div style={{...T.sm,marginBottom:8,textTransform:'uppercase',letterSpacing:0.5}}>Items</div>
          <div style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,overflow:'hidden',marginBottom:16}}>
            <table style={{width:'100%',borderCollapse:'collapse'}}>
              <thead><tr style={{borderBottom:`1px solid ${G.border}`}}>
                {['Producto','Cant.','Costo unit.','Total'].map(h=><th key={h} style={{padding:'7px 12px',textAlign:'left',fontSize:10,color:G.textSec,fontWeight:700,textTransform:'uppercase'}}>{h}</th>)}
              </tr></thead>
              <tbody>
                {(viewDetail.items||[]).map((it,i)=>(
                  <tr key={i} style={{borderBottom:`1px solid ${G.border}22`}}>
                    <td style={{padding:'8px 12px',fontSize:12}}>{it.productName}</td>
                    <td style={{padding:'8px 12px',fontSize:12,textAlign:'center'}}>{it.qty}</td>
                    <td style={{padding:'8px 12px',fontSize:12}}>{fmtS(it.cost)}</td>
                    <td style={{padding:'8px 12px',fontSize:12,fontWeight:700,color:G.warning}}>{fmtS(it.total)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div style={{display:'flex',justifyContent:'flex-end',gap:8}}>
            {viewDetail.status==='borrador' && <Btn variant="accent" onClick={()=>updateStatus(viewDetail,'enviada')}>✉ Marcar Enviada</Btn>}
            {viewDetail.status==='enviada'  && <Btn variant="primary" onClick={()=>startReceive(viewDetail)}>📦 Marcar Recibida</Btn>}
            <Btn variant="ghost" onClick={()=>setViewPDF(viewDetail)}>📄 PDF</Btn>
            <Btn variant="secondary" onClick={()=>setViewDetail(null)}>Cerrar</Btn>
          </div>
        </Modal>
      )}

      {/* PDF */}
      {viewPDF && <OCPDF po={viewPDF} onClose={()=>setViewPDF(null)} currentUser={currentUser}/>}
    </div>
  );
}

// ── COMPRAS (página principal) ───────────────────────────────
function Compras({ products, setProducts, contacts, currentUser, setMonthly }) {
  const [tab, setTab] = useState('dashboard');
  const [movements, setMovements] = useState([]);
  const [pos, setPOs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showBuyModal, setShowBuyModal] = useState(false);
  const [filterYear, setFilterYear] = useState('todos');
  const [filterMonth, setFilterMonth] = useState('todos');

  useEffect(() => {
    Promise.all([
      window.api('/movements').then(r => r && r.json()).catch(() => []),
      window.api('/purchase-orders').then(r => r && r.json()).catch(() => []),
    ]).then(([movData, poData]) => {
      if (Array.isArray(movData)) setMovements(movData);
      if (Array.isArray(poData))  setPOs(poData);
      setLoading(false);
    });
  }, []);

  const entradas = movements.filter(m => m.type === 'entrada');

  const availYears = ['todos', ...[...new Set(
    entradas.map(e => { const { yyyy } = parseDateParts(e.date); return String(yyyy); }).filter(y => y !== '0')
  )].sort((a, b) => +b - +a)];

  const refreshProducts = () => {
    window.api('/products').then(r => r && r.json()).then(d => { if (Array.isArray(d)) setProducts(d); });
  };
  const refreshMovements = () => {
    window.api('/movements').then(r => r && r.json()).then(d => { if (Array.isArray(d)) setMovements(d); });
  };
  const refreshMonthly = () => {
    if (!setMonthly) return;
    window.api('/monthly?all=1').then(r => r && r.json()).then(d => { if (Array.isArray(d) && d.length) setMonthly(d); });
  };

  const handleNewPurchase = (created) => {
    setMovements(ms => [created, ...ms]);
    refreshProducts();
    refreshMonthly();
    if (window.refreshDashboard) window.refreshDashboard();
    setShowBuyModal(false);
  };

  const handleDelete = (id) => {
    setMovements(ms => ms.filter(m => m.id !== id));
    refreshProducts();
    refreshMonthly();
    if (window.refreshDashboard) window.refreshDashboard();
  };

  const handleReceiveOC = () => {
    refreshMovements();
    refreshProducts();
    refreshMonthly();
    if (window.refreshDashboard) window.refreshDashboard();
  };

  const tabs = ['Dashboard', 'Historial', 'Histórico de Precios', 'Órdenes de Compra'];
  const tabKey = { 'Dashboard':'dashboard', 'Historial':'historial', 'Histórico de Precios':'precios', 'Órdenes de Compra':'oc' };

  return (
    <div>
      <PageHeader title="COMPRAS" subtitle="Gestión de adquisiciones y proveedores"/>
      <Tabs tabs={tabs} active={tabs.find(t=>tabKey[t]===tab)||tabs[0]} onChange={t=>setTab(tabKey[t])}/>
      {loading
        ? <div style={{color:G.textSec,fontSize:13,padding:24}}>Cargando datos…</div>
        : (
          <>
            {tab === 'dashboard'  && <DashboardCompras entradas={entradas} pos={pos} filterYear={filterYear} filterMonth={filterMonth} setFilterYear={setFilterYear} setFilterMonth={setFilterMonth} availYears={availYears}/>}
            {tab === 'historial'  && <HistorialCompras entradas={entradas} onNew={()=>setShowBuyModal(true)} currentUser={currentUser} onDelete={handleDelete} filterYear={filterYear} filterMonth={filterMonth} setFilterYear={setFilterYear} setFilterMonth={setFilterMonth} availYears={availYears}/>}
            {tab === 'precios'    && <HistoricoPreciosCompras entradas={entradas}/>}
            {tab === 'oc'         && <OrdenesCompra pos={pos} setPOs={setPOs} contacts={contacts} products={products} currentUser={currentUser} onReceive={handleReceiveOC}/>}
          </>
        )
      }
      {showBuyModal && <FormCompra contacts={contacts} products={products} onSave={handleNewPurchase} onClose={()=>setShowBuyModal(false)}/>}
    </div>
  );
}

Object.assign(window, { Compras });
