// Shared components and icons for QA platform
var useState = React.useState, useEffect = React.useEffect, useMemo = React.useMemo, useRef = React.useRef, Fragment = React.Fragment;

// ---------------------------------------------------------------- ICONS
const Icon = {
  Dashboard: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>,
  Clients: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
  Projects: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>,
  Clock: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg>,
  Report: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="13" y2="17"/></svg>,
  Bug: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="8" y="6" width="8" height="14" rx="4"/><path d="M12 6V3"/><path d="M9 9 6 7"/><path d="M15 9l3-2"/><path d="M9 13H5"/><path d="M19 13h-4"/><path d="M9 17l-3 2"/><path d="M15 17l3 2"/></svg>,
  Calendar: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
  Settings: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
  Search: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  Plus: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  Arrow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  Check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="20 6 9 17 4 12"/></svg>,
  More: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>,
  Filter: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>,
  Download: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>,
  Image: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>,
  Upload: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>,
  Close: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  External: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>,
  WhatsApp: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M17.5 14.4c-.3-.2-1.8-.9-2.1-1-.3-.1-.5-.2-.7.2-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-.3-.2-1.3-.5-2.5-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.5-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.2.2 2.2 3.3 5.3 4.6.7.3 1.3.5 1.8.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.5.2-.7.2-1.4.2-1.5-.1-.1-.3-.2-.5-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.4 5L2 22l5.2-1.4c1.5.8 3.1 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>,
  Mail: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>,
  Sparkles: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.5 5.5l2 2M16.5 16.5l2 2M5.5 18.5l2-2M16.5 7.5l2-2"/></svg>,
};

// ---------------------------------------------------------------- BADGE
function Badge({ tone = 'neutral', dot, children }) {
  return <span className={`badge ${tone}`}>{dot && <span className="dot"/>}{children}</span>;
}

// ---------------------------------------------------------------- SEV CHIP
function SevChip({ value }) {
  return <span className={`sev ${value.toLowerCase().replace('í','i')}`}>{value}</span>;
}

