/* ============================================================
   DASHBOARD · consumos, resumen, histórico, ingeniería de menú
   ============================================================ */
const MONTHS_ES = ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'];
const effectivePrice = (p) => (p && p.price != null) ? p.price : ((p && p.variants && p.variants[0] && p.variants[0].price) || 0);
const curMonth = () => { const d=new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`; };
const monthLabel = (m) => { const [y,mo]=m.split('-'); return `${MONTHS_ES[+mo-1]} ${y}`; };

/* ---- daily consumption entry ---- */
function ConsumosDia() {
  const store = useStore();
  const { data, productIndex } = store;
  const [date, setDate] = useState(store.todayISO());
  const [cartaId, setCartaId] = useState(data.cartas[0].id);
  const [query, setQuery] = useState('');
  const [entries, setEntries] = useState({});
  const [onlyWith, setOnlyWith] = useState(false);

  useEffect(() => { setEntries({ ...(data.sales[date] || {}) }); }, [date, data.sales]);

  const carta = data.cartas.find(c => c.id === cartaId);
  const q = query.trim().toLowerCase();
  const rows = useMemo(() => {
    const out = [];
    carta.categories.forEach(cat => cat.subcats.forEach(s => s.products.forEach(p => {
      if (q && !p.name.toLowerCase().includes(q)) return;
      if (onlyWith && !(entries[p.id] > 0)) return;
      out.push({ p, cat });
    })));
    return out;
  }, [carta, q, onlyWith, entries]);

  const setQty = (pid, v) => { const n = Math.max(0, parseInt(v||0,10)||0); setEntries(e => ({ ...e, [pid]: n })); };
  const dirty = JSON.stringify(entries) !== JSON.stringify(data.sales[date] || {});

  const dayUnits = Object.values(entries).reduce((a,b)=>a+b,0);
  const dayRevenue = Object.entries(entries).reduce((a,[pid,q])=>a + q*effectivePrice(productIndex[pid]),0);

  return (
    <div style={accentVars(cartaId)}>
      <div className="stat-grid">
        <div className="stat"><div className="s-l">Fecha seleccionada</div>
          <input className="input" type="date" value={date} onChange={e=>setDate(e.target.value)} style={{marginTop:8,fontFamily:'var(--font-display)',fontSize:18}}/></div>
        <div className="stat"><div className="s-l">Unidades del día</div><div className="s-v">{dayUnits}</div></div>
        <div className="stat"><div className="s-l">Venta estimada</div><div className="s-v" style={{color:'var(--accent-deep)'}}>{store.money(dayRevenue)}</div><div className="s-sub">según precios actuales</div></div>
        <div className="stat" style={{display:'flex',flexDirection:'column',justifyContent:'center',gap:10}}>
          <button className="btn block" disabled={!dirty} onClick={()=>store.saveSalesBatch(date, entries)}><Icon name="save" size={16}/> Guardar consumos</button>
          {dirty && <div style={{fontSize:11.5,color:'var(--ocre-deep)',textAlign:'center'}}>Hay cambios sin guardar</div>}
        </div>
      </div>

      <div className="card">
        <div className="card-h">
          <h3>Registro de consumos</h3>
          <div style={{display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}}>
            <div className="searchbar" style={{margin:0,padding:'7px 13px'}}><Icon name="search" size={15} style={{color:'var(--ink-faint)'}}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Buscar producto…" style={{width:140}}/></div>
            <button className={'dash-tab'+(onlyWith?' active':'')} onClick={()=>setOnlyWith(v=>!v)}>Solo con consumo</button>
          </div>
        </div>
        <div className="carta-pick" style={{padding:'0 0 14px'}}>
          {data.cartas.map(c=>(
            <button key={c.id} className={cartaId===c.id?'active':''} onClick={()=>setCartaId(c.id)} style={cartaId===c.id?accentVars(c.id):null}>
              <Icon name={themeFor(c.id).icon} size={14} style={{verticalAlign:'-2px',marginRight:5}}/>{c.name}
            </button>
          ))}
        </div>
        {rows.length===0 ? <div className="empty">Sin productos para mostrar.</div> :
          rows.map(({p,cat})=>(
            <div key={p.id} className="day-prod-row">
              <div className="dp-main">
                <div className="dp-name">{p.featured&&<Icon name="star" size={12} fill style={{color:'var(--ocre-deep)',verticalAlign:'-1px',marginRight:4}}/>}{p.name}</div>
                <div className="dp-cat">{cat.name} · {store.money(effectivePrice(p))}</div>
              </div>
              <div className="qty-input">
                <button onClick={()=>setQty(p.id,(entries[p.id]||0)-1)}><Icon name="minus" size={15}/></button>
                <input value={entries[p.id]||0} onChange={e=>setQty(p.id,e.target.value)} inputMode="numeric"/>
                <button onClick={()=>setQty(p.id,(entries[p.id]||0)+1)}><Icon name="plus" size={15}/></button>
              </div>
            </div>
          ))}
      </div>
    </div>
  );
}

/* ---- monthly aggregation ---- */
function useMonthAgg(month) {
  const { data, productIndex } = useStore();
  return useMemo(() => {
    const perProduct = {}; let totalUnits=0, totalRevenue=0; const perCategory={}; const perCarta={};
    const daily = {};
    Object.entries(data.sales).forEach(([date, items]) => {
      if (!date.startsWith(month)) return;
      let dRev=0, dUnits=0;
      Object.entries(items).forEach(([pid, qty]) => {
        const p = productIndex[pid]; if (!p) return;
        const rev = qty * effectivePrice(p);
        perProduct[pid] = (perProduct[pid]||0) + qty;
        totalUnits += qty; totalRevenue += rev;
        perCategory[p.catName] = (perCategory[p.catName]||0) + rev;
        perCarta[p.cartaName] = (perCarta[p.cartaName]||0) + rev;
        dRev += rev; dUnits += qty;
      });
      daily[date] = { revenue:dRev, units:dUnits };
    });
    return { perProduct, totalUnits, totalRevenue, perCategory, perCarta, daily };
  }, [data.sales, productIndex, month]);
}

function MonthPicker({ month, setMonth }) {
  return (
    <div style={{display:'flex',alignItems:'center',gap:6}}>
      <button className="iconbtn" onClick={()=>{const [y,m]=month.split('-').map(Number);const d=new Date(y,m-2,1);setMonth(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`);}}><Icon name="chevleft" size={18}/></button>
      <span className="chip" style={{minWidth:120,justifyContent:'center',fontFamily:'var(--font-display)',fontSize:15,textTransform:'capitalize'}}>{monthLabel(month)}</span>
      <button className="iconbtn" onClick={()=>{const [y,m]=month.split('-').map(Number);const d=new Date(y,m,1);setMonth(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`);}}><Icon name="chevright" size={18}/></button>
    </div>
  );
}

/* ---- resumen mensual ---- */
function ResumenMes() {
  const store = useStore();
  const { productIndex } = store;
  const [month, setMonth] = useState(curMonth());
  const agg = useMonthAgg(month);
  const top = Object.entries(agg.perProduct).map(([pid,u])=>({p:productIndex[pid],u,rev:u*effectivePrice(productIndex[pid])})).filter(x=>x.p).sort((a,b)=>b.u-a.u);
  const maxU = top[0]?.u || 1;
  const cats = Object.entries(agg.perCategory).sort((a,b)=>b[1]-a[1]);
  const maxCat = cats[0]?.[1] || 1;
  const daysWithData = Object.keys(agg.daily).length;

  return (
    <div style={accentVars('restaurante')}>
      <div className="section-bar"><div/><MonthPicker month={month} setMonth={setMonth}/></div>
      <div className="stat-grid">
        <div className="stat"><div className="s-l">Venta del mes</div><div className="s-v" style={{color:'var(--accent-deep)'}}>{store.money(agg.totalRevenue)}</div></div>
        <div className="stat"><div className="s-l">Unidades vendidas</div><div className="s-v">{agg.totalUnits}</div></div>
        <div className="stat"><div className="s-l">Ticket prom. / día</div><div className="s-v">{store.money(daysWithData?agg.totalRevenue/daysWithData:0)}</div><div className="s-sub">{daysWithData} días con registro</div></div>
        <div className="stat"><div className="s-l">Productos distintos</div><div className="s-v">{top.length}</div></div>
      </div>

      {top.length===0 ? <div className="card"><div className="empty">No hay consumos registrados en {monthLabel(month)}. Regístralos en la pestaña “Consumos”.</div></div> : (
        <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:18}} className="resumen-cols">
          <div className="card">
            <div className="card-h"><h3>Más vendidos</h3><span className="chip"><Icon name="trend" size={14}/> top {Math.min(12,top.length)}</span></div>
            <table className="gc">
              <thead><tr><th>#</th><th>Producto</th><th className="num">Unid.</th><th style={{width:'30%'}}>Mix</th><th className="num">Venta</th></tr></thead>
              <tbody>
                {top.slice(0,12).map((x,i)=>(
                  <tr key={x.p.id}><td style={{color:'var(--ink-faint)',fontWeight:700}}>{i+1}</td>
                    <td><b style={{fontWeight:600}}>{x.p.name}</b><div style={{fontSize:11.5,color:'var(--ink-faint)'}}>{x.p.cartaName}</div></td>
                    <td className="num">{x.u}</td>
                    <td><div className="bar-track"><div className="bar-fill" style={{width:`${x.u/maxU*100}%`}}/></div></td>
                    <td className="num">{store.money(x.rev)}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="card">
            <div className="card-h"><h3>Venta por categoría</h3></div>
            <table className="gc">
              <tbody>
                {cats.map(([name,rev])=>(
                  <tr key={name}><td><b style={{fontWeight:600}}>{name}</b><div className="bar-track" style={{marginTop:5}}><div className="bar-fill" style={{width:`${rev/maxCat*100}%`}}/></div></td><td className="num" style={{verticalAlign:'top'}}>{store.money(rev)}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- histórico (gráfico por fechas) ---- */
function Historico() {
  const store = useStore();
  const [month, setMonth] = useState(curMonth());
  const [metric, setMetric] = useState('revenue');
  const agg = useMonthAgg(month);
  const [y,m] = month.split('-').map(Number);
  const days = new Date(y, m, 0).getDate();
  const series = Array.from({length:days}, (_,i)=>{ const key=`${month}-${String(i+1).padStart(2,'0')}`; const d=agg.daily[key]||{revenue:0,units:0}; return { day:i+1, ...d }; });
  const maxV = Math.max(1, ...series.map(s=>s[metric]));
  const W=720, H=240, pad=34, bw=(W-pad*2)/days;

  return (
    <div style={accentVars('aromas')}>
      <div className="section-bar">
        <div className="dash-tabs" style={{margin:0}}>
          <button className={'dash-tab'+(metric==='revenue'?' active':'')} onClick={()=>setMetric('revenue')}>Ventas $</button>
          <button className={'dash-tab'+(metric==='units'?' active':'')} onClick={()=>setMetric('units')}>Unidades</button>
        </div>
        <MonthPicker month={month} setMonth={setMonth}/>
      </div>
      <div className="card">
        <div className="card-h"><h3 style={{textTransform:'capitalize'}}>{monthLabel(month)}</h3>
          <span className="chip">{metric==='revenue'?'Venta total: '+store.money(agg.totalRevenue):'Total: '+agg.totalUnits+' unid.'}</span></div>
        <div style={{overflowX:'auto'}}>
          <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%',minWidth:560,height:'auto'}}>
            {[0,.25,.5,.75,1].map(t=>{const yy=pad+(H-pad*2)*(1-t);return <g key={t}><line x1={pad} y1={yy} x2={W-pad} y2={yy} stroke="var(--line-soft)"/><text x={pad-6} y={yy+3} textAnchor="end" fontSize="9" fill="var(--ink-faint)">{metric==='revenue'?'$'+Math.round(maxV*t/1000)+'k':Math.round(maxV*t)}</text></g>;})}
            {series.map(s=>{const h=(H-pad*2)*(s[metric]/maxV);const x=pad+s.day*bw-bw+bw*0.15;return (
              <g key={s.day}>
                <rect x={x} y={H-pad-h} width={bw*0.7} height={h} rx="2" fill="var(--accent)" opacity={s[metric]?0.92:0.12}>
                  <title>{`${s.day} ${MONTHS_ES[m-1]}: ${metric==='revenue'?store.money(s.revenue):s.units+' u'}`}</title>
                </rect>
                {(s.day===1||s.day%5===0||s.day===days)&&<text x={x+bw*0.35} y={H-pad+13} textAnchor="middle" fontSize="9" fill="var(--ink-faint)">{s.day}</text>}
              </g>);})}
          </svg>
        </div>
        {agg.totalUnits===0 && <div className="empty" style={{marginTop:-10}}>Sin datos en este mes. Registra consumos para ver la tendencia.</div>}
      </div>
    </div>
  );
}

/* ---- ingeniería de menú ---- */
function IngenieriaMenu() {
  const store = useStore();
  const { productIndex } = store;
  const [month, setMonth] = useState(curMonth());
  const agg = useMonthAgg(month);

  const sold = Object.entries(agg.perProduct).map(([pid,u])=>{
    const p = productIndex[pid]; if(!p) return null;
    const price = effectivePrice(p);
    const cm = (p.cost!=null) ? price - p.cost : null;
    return { p, u, price, cm };
  }).filter(Boolean);
  const withCost = sold.filter(x=>x.cm!=null);
  const noCost = sold.filter(x=>x.cm==null);

  const n = withCost.length;
  const totalU = withCost.reduce((a,b)=>a+b.u,0);
  const popThresh = n? (0.7*(totalU/n)) : 0;          // 70% of avg units
  const avgCM = n? withCost.reduce((a,b)=>a+b.cm,0)/n : 0;
  const classify = (x)=>{ const hp=x.u>=popThresh, hm=x.cm>=avgCM; return hp&&hm?'star':hp&&!hm?'horse':!hp&&hm?'puzzle':'dog'; };
  const groups = {star:[],horse:[],puzzle:[],dog:[]};
  withCost.forEach(x=>groups[classify(x)].push(x));
  const META = {
    star:{l:'Estrellas',d:'Alta popularidad + alto margen. Destácalas.'},
    horse:{l:'Caballos de batalla',d:'Muy pedidas, margen bajo. Optimiza costos.'},
    puzzle:{l:'Enigmas',d:'Buen margen, poca venta. Promociónalas.'},
    dog:{l:'Perros',d:'Baja venta y margen. Revisar o retirar.'},
  };

  return (
    <div style={accentVars('restaurante')}>
      <div className="section-bar">
        <div><p className="admin-sub" style={{margin:0}}>Clasificación Kasavana-Smith según consumos y margen (precio − costo).</p></div>
        <MonthPicker month={month} setMonth={setMonth}/>
      </div>

      {noCost.length>0 && (
        <div className="card" style={{background:'var(--accent-tint)',borderColor:'color-mix(in srgb,var(--accent) 30%,transparent)'}}>
          <div style={{display:'flex',gap:12,alignItems:'flex-start'}}>
            <Icon name="info" size={20} style={{color:'var(--accent-deep)',marginTop:2}}/>
            <div style={{fontSize:13.5,color:'var(--ink-soft)',lineHeight:1.6}}>
              <b style={{color:'var(--ink)'}}>{noCost.length} producto(s) con ventas aún no tienen costo asignado</b> y no se pueden clasificar. Agrega el costo en <b>Contenido → editar producto → Costo</b> para completar el análisis.
            </div>
          </div>
        </div>
      )}

      {withCost.length===0 ? (
        <div className="card"><div className="empty">Aún no hay productos con costo <i>y</i> consumos en {monthLabel(month)}.<br/>Registra costos y ventas para activar la ingeniería de menú.</div></div>
      ) : (
        <>
          <div className="quad-grid" style={{marginBottom:18}}>
            {['star','horse','puzzle','dog'].map(k=>(
              <div key={k} className={'quad '+k}>
                <div className="q-l">{META[k].l} <span style={{fontSize:13,color:'var(--ink-faint)'}}>· {groups[k].length}</span></div>
                <div className="q-d">{META[k].d}</div>
                <div className="q-items">
                  {groups[k].sort((a,b)=>b.u-a.u).slice(0,6).map(x=>(
                    <div key={x.p.id} style={{display:'flex',justifyContent:'space-between',gap:8}}><span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{x.p.name}</span><span style={{color:'var(--ink-faint)',whiteSpace:'nowrap'}}>{x.u}u · {store.money(x.cm)}</span></div>
                  ))}
                  {groups[k].length===0&&<span style={{color:'var(--ink-faint)'}}>—</span>}
                </div>
              </div>
            ))}
          </div>
          <div className="card">
            <div className="card-h"><h3>Detalle</h3><span className="chip">umbral pop.: {popThresh.toFixed(1)}u · margen prom.: {store.money(avgCM)}</span></div>
            <div style={{overflowX:'auto'}}>
              <table className="gc">
                <thead><tr><th>Producto</th><th className="num">Unid.</th><th className="num">Precio</th><th className="num">Costo</th><th className="num">Margen</th><th>Clase</th></tr></thead>
                <tbody>
                  {withCost.sort((a,b)=>b.u-a.u).map(x=>{const k=classify(x);return(
                    <tr key={x.p.id}><td><b style={{fontWeight:600}}>{x.p.name}</b></td><td className="num">{x.u}</td><td className="num">{store.money(x.price)}</td><td className="num">{store.money(x.p.cost)}</td><td className="num" style={{color:'var(--accent-deep)',fontWeight:600}}>{store.money(x.cm)}</td><td><span className="chip" style={{fontSize:11}}>{META[k].l.replace(/s$/,'')}</span></td></tr>
                  );})}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

/* ---- dashboard shell ---- */
function Dashboard() {
  const [tab, setTab] = useState('consumos');
  const TABS = [
    {k:'consumos', l:'Consumos del día', icon:'calendar'},
    {k:'resumen', l:'Resumen mensual', icon:'chart'},
    {k:'historico', l:'Histórico', icon:'trend'},
    {k:'ingenieria', l:'Ingeniería de menú', icon:'grid'},
  ];
  return (
    <div>
      <div className="section-bar"><div>
        <h1 className="admin-h">Dashboard</h1>
        <p className="admin-sub">Registra consumos diarios y analiza el rendimiento de la carta.</p>
      </div></div>
      <div className="dash-tabs">
        {TABS.map(t=>(<button key={t.k} className={'dash-tab'+(tab===t.k?' active':'')} onClick={()=>setTab(t.k)}><Icon name={t.icon} size={15} style={{verticalAlign:'-2px',marginRight:6}}/>{t.l}</button>))}
      </div>
      {tab==='consumos'&&<ConsumosDia/>}
      {tab==='resumen'&&<ResumenMes/>}
      {tab==='historico'&&<Historico/>}
      {tab==='ingenieria'&&<IngenieriaMenu/>}
    </div>
  );
}

Object.assign(window, { Dashboard });
