// EUTPeru — Dashboard View
const { useState, useEffect } = React;
const G = window.C;

function Dashboard({ onNav }) {
  const { KPICard, BarChart, Card, Btn, DaysBadge, StockBadge, T } = window;
  const fmtS = window.fmtS;

  const [data,       setData]       = useState(null);
  const [activity,   setActivity]   = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [refreshKey, setRefreshKey] = useState(0);
  const [allMonthly, setAllMonthly] = useState([]);
  const [chartPage,  setChartPage]  = useState(0); // 0 = más recientes

  React.useEffect(() => {
    window.refreshDashboard = () => setRefreshKey(k => k + 1);
    return () => { delete window.refreshDashboard; };
  }, []);

  useEffect(() => {
    setLoading(true);
    Promise.all([
      window.api('/dashboard').then(r => r ? r.json() : null),
      window.api('/activity').then(r => r ? r.json() : null),
      window.api('/monthly?all=1').then(r => r ? r.json() : null),
    ]).then(([dash, acts, mly]) => {
      if (dash) setData(dash);
      if (Array.isArray(acts)) setActivity(acts);
      if (Array.isArray(mly) && mly.length) setAllMonthly(mly);
      setChartPage(0);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [refreshKey]);

  const now    = new Date();
  const mNames = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
  const mShort = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
  const currentYear  = String(now.getFullYear());

  const availYears = [...new Set(allMonthly.map(d => String(d.y)))].sort((a,b)=>+b-+a);
  if (!availYears.includes(currentYear)) availYears.unshift(currentYear);

  const [yearFilter,  setYearFilter]  = useState('todos');
  const [monthFilter, setMonthFilter] = useState('todos');

  const monthly   = data?.monthly   || [];
  const criticals = data?.criticals || [];
  const dueSoon   = data?.dueSoon   || [];
  const facturado = data?.facturado || 0;
  const cobrado   = data?.cobrado   || 0;
  const pendiente = data?.pendiente || 0;

  const cobPct   = facturado > 0 ? ((cobrado / facturado) * 100).toFixed(1) : '0.0';

  // ── Chart data + paginación por semestres fijos (Ene-Jun / Jul-Dic) ────
  const base = allMonthly.length ? allMonthly : monthly;
  const mToNum = { Ene:1,Feb:2,Mar:3,Abr:4,May:5,Jun:6,Jul:7,Ago:8,Sep:9,Oct:10,Nov:11,Dic:12 };

  // Construir lista ordenada de semestres con datos
  const halfSet = new Map();
  base.forEach(d => {
    const mn  = mToNum[d.m] || 0;
    const h   = mn <= 6 ? 0 : 1;
    const key = `${d.y}-${h}`;
    if (!halfSet.has(key)) halfSet.set(key, { y: d.y, half: h });
  });
  const nowMn  = now.getMonth() + 1;
  const nowH   = nowMn <= 6 ? 0 : 1;
  const nowKey = `${now.getFullYear()}-${nowH}`;
  if (!halfSet.has(nowKey)) halfSet.set(nowKey, { y: now.getFullYear(), half: nowH });
  const halfYears = [...halfSet.values()].sort((a,b) => a.y !== b.y ? a.y - b.y : a.half - b.half);

  const maxPage     = Math.max(0, halfYears.length - 1);
  const safePage    = Math.min(chartPage, maxPage);
  const currentHalf = halfYears[halfYears.length - 1 - safePage] || { y: now.getFullYear(), half: nowH };

  // Siempre exactamente 6 meses del semestre (ceros donde no haya datos)
  const halfStart  = currentHalf.half === 0 ? 1 : 7;
  const chartSlice = Array.from({length:6}, (_, i) => {
    const mn = halfStart + i;
    const ms = mShort[mn - 1];
    return base.find(d => d.y === currentHalf.y && d.m === ms) || { m: ms, y: currentHalf.y, v: 0, c: 0, co: 0 };
  });

  const chartLabel = currentHalf.half === 0
    ? `Enero — Junio ${currentHalf.y}`
    : `Julio — Diciembre ${currentHalf.y}`;

  const jumpToHalf = (y, m) => {
    let targetIdx = -1;
    if (m !== 'todos') {
      const mn = mNames.indexOf(m) + 1;
      const h  = mn <= 6 ? 0 : 1;
      const yr = y !== 'todos' ? Number(y) : now.getFullYear();
      targetIdx = halfYears.findIndex(hh => hh.y === yr && hh.half === h);
    } else if (y !== 'todos') {
      targetIdx = halfYears.reduce((last, hh, i) => String(hh.y) === String(y) ? i : last, -1);
    }
    setChartPage(targetIdx >= 0 ? halfYears.length - 1 - targetIdx : 0);
  };

  const handleYearChange  = (y) => { setYearFilter(y);  jumpToHalf(y, monthFilter); };
  const handleMonthChange = (m) => { setMonthFilter(m); jumpToHalf(yearFilter, m);  };

  const canPrev = safePage < maxPage;
  const canNext = safePage > 0;

  // KPIs del semestre (o del mes filtrado)
  const kpiSlice = monthFilter !== 'todos'
    ? chartSlice.filter(d => d.m === mShort[mNames.indexOf(monthFilter)])
    : chartSlice;
  const facturadoChart = kpiSlice.reduce((s,d) => s + (d.v||0), 0);
  const cobradoChart   = kpiSlice.reduce((s,d) => s + (d.co||0), 0);
  const pendienteChart = Math.max(0, facturadoChart - cobradoChart);
  const cobPctChart    = facturadoChart > 0 ? ((cobradoChart / facturadoChart) * 100).toFixed(1) : '0.0';
  const kpiLabel = monthFilter !== 'todos'
    ? `${monthFilter}${yearFilter !== 'todos' ? ' '+yearFilter : ''}`
    : chartLabel;
  const kpiSub = monthFilter !== 'todos' ? 'Mes filtrado' : 'Semestre';

  const navBtnSt = (disabled) => ({
    background: disabled ? G.card2 : G.accent+'22',
    border: `1px solid ${disabled ? G.border : G.accent}`,
    color: disabled ? G.border : G.accent,
    padding:'4px 12px', borderRadius:5, fontSize:12, fontWeight:700,
    cursor: disabled ? 'default' : 'pointer', lineHeight:1.4,
  });

  const selSt = {background:G.card2,border:`1px solid ${G.border}`,color:G.text,padding:'5px 9px',borderRadius:5,fontSize:12,cursor:'pointer'};

  if (loading) {
    return (
      <div style={{display:'flex',alignItems:'center',justifyContent:'center',height:300,color:G.textSec,fontSize:13}}>
        Cargando dashboard…
      </div>
    );
  }

  return (
    <div>
      {/* Header */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:22,paddingBottom:14,borderBottom:`1px solid ${G.border}`}}>
        <div>
          <h1 style={T.h1}>DASHBOARD</h1>
          <div style={{color:G.textSec,fontSize:11,marginTop:3}}>Resumen operativo — EUT Perú EIRL · RUC 20611733985</div>
        </div>
        <div style={{display:'flex',gap:6,alignItems:'center'}}>
          <select value={yearFilter} onChange={e=>handleYearChange(e.target.value)} style={selSt}>
            <option value="todos">Todos los años</option>
            {availYears.map(y=><option key={y} value={y}>{y}</option>)}
          </select>
          <select value={monthFilter} onChange={e=>handleMonthChange(e.target.value)} style={selSt}>
            <option value="todos">Todos los meses</option>
            {mNames.map(m=><option key={m} value={m}>{m}</option>)}
          </select>
          {(yearFilter!=='todos'||monthFilter!=='todos') && (
            <button onClick={()=>{setYearFilter('todos');setMonthFilter('todos');setChartPage(0);}} style={{background:'none',border:'none',color:G.accent,cursor:'pointer',fontSize:12}}>✕ Limpiar</button>
          )}
        </div>
      </div>

      {/* KPIs */}
      <div style={{display:'flex',gap:14,marginBottom:20,flexWrap:'wrap'}}>
        <KPICard
          label={`Total Facturado — ${kpiLabel}`}
          value={fmtS(facturadoChart)}
          sub={kpiSub}
          color={G.accent} icon="📈"/>
        <KPICard
          label="Total Cobrado"
          value={fmtS(cobradoChart)}
          sub={`${cobPctChart}% del facturado`}
          color={G.accent} icon="✅"/>
        <KPICard
          label="Pendiente de Cobro"
          value={fmtS(pendienteChart)}
          sub={`${dueSoon.length} factura${dueSoon.length!==1?'s':''} activa${dueSoon.length!==1?'s':''}`}
          color={G.warning} icon="⏳"/>
      </div>

      {/* Chart full width */}
      <div style={{marginBottom:14}}>
        <Card title={`Evolución de Ventas — ${chartLabel}`}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
            <button style={navBtnSt(!canPrev)} disabled={!canPrev} onClick={()=>setChartPage(p=>p+1)}>← Semestre anterior</button>
            <span style={{fontSize:11,color:G.textSec}}>{safePage===0?'Semestre actual':`Hace ${safePage} semestre${safePage>1?'s':''}`}</span>
            <button style={navBtnSt(!canNext)} disabled={!canNext} onClick={()=>setChartPage(p=>p-1)}>Semestre siguiente →</button>
          </div>
          <BarChart data={chartSlice} height={150}/>
          <div style={{display:'flex',marginTop:4}}>
            {chartSlice.map((d,i)=>(
              <div key={i} style={{flex:1,textAlign:'center'}}>
                <div style={{color:G.textSec,fontSize:9,marginBottom:1}}>{d.m}{d.y&&chartSlice.some(x=>x.y!==d.y)?' '+String(d.y).slice(2):''}</div>
                <div style={{color:d.v>0?G.accent:G.textSec,fontSize:10,fontWeight:700}}>{d.v>0?fmtS(d.v).replace('S/ ',''):'—'}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Bottom panels */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
        {/* Stock alerts */}
        <Card title="⚠️ Alertas de Stock Crítico" action={<Btn sm variant="ghost" onClick={()=>onNav('almacen')}>Ver Almacén →</Btn>} noPad>
          <div style={{padding:'0 18px 12px'}}>
            {criticals.length===0 && <div style={{color:G.textSec,fontSize:12,padding:'12px 0'}}>Sin alertas activas.</div>}
            {criticals.map(p=>(
              <div key={p.id} style={{display:'flex',alignItems:'center',gap:10,padding:'9px 0',borderBottom:`1px solid ${G.border}22`}}>
                <div style={{width:32,height:32,background:G.card2,border:`1px solid ${G.border}`,borderRadius:6,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                  <svg width="16" height="16" viewBox="0 0 16 16"><path d="M8 2L2 6h12L8 2z" fill={G.accentDark}/><ellipse cx="8" cy="10" rx="4" ry="3.5" fill={G.accentDark} stroke={G.accent} strokeWidth="1"/></svg>
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:12,color:G.text,fontWeight:500,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.name}</div>
                  <div style={{fontSize:10,color:G.textSec}}>Stock: <b style={{color:p.stock<=p.minStock?G.error:G.warning}}>{p.stock}</b> / Mín: {p.minStock}</div>
                </div>
                <StockBadge stock={p.stock} minStock={p.minStock}/>
              </div>
            ))}
          </div>
        </Card>

        {/* Upcoming payments */}
        <Card title="📅 Próximos Vencimientos de Cobro" action={<Btn sm variant="ghost" onClick={()=>onNav('contabilidad')}>Ver todo →</Btn>} noPad>
          <div style={{padding:'0 18px 12px'}}>
            {dueSoon.length===0 && <div style={{color:G.textSec,fontSize:12,padding:'12px 0'}}>Sin vencimientos próximos.</div>}
            {dueSoon.map((d,i)=>(
              <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'9px 0',borderBottom:`1px solid ${G.border}22`}}>
                <div style={{flex:1}}>
                  <div style={{fontSize:12,color:G.text,fontWeight:600}}>{d.client}</div>
                  <div style={{fontSize:10,color:G.textSec}}>{d.invoice} · {d.amount}</div>
                </div>
                <DaysBadge days={d.days}/>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Recent activity strip */}
      <div style={{marginTop:14}}>
        <Card title="🕒 Actividad Reciente" action={<Btn sm variant="ghost" onClick={()=>onNav('historial')}>Ver historial →</Btn>} noPad>
          <div style={{display:'flex',gap:0,overflowX:'auto',padding:'10px 18px'}}>
            {activity.length===0 && <div style={{color:G.textSec,fontSize:12}}>Sin actividad reciente.</div>}
            {activity.slice(0,5).map(a=>(
              <div key={a.id} style={{flexShrink:0,marginRight:16,paddingRight:16,borderRight:`1px solid ${G.border}`,minWidth:180}}>
                <div style={{fontSize:10,color:G.textSec,marginBottom:2}}>{a.dt} · <span style={{color:G.accent}}>{a.module}</span></div>
                <div style={{fontSize:12,color:G.text,fontWeight:500}}>{a.action}</div>
                <div style={{fontSize:11,color:G.textSec}}>{a.detail}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function DashboardEmpleado({ onNav, quotes, products, contacts, currentUser }) {
  const { KPICard, Card, Btn, DaysBadge, StatusBadge, StockBadge, Tag, T } = window;
  const fmtS = window.fmtS;
  const G = window.C;

  const now = new Date();
  const dias = ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'];
  const meses = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
  const fechaHoy = `${dias[now.getDay()]} ${now.getDate()} de ${meses[now.getMonth()]}, ${now.getFullYear()}`;

  const storageKey = `eutProfileImg_${currentUser?.username}`;
  const [profileImg, setProfileImg] = React.useState(() => localStorage.getItem(storageKey) || '');
  const fileRef = React.useRef(null);

  const handleImgChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      const b64 = ev.target.result;
      setProfileImg(b64);
      localStorage.setItem(storageKey, b64);
    };
    reader.readAsDataURL(file);
  };

  const misCots = (quotes||[]).filter(q => q.createdBy === currentUser?.username);
  const mesActual = String(now.getMonth()+1).padStart(2,'0');
  const anioActual = String(now.getFullYear()).slice(2);
  const cotsMes = misCots.filter(q => {
    const parts = (q.date||'').split('/');
    return parts[1] === mesActual && parts[2] && parts[2].slice(-2) === anioActual;
  });

  const miVigentes   = misCots.filter(q => q.status==='vigente').length;
  const miAceptadas  = misCots.filter(q => q.status==='aceptada').length;
  const miVendidoMes = cotsMes.filter(q => q.status==='entregada').reduce((s,q) => s+q.total, 0);
  const miTotalVendido = misCots.filter(q => q.status==='entregada').reduce((s,q) => s+q.total, 0);

  const misFactPend = misCots.filter(q => q.invoice && !q.paidAt && q.credit > 0 && q.daysLeft !== null);
  const porVencer  = misFactPend.filter(q => q.daysLeft >= 0 && q.daysLeft <= 7).sort((a,b) => a.daysLeft - b.daysLeft);
  const vencidas   = misFactPend.filter(q => q.daysLeft < 0).sort((a,b) => a.daysLeft - b.daysLeft);
  const proximas   = misFactPend.filter(q => q.daysLeft > 7 && q.daysLeft <= 30).sort((a,b) => a.daysLeft - b.daysLeft);

  const stockCrit = (products||[]).filter(p => p.stock <= p.minStock);
  const stockBajo = (products||[]).filter(p => p.stock > p.minStock && p.stock <= p.minStock*1.5);
  const misClientes = (contacts||[]).filter(c => c.type==='cliente' && c.ownerId===currentUser?.id);

  const hayAlertas = porVencer.length > 0 || vencidas.length > 0;
  const displayName = currentUser ? (currentUser.apellidos ? `${currentUser.name} ${currentUser.apellidos}` : currentUser.name) : '';
  const initials = currentUser ? `${(currentUser.name||'?').charAt(0)}${(currentUser.apellidos||currentUser.name||'').charAt(1)||''}` : '?';

  return (
    <div>
      {/* Header greeting */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:20,paddingBottom:14,borderBottom:`1px solid ${G.border}`}}>
        <div>
          <h1 style={T.h1}>BIENVENIDO, {(currentUser?.name||'').toUpperCase()}</h1>
          <div style={{color:G.textSec,fontSize:11,marginTop:3}}>{fechaHoy}</div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <Btn sm variant="ghost" onClick={()=>onNav('cotizaciones')}>Mis Cotizaciones →</Btn>
          <Btn sm variant="ghost" onClick={()=>onNav('misventas')}>Mis Ventas →</Btn>
        </div>
      </div>

      {/* Main layout: left content + right profile */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 280px',gap:16,marginBottom:14,alignItems:'start'}}>

        {/* LEFT: KPIs + Alerts + Stock + Recent quotes */}
        <div>
          {/* KPIs */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:10,marginBottom:14}}>
            <KPICard label="Mis Cotizaciones" value={misCots.length} color={G.text} icon="📋"/>
            <KPICard label="Vigentes" value={miVigentes} color={G.warning} icon="⏳"/>
            <KPICard label="En proceso" value={miAceptadas} color={G.accent} icon="✓"/>
            <KPICard label="Vendido este mes" value={fmtS(miVendidoMes)} color={G.accent} icon="💰"/>
          </div>

          {/* Alertas urgentes */}
          {hayAlertas && (
            <div style={{background:'#1a0a00',border:`1px solid ${G.warning}55`,borderRadius:8,padding:'14px 18px',marginBottom:12}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
                <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontSize:15,fontWeight:700,color:G.warning}}>⚠️ COBROS URGENTES</div>
                <Btn sm variant="ghost" onClick={()=>onNav('misventas')}>Ver todas →</Btn>
              </div>
              {vencidas.map(q=>(
                <div key={q.id} style={{display:'flex',alignItems:'center',gap:10,padding:'7px 0',borderBottom:`1px solid ${G.border}33`}}>
                  <div style={{background:G.error+'22',border:`1px solid ${G.error}44`,borderRadius:4,padding:'2px 8px',fontSize:10,fontWeight:700,color:G.error,flexShrink:0,minWidth:76,textAlign:'center'}}>
                    VENCIDA {Math.abs(q.daysLeft)}d
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:600,color:G.text,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{q.client}</div>
                    <div style={{fontSize:10,color:G.textSec}}>{q.invoice}</div>
                  </div>
                  <div style={{fontWeight:700,color:G.error,fontSize:12,flexShrink:0}}>{fmtS(q.total)}</div>
                </div>
              ))}
              {porVencer.map(q=>(
                <div key={q.id} style={{display:'flex',alignItems:'center',gap:10,padding:'7px 0',borderBottom:`1px solid ${G.border}33`}}>
                  <div style={{background:G.warning+'22',border:`1px solid ${G.warning}44`,borderRadius:4,padding:'2px 8px',fontSize:10,fontWeight:700,color:G.warning,flexShrink:0,minWidth:76,textAlign:'center'}}>
                    {q.daysLeft===0?'VENCE HOY':`${q.daysLeft} día${q.daysLeft!==1?'s':''}`}
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:600,color:G.text,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{q.client}</div>
                    <div style={{fontSize:10,color:G.textSec}}>{q.invoice} · vence {q.dueDate}</div>
                  </div>
                  <div style={{fontWeight:700,color:G.accent,fontSize:12,flexShrink:0}}>{fmtS(q.total)}</div>
                </div>
              ))}
            </div>
          )}

          {/* Próximos cobros 8-30d */}
          {proximas.length > 0 && (
            <div style={{background:G.card,border:`1px solid ${G.border}`,borderRadius:8,padding:'12px 16px',marginBottom:12}}>
              <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontSize:14,fontWeight:700,color:G.text,marginBottom:8}}>📅 PRÓXIMOS COBROS (8–30 días)</div>
              {proximas.slice(0,3).map(q=>(
                <div key={q.id} style={{display:'flex',alignItems:'center',gap:10,padding:'6px 0',borderBottom:`1px solid ${G.border}22`}}>
                  <DaysBadge days={q.daysLeft}/>
                  <div style={{flex:1,fontSize:12,color:G.text,fontWeight:500}}>{q.client}</div>
                  <div style={{fontWeight:600,color:G.accent,fontSize:12}}>{fmtS(q.total)}</div>
                </div>
              ))}
              {proximas.length>3 && <div style={{fontSize:10,color:G.textSec,marginTop:6}}>+ {proximas.length-3} más en los próximos 30 días</div>}
            </div>
          )}

          {/* Sin alertas */}
          {!hayAlertas && proximas.length===0 && (
            <div style={{background:G.accent+'0d',border:`1px solid ${G.accent}33`,borderRadius:8,padding:'12px 16px',marginBottom:12,display:'flex',alignItems:'center',gap:10}}>
              <span style={{fontSize:20}}>✅</span>
              <div>
                <div style={{fontSize:13,fontWeight:600,color:G.accent}}>¡Todo al día!</div>
                <div style={{fontSize:11,color:G.textSec}}>Sin cobros urgentes ni vencidos en tu cartera.</div>
              </div>
            </div>
          )}

          {/* Stock */}
          {(stockCrit.length > 0 || stockBajo.length > 0) && (
            <Card title="📦 Alertas de Inventario" action={<Btn sm variant="ghost" onClick={()=>onNav('almacen')}>Ver →</Btn>} noPad style={{marginBottom:12}}>
              <div style={{padding:'0 16px 10px'}}>
                {[...stockCrit,...stockBajo].slice(0,4).map(p=>(
                  <div key={p.id} style={{display:'flex',alignItems:'center',gap:10,padding:'7px 0',borderBottom:`1px solid ${G.border}22`}}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:12,color:G.text,fontWeight:500,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.name}</div>
                      <div style={{fontSize:10,color:p.stock<=p.minStock?G.error:G.warning}}>Stock: {p.stock} · Mín: {p.minStock}</div>
                    </div>
                    <StockBadge stock={p.stock} minStock={p.minStock}/>
                  </div>
                ))}
              </div>
            </Card>
          )}

          {/* Mis cotizaciones recientes */}
          <Card title="🕒 Mis Cotizaciones Recientes" action={<Btn sm variant="ghost" onClick={()=>onNav('cotizaciones')}>Ver todas →</Btn>} noPad>
            <div style={{padding:'0 16px 10px'}}>
              {misCots.length===0 && <div style={{color:G.textSec,fontSize:12,padding:'12px 0'}}>Aún no tienes cotizaciones.</div>}
              {misCots.slice(0,4).map(q=>(
                <div key={q.id} style={{display:'flex',alignItems:'center',gap:10,padding:'7px 0',borderBottom:`1px solid ${G.border}22`}}>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{display:'flex',alignItems:'center',gap:6}}>
                      <span style={{fontSize:11,color:G.accent,fontWeight:600}}>{q.id}</span>
                      <StatusBadge status={q.status}/>
                    </div>
                    <div style={{fontSize:11,color:G.textSec,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{q.client} · {q.date}</div>
                  </div>
                  <div style={{fontSize:12,fontWeight:700,color:G.accent,flexShrink:0}}>{fmtS(q.total)}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* RIGHT: Profile card */}
        <div>
          {/* Foto / imagen personalizada */}
          <div style={{background:G.card,border:`1px solid ${G.border}`,borderRadius:8,overflow:'hidden',marginBottom:12}}>
            {/* Image area - clickeable */}
            <div
              onClick={()=>fileRef.current?.click()}
              title="Haz clic para cambiar tu imagen"
              style={{
                height:220,
                background: profileImg ? 'transparent' : `linear-gradient(135deg, ${G.accent}22 0%, #0a2200 50%, ${G.accent}11 100%)`,
                display:'flex',alignItems:'center',justifyContent:'center',
                cursor:'pointer',position:'relative',overflow:'hidden',
              }}
            >
              {profileImg ? (
                <img src={profileImg} alt="Mi foto" style={{width:'100%',height:'100%',objectFit:'cover',display:'block'}}/>
              ) : (
                <div style={{textAlign:'center',color:G.accent+'88'}}>
                  <div style={{fontSize:56,marginBottom:8,fontWeight:700,fontFamily:"'Barlow Condensed',sans-serif",color:G.accent+'55'}}>{initials}</div>
                  <div style={{fontSize:11,color:G.textSec}}>Clic para agregar foto</div>
                </div>
              )}
              {/* Hover overlay */}
              <div style={{position:'absolute',inset:0,background:'#00000066',display:'flex',alignItems:'center',justifyContent:'center',opacity:0,transition:'opacity 0.2s'}}
                onMouseEnter={e=>e.currentTarget.style.opacity=1}
                onMouseLeave={e=>e.currentTarget.style.opacity=0}>
                <div style={{color:'#fff',fontSize:12,fontWeight:600,textAlign:'center'}}>
                  <div style={{fontSize:20,marginBottom:4}}>📷</div>
                  Cambiar imagen
                </div>
              </div>
            </div>
            <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={handleImgChange}/>

            {/* Profile info */}
            <div style={{padding:'14px 16px'}}>
              <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontSize:20,fontWeight:700,color:G.text,marginBottom:2}}>{displayName}</div>
              <div style={{fontSize:11,color:G.textSec,marginBottom:12}}>@{currentUser?.username} · {currentUser?.role}</div>

              {/* My stats */}
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                {[
                  ['Total vendido',fmtS(miTotalVendido),G.accent],
                  ['Clientes',misClientes.length>0?misClientes.length:'—',G.text],
                  ['Cots. totales',misCots.length,G.text],
                  ['Por cobrar',misFactPend.length,misFactPend.length>0?G.warning:G.textSec],
                ].map(([l,v,c])=>(
                  <div key={l} style={{background:G.bg,border:`1px solid ${G.border}`,borderRadius:6,padding:'8px 10px',textAlign:'center'}}>
                    <div style={{fontFamily:"'Barlow Condensed',sans-serif",fontSize:18,fontWeight:700,color:c,lineHeight:1}}>{v}</div>
                    <div style={{fontSize:9,color:G.textSec,marginTop:3,textTransform:'uppercase',letterSpacing:0.3}}>{l}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Mi cartera */}
          {misClientes.length > 0 && (
            <Card title="👥 Mi Cartera" action={<Btn sm variant="ghost" onClick={()=>onNav('misclientes')}>Ver →</Btn>} noPad>
              <div style={{padding:'0 14px 10px'}}>
                {misClientes.slice(0,4).map(c=>(
                  <div key={c.id} style={{display:'flex',alignItems:'center',gap:8,padding:'7px 0',borderBottom:`1px solid ${G.border}22`}}>
                    <div style={{width:24,height:24,borderRadius:'50%',background:G.accent+'22',display:'flex',alignItems:'center',justifyContent:'center',fontSize:10,fontWeight:700,color:G.accent,flexShrink:0}}>{c.name.charAt(0)}</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:12,fontWeight:500,color:G.text,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{c.name}</div>
                      <div style={{fontSize:10,color:G.textSec}}>{c.credit===0?'Contado':`${c.credit}d crédito`}</div>
                    </div>
                  </div>
                ))}
                {misClientes.length>4 && <div style={{fontSize:10,color:G.textSec,paddingTop:6}}>+ {misClientes.length-4} más</div>}
              </div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, DashboardEmpleado });