// ---------------------------------------------------------------- STAT CARD
function StatCard({ label, value, delta, deltaTone, hint }) {
  return (
    <div className="card stat">
      <div className="stat-label">{label}</div>
      <div className="stat-value">{value}</div>
      {(delta || hint) && (
        <div className={`stat-delta ${deltaTone || ''}`}>
          {delta && <span>{delta}</span>}
          {hint && <span className="cell-muted">{hint}</span>}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------- SIDEBAR
function Sidebar({ active, onNav, role = 'admin', onLogout }) {
  const D = useStore();
  const user = useUser();
  const adminNav = [
    { id: 'dashboard', label: 'Dashboard', icon: Icon.Dashboard },
    { id: 'projects', label: 'Proyectos', icon: Icon.Projects, badge: D.projects.filter(p=>p.stage!=='Finalizado').length },
    { id: 'clients', label: 'Clientes', icon: Icon.Clients, badge: D.clients.length },
    { id: 'hours', label: 'Registro de horas', icon: Icon.Clock },
    { id: 'bugs', label: 'Incidencias', icon: Icon.Bug, badge: D.openBugs() },
    { id: 'reports', label: 'Reportes', icon: Icon.Report },
    { id: 'quincena', label: 'Resumen quincenal', icon: Icon.Calendar },
  ];
  const clientNav = [
    { id: 'client-overview', label: 'Resumen', icon: Icon.Dashboard },
    { id: 'client-projects', label: 'Mis proyectos', icon: Icon.Projects },
    { id: 'client-bugs', label: 'Incidencias', icon: Icon.Bug },
    { id: 'client-reports', label: 'Reportes', icon: Icon.Report },
    { id: 'client-hours', label: 'Horas y costo', icon: Icon.Clock },
  ];
  const items = role === 'admin' ? adminNav : clientNav;
  const isAdmin = role === 'admin';
  const initials = user?.full_name ? user.full_name.split(' ').map(x=>x[0]).join('').slice(0,2).toUpperCase() : (isAdmin?'ER':'CL');
  const name = user?.full_name || (isAdmin ? 'Ebed R. Mendez' : 'Cliente');
  const email = user?.email || '';
  const company = isAdmin ? 'QA Freelance' : (D.clients.find(c=>c.user_id===user?.id)?.name || 'Cliente');

  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className="brand-mark"/>
        <div>
          <div className="brand-name">bugzero</div>
          <div className="brand-sub">{isAdmin ? 'Estación QA' : 'Portal cliente'}</div>
        </div>
      </div>
      <div className="sidebar-section">{isAdmin ? 'Trabajo' : 'Mi cuenta'}</div>
      <nav>
        {items.map(it => {
          const I = it.icon;
          return (
            <button key={it.id} className={`nav-item ${active===it.id?'active':''}`} onClick={() => onNav(it.id)}>
              <I/>
              <span>{it.label}</span>
              {it.badge != null && <span className="nav-badge">{it.badge}</span>}
            </button>
          );
        })}
      </nav>
      <div className="sidebar-section">Cuenta</div>
      <nav>
        <button className={`nav-item ${active==='profile'?'active':''}`} onClick={() => onNav('profile')}>
          <Icon.Settings/><span>Perfil y ajustes</span>
        </button>
      </nav>
      <div className="sidebar-footer">
        <div className="sidebar-user" title={email}>
          <div className="avatar">{initials}</div>
          <div style={{minWidth:0, flex:1}}>
            <div className="user-name">{name}</div>
            <div className="user-role">{company}</div>
          </div>
          <button className="icon-btn" onClick={(e)=>{e.stopPropagation(); onLogout && onLogout();}} title="Cerrar sesión">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
          </button>
        </div>
      </div>
    </aside>
  );
}

// ---------------------------------------------------------------- TOPBAR
function Topbar({ title, crumb, search = true, children }) {
  return (
    <div className="topbar">
      <div>
        {crumb && <div className="topbar-crumb">{crumb}</div>}
        <div className="topbar-title">{title}</div>
      </div>
      <div className="topbar-spacer"/>
      {search && (
        <div className="topbar-search">
          <Icon.Search width="14" height="14"/>
          <input placeholder="Buscar proyectos, bugs, clientes…"/>
          <span className="kbd">⌘K</span>
        </div>
      )}
      {children}
    </div>
  );
}

// ---------------------------------------------------------------- DONUT
function Donut({ value, max = 100, label, color = 'var(--text)' }) {
  const r = 44, c = 2 * Math.PI * r;
  const off = c - (value / max) * c;
  return (
    <div className="donut">
      <svg width="110" height="110" viewBox="0 0 110 110">
        <circle cx="55" cy="55" r={r} fill="none" stroke="var(--surface-2)" strokeWidth="10"/>
        <circle cx="55" cy="55" r={r} fill="none" stroke={color} strokeWidth="10"
                strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"/>
      </svg>
      <div className="center">
        <div className="val">{Math.round((value/max)*100)}%</div>
        <div className="lbl">{label}</div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------- SPARKBAR
function SparkBar({ data, labels, max }) {
  const m = max || Math.max(...data, 1);
  return (
    <div>
      <div className="sparkbar">
        {data.map((v, i) => (
          <div key={i} className={`bar-i ${v===0?'muted':''}`} style={{height: `${Math.max(4, (v/m)*100)}%`}}/>
        ))}
      </div>
      {labels && <div className="spark-axis">{labels.map((l,i)=><span key={i}>{l}</span>)}</div>}
    </div>
  );
}

// ---------------------------------------------------------------- HEATMAP
function HeatmapRow({ data }) {
  const cls = (v) => v === 0 ? '' : v < 2 ? 'l1' : v < 4 ? 'l2' : v < 5.5 ? 'l3' : 'l4';
  return (
    <div className="heatmap">
      {data.map((v, i) => <div key={i} className={`cell ${cls(v)}`} title={`${v}h`}/>)}
    </div>
  );
}

// ---------------------------------------------------------------- DRAWER
function Drawer({ open, onClose, title, children, footer }) {
  return (
    <Fragment>
      <div className={`drawer-backdrop ${open?'open':''}`} onClick={onClose}/>
      <aside className={`drawer ${open?'open':''}`}>
        <div className="drawer-header">
          <div className="topbar-title">{title}</div>
          <button className="icon-btn" onClick={onClose}><Icon.Close width="16" height="16"/></button>
        </div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-footer">{footer}</div>}
      </aside>
    </Fragment>
  );
}

// ---------------------------------------------------------------- EVIDENCE TILE
function EvidenceTile({ ev }) {
  const url = ev.url || `/uploads/evidence/${encodeURIComponent(ev.name)}`;
  return (
    <div className="evidence" style={{backgroundImage:`url(${url})`, backgroundSize:'cover', backgroundPosition:'center'}}>
      <div style={{position:'absolute', top:10, left:12, fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-4)'}}>PNG · {ev.date}</div>
      <div className="meta">
        <span>{ev.label}</span>
        <Icon.Image width="12" height="12"/>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------- PDF ITEM
function PdfItem({ r }) {
  return (
    <div className="pdf-item">
      <div className="pdf-icon">PDF</div>
      <div style={{flex:1, minWidth:0}}>
        <div className="pdf-name" style={{whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{r.name}</div>
        <div className="pdf-meta">{r.type} · {r.date} · {r.size}</div>
      </div>
      <button className="icon-btn" title="Descargar"><Icon.Download width="15" height="15"/></button>
    </div>
  );
}

// ---------------------------------------------------------------- ACTION MENU
function ActionMenu({ onEdit, onDelete, disabled }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    function handler(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);
  return (
    <div className="action-menu-wrap" ref={ref}>
      <button className="icon-btn" onClick={() => setOpen(v => !v)} disabled={disabled}><Icon.More width="14" height="14"/></button>
      {open && (
        <div className="action-menu">
          {onEdit && <button onClick={() => { setOpen(false); onEdit(); }}><Icon.Edit width="13" height="13"/> Editar</button>}
          {onDelete && <button className="danger" onClick={() => { setOpen(false); onDelete(); }}><Icon.Trash width="13" height="13"/> Eliminar</button>}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------- CONFIRM DIALOG
function ConfirmDialog({ open, title, message, onConfirm, onCancel, loading }) {
  if (!open) return null;
  return (
    <div className="confirm-backdrop" onClick={onCancel}>
      <div className="confirm-box" onClick={e => e.stopPropagation()}>
        <h3>{title || '¿Confirmar?'}</h3>
        <p>{message || 'Esta acción no se puede deshacer.'}</p>
        <div className="confirm-actions">
          <button className="btn" onClick={onCancel} disabled={loading}>Cancelar</button>
          <button className="btn btn-danger" onClick={onConfirm} disabled={loading}>{loading ? 'Eliminando…' : 'Eliminar'}</button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------- PAGINATOR
function Paginator({ page, totalPages, onChange }) {
  if (totalPages <= 1) return null;
  const pages = [];
  const start = Math.max(1, Math.min(page - 2, totalPages - 4));
  const end = Math.min(totalPages, Math.max(page + 2, 5));
  for (let i = start; i <= end; i++) pages.push(i);
  return (
    <div className="paginator">
      <button onClick={() => onChange(page - 1)} disabled={page <= 1}>← Anterior</button>
      {start > 1 && <button onClick={() => onChange(1)}>1</button>}
      {start > 2 && <span style={{color:'var(--text-3)',padding:'6px 4px'}}>…</span>}
      {pages.map(p => <button key={p} className={p === page ? 'active' : ''} onClick={() => onChange(p)}>{p}</button>)}
      {end < totalPages - 1 && <span style={{color:'var(--text-3)',padding:'6px 4px'}}>…</span>}
      {end < totalPages && <button onClick={() => onChange(totalPages)}>{totalPages}</button>}
      <button onClick={() => onChange(page + 1)} disabled={page >= totalPages}>Siguiente →</button>
    </div>
  );
}

// Extra icons for ActionMenu
Icon.Edit = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
Icon.Trash = (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>;

Object.assign(window, {
  Icon, Badge, SevChip, StatCard, Sidebar, Topbar, Donut, SparkBar, HeatmapRow, Drawer, EvidenceTile, PdfItem,
  ActionMenu, ConfirmDialog, Paginator
});
