// ── REPORTES v2 — localStorage ───────────────────────

function Reportes() {
  const { useState } = React;
  const [tab, setTab] = useState('hoy');
  const ventas  = lsGet('ventas',[]);
  const ordenes = lsGet('ordenes',[]);
  const hoyStr  = hoy();
  const ventasHoy = ventas.filter(v=>v.fecha?.slice(0,10)===hoyStr);
  const totalHoy  = ventasHoy.reduce((s,v)=>s+(v.total||0),0);
  const hace7 = new Date(); hace7.setDate(hace7.getDate()-7);
  const ventasSem = ventas.filter(v=>v.fecha&&new Date(v.fecha)>=hace7);
  const totalSem  = ventasSem.reduce((s,v)=>s+(v.total||0),0);
  const {neto:netoHoy,iva:ivaHoy}=desglosarIVA(totalHoy);
  const porMedio={};
  ventas.forEach(v=>{ porMedio[v.medio]=(porMedio[v.medio]||0)+(v.total||0); });
  const otActivas=ordenes.filter(o=>o.estado!=='Entregado'&&o.estado!=='Cancelado');
  const S=repStyles;
  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      <div style={{display:'flex',borderBottom:'1px solid var(--border)',background:'var(--bg-card)',flexShrink:0}}>
        {[{id:'hoy',l:'Hoy'},{id:'semana',l:'Semana'},{id:'ventas',l:'Ventas'},{id:'ot',l:'Taller'}].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            style={{padding:'10px 16px',background:'transparent',border:'none',color:tab===t.id?'var(--cream)':'var(--cream-3)',cursor:'pointer',fontSize:'12px',fontFamily:'Inter,sans-serif',borderBottom:tab===t.id?'2px solid var(--gold)':'2px solid transparent'}}>
            {t.l}
          </button>
        ))}
      </div>
      <div style={{flex:1,overflowY:'auto',padding:'16px'}}>
        {tab==='hoy'&&(
          <div>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>
              {new Date().toLocaleDateString('es-CL',{weekday:'long',day:'numeric',month:'long'})}
            </div>
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'9px',marginBottom:'14px'}}>
              {[{l:'Ventas brutas',v:clp(totalHoy),c:'var(--gold)'},{l:'Neto',v:clp(netoHoy),c:'var(--cream)'},{l:'IVA 19%',v:clp(ivaHoy),c:'var(--cream-2)'},{l:'Transacciones',v:ventasHoy.length,c:'var(--cream)'},{l:'OT activas',v:otActivas.length,c:'#2980b9'},{l:'Valor en taller',v:clp(otActivas.reduce((s,o)=>s+(o.valorPresupuesto||0),0)),c:'#2980b9'}].map(k=>(
                <div key={k.l} style={S.kpiCard}><div style={{color:k.c,fontWeight:700,fontSize:'18px'}}>{k.v}</div><div style={{color:'var(--cream-3)',fontSize:'10px',marginTop:'3px'}}>{k.l}</div></div>
              ))}
            </div>
            {ventasHoy.length===0
              ? <div style={{textAlign:'center',padding:'36px',color:'var(--cream-3)'}}><div style={{fontSize:'28px',marginBottom:'8px'}}>📊</div>Sin ventas hoy aún. Usa el POS para registrarlas.</div>
              : <div style={S.card}><div style={S.cardTitle}>Ventas de hoy</div>
                  <table style={{width:'100%',borderCollapse:'collapse'}}>
                    <thead><tr>{['Folio','Cliente','Medio','Total'].map(h=><th key={h} style={inv2Styles.th}>{h}</th>)}</tr></thead>
                    <tbody>{ventasHoy.map((v,i)=>(
                      <tr key={i} style={inv2Styles.tr}>
                        <td style={inv2Styles.td}><span style={{fontFamily:'monospace',fontSize:'10px',color:'var(--cream-3)'}}>{v.folio}</span></td>
                        <td style={inv2Styles.td}><span style={{color:'var(--cream)',fontSize:'12px'}}>{v.clienteNombre||'Sin registro'}</span></td>
                        <td style={inv2Styles.td}><span style={{color:'var(--cream-2)',fontSize:'11px'}}>{v.medio}</span></td>
                        <td style={inv2Styles.td}><span style={{color:'var(--gold)',fontWeight:600}}>{clp(v.total)}</span></td>
                      </tr>
                    ))}</tbody>
                  </table>
                </div>
            }
          </div>
        )}
        {tab==='semana'&&(
          <div>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Últimos 7 días</div>
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'9px',marginBottom:'14px'}}>
              {[{l:'Total semana',v:clp(totalSem),c:'var(--gold)'},{l:'Transacciones',v:ventasSem.length,c:'var(--cream)'},{l:'Ticket promedio',v:ventasSem.length>0?clp(Math.round(totalSem/ventasSem.length)):'$0',c:'var(--cream-2)'}].map(k=>(
                <div key={k.l} style={S.kpiCard}><div style={{color:k.c,fontWeight:700,fontSize:'18px'}}>{k.v}</div><div style={{color:'var(--cream-3)',fontSize:'10px',marginTop:'3px'}}>{k.l}</div></div>
              ))}
            </div>
            {Object.keys(porMedio).length>0&&(
              <div style={S.card}><div style={S.cardTitle}>Por medio de pago</div>
                {Object.entries(porMedio).sort((a,b)=>b[1]-a[1]).map(([m,v])=>{
                  const pct=totalSem>0?Math.round(v/totalSem*100):0;
                  return <div key={m} style={{marginBottom:'8px'}}>
                    <div style={{display:'flex',justifyContent:'space-between',fontSize:'12px',marginBottom:'3px'}}><span style={{color:'var(--cream)'}}>{m}</span><span style={{color:'var(--gold)',fontWeight:600}}>{clp(v)}</span></div>
                    <div style={{height:'4px',background:'var(--surface)',borderRadius:'2px',overflow:'hidden'}}><div style={{height:'100%',width:`${pct}%`,background:'var(--gold)',borderRadius:'2px'}}/></div>
                  </div>;
                })}
              </div>
            )}
            {ventasSem.length===0&&<div style={{textAlign:'center',padding:'36px',color:'var(--cream-3)'}}><div style={{fontSize:'28px',marginBottom:'8px'}}>📈</div>Sin ventas en 7 días.</div>}
          </div>
        )}
        {tab==='ventas'&&(
          <div>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Historial de Ventas</div>
            {ventas.length===0
              ? <div style={{textAlign:'center',padding:'36px',color:'var(--cream-3)'}}><div style={{fontSize:'28px',marginBottom:'8px'}}>🛍</div>Sin ventas registradas. Usa el POS para vender.</div>
              : <table style={{width:'100%',borderCollapse:'collapse'}}>
                  <thead><tr>{['Folio','Fecha','Tienda','Cliente','Medio','Total'].map(h=><th key={h} style={inv2Styles.th}>{h}</th>)}</tr></thead>
                  <tbody>{[...ventas].reverse().map((v,i)=>(
                    <tr key={i} style={inv2Styles.tr}>
                      <td style={inv2Styles.td}><span style={{fontFamily:'monospace',fontSize:'10px',color:'var(--cream-3)'}}>{v.folio}</span></td>
                      <td style={inv2Styles.td}><span style={{fontSize:'11px',color:'var(--cream-3)'}}>{v.fecha?.slice(0,10)}</span></td>
                      <td style={inv2Styles.td}><span style={{fontSize:'10px',color:TIENDAS.find(t=>t.id===v.tienda)?.color||'var(--cream-3)'}}>{TIENDAS.find(t=>t.id===v.tienda)?.sigla||v.tienda}</span></td>
                      <td style={inv2Styles.td}><span style={{color:'var(--cream)',fontSize:'12px'}}>{v.clienteNombre||'Sin registro'}</span></td>
                      <td style={inv2Styles.td}><span style={{color:'var(--cream-3)',fontSize:'11px'}}>{v.medio}</span></td>
                      <td style={inv2Styles.td}><span style={{color:'var(--gold)',fontWeight:600}}>{clp(v.total)}</span></td>
                    </tr>
                  ))}</tbody>
                </table>
            }
          </div>
        )}
        {tab==='ot'&&(
          <div>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Resumen Taller</div>
            <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:'9px',marginBottom:'14px'}}>
              {['Recibido','En proceso','Listo','Entregado'].map(e=>{
                const cnt=ordenes.filter(o=>o.estado===e).length;
                const col={'Recibido':'#2980b9','En proceso':'#f39c12','Listo':'#27ae60','Entregado':'var(--cream-3)'}[e];
                return <div key={e} style={{...S.kpiCard,borderTop:`2px solid ${col}`}}><div style={{color:col,fontWeight:700,fontSize:'20px'}}>{cnt}</div><div style={{color:'var(--cream-3)',fontSize:'10px',marginTop:'3px'}}>{e}</div></div>;
              })}
            </div>
            {ordenes.length===0&&<div style={{textAlign:'center',padding:'36px',color:'var(--cream-3)'}}><div style={{fontSize:'28px',marginBottom:'8px'}}>🔧</div>Sin órdenes. Créalas en el módulo Taller / OT.</div>}
          </div>
        )}
      </div>
    </div>
  );
}

const repStyles = {
  kpiCard:{ background:'var(--bg-card)',border:'1px solid var(--border)',borderRadius:'12px',padding:'14px',textAlign:'center' },
  card:{ background:'var(--bg-card)',border:'1px solid var(--border)',borderRadius:'12px',padding:'14px' },
  cardTitle:{ fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600,color:'var(--cream)',marginBottom:'10px',paddingBottom:'7px',borderBottom:'1px solid var(--border)' },
};

Object.assign(window, { Reportes });
