/* ============================================================
   F2 UI — Dashboard / client-panel library
   StatCard · MetricChart · SidebarNav · Topbar · DashboardLayout
   ============================================================ */
(function () {
  const { Icon, Card, Stat, Avatar, IconButton, StatusDot, Badge } = window.F2;

  /* ====================== MetricChart ====================== */
  function MetricChart({ data = [], type = 'bar', height = 120, tone = 'accent', highlightLast = true, style = {} }) {
    const vals = data.map((d) => (typeof d === 'number' ? d : d.value));
    const labels = data.map((d) => (typeof d === 'number' ? '' : d.label || ''));
    const max = Math.max(...vals, 1);
    const color = tone === 'success' ? 'var(--f2-success)' : tone === 'muted' ? 'var(--f2-text-muted)' : 'var(--f2-accent)';

    if (type === 'bar') {
      return (
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 'clamp(3px, 1.5%, 8px)', height, ...style }}>
          {vals.map((v, i) => {
            const last = i === vals.length - 1;
            const lit = highlightLast && last;
            return (
              <div key={i} title={labels[i] ? `${labels[i]}: ${v}` : String(v)} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', height: '100%' }}>
                <div style={{ height: `${Math.max(3, (v / max) * 100)}%`, borderRadius: 'var(--f2-radius-sm)', background: lit ? color : 'var(--f2-surface-raised)', border: lit ? 'none' : '1px solid var(--f2-border-strong)', transition: 'height var(--f2-dur-base) var(--f2-ease)' }} />
              </div>
            );
          })}
        </div>
      );
    }

    // line / area / sparkline (responsive SVG, non-scaling stroke)
    const W = 100, H = 100;
    const n = vals.length;
    const pts = vals.map((v, i) => [n === 1 ? 0 : (i / (n - 1)) * W, H - (v / max) * (H - 6) - 3]);
    const line = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(2)} ${p[1].toFixed(2)}`).join(' ');
    const area = `${line} L${W} ${H} L0 ${H} Z`;
    const spark = type === 'sparkline';
    return (
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" width="100%" height={height} style={{ display: 'block', overflow: 'visible', ...style }}>
        {(type === 'area') && <path d={area} fill={color} opacity="0.12" />}
        <path d={line} fill="none" stroke={color} strokeWidth={spark ? 1.6 : 1.8} vectorEffect="non-scaling-stroke" strokeLinejoin="round" strokeLinecap="round" />
        {!spark && pts.length > 0 && <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.4" fill={color} vectorEffect="non-scaling-stroke" />}
      </svg>
    );
  }

  /* ====================== StatCard ====================== */
  function StatCard({ label, value, delta, deltaTone, icon, chart, chartTone, active = false, style = {} }) {
    return (
      <Card active={active} style={{ padding: 18, ...style }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <Stat label={label} value={value} delta={delta} deltaTone={deltaTone} />
          {icon && <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: 'var(--f2-radius-control)', background: 'var(--f2-surface-raised)', border: '1px solid var(--f2-border)', color: 'var(--f2-text-muted)', flex: '0 0 auto' }}><Icon name={icon} size={17} /></span>}
        </div>
        {chart && <div style={{ marginTop: 14 }}><MetricChart data={chart} type="area" tone={chartTone || 'accent'} height={42} /></div>}
      </Card>
    );
  }

  /* ====================== SidebarNav ====================== */
  function F2Glyph({ size = 9 }) {
    const cell = (a) => ({ width: size, height: size, borderRadius: size * 0.28, background: a ? 'var(--f2-accent)' : 'var(--f2-surface-card)', border: a ? 'none' : '1px solid var(--f2-border-strong)' });
    return <div style={{ display: 'grid', gridTemplateColumns: `${size}px ${size}px`, gap: 3 }}><span style={cell()} /><span style={cell()} /><span style={cell()} /><span style={cell(true)} /></div>;
  }
  function SidebarNav({ items = [], active, onSelect, brand = 'F2 Tecnologia', user, footer, style = {} }) {
    let lastSection = null;
    return (
      <aside style={{ display: 'flex', flexDirection: 'column', height: '100%', width: '100%', background: 'var(--f2-surface)', borderRight: '1px solid var(--f2-border)', ...style }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '18px 18px 14px' }}>
          <F2Glyph />
          <span style={{ fontFamily: 'var(--f2-font-display)', fontWeight: 600, fontSize: 15, color: 'var(--f2-text)', letterSpacing: '-0.01em' }}>{brand}</span>
        </div>
        <nav style={{ flex: 1, overflowY: 'auto', padding: '4px 10px' }}>
          {items.map((it, i) => {
            const showSection = it.section && it.section !== lastSection;
            lastSection = it.section || lastSection;
            const on = it.value === active;
            return (
              <React.Fragment key={it.value || i}>
                {showSection && <div style={{ fontFamily: 'var(--f2-font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--f2-text-faint)', padding: '14px 10px 6px' }}>{it.section}</div>}
                <button onClick={() => onSelect && onSelect(it.value)} style={{
                  display: 'flex', alignItems: 'center', gap: 11, width: '100%', textAlign: 'left', padding: '9px 10px', marginBottom: 2, border: 'none', borderRadius: 8, cursor: 'pointer',
                  background: on ? 'var(--f2-surface-card)' : 'transparent', boxShadow: on ? 'inset 0 0 0 1px var(--f2-border)' : 'none',
                  color: on ? 'var(--f2-text)' : 'var(--f2-text-secondary)', fontFamily: 'var(--f2-font-body)', fontSize: 14.5, transition: 'background var(--f2-dur-fast) var(--f2-ease)' }}
                  onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = 'var(--f2-surface-raised)'; }}
                  onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                  <span style={{ color: on ? 'var(--f2-accent-text)' : 'var(--f2-text-muted)', display: 'inline-flex' }}><Icon name={it.icon} size={18} /></span>
                  <span style={{ flex: 1 }}>{it.label}</span>
                  {it.badge != null && <span style={{ fontFamily: 'var(--f2-font-mono)', fontSize: 11, color: on ? 'var(--f2-accent-text)' : 'var(--f2-text-faint)', background: 'var(--f2-surface-sunken)', borderRadius: 999, padding: '1px 7px' }}>{it.badge}</span>}
                </button>
              </React.Fragment>
            );
          })}
        </nav>
        {(user || footer) && (
          <div style={{ borderTop: '1px solid var(--f2-border)', padding: 12 }}>
            {footer || (
              <button style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: 7, border: 'none', background: 'none', cursor: 'pointer', borderRadius: 8, color: 'var(--f2-text)' }}>
                <Avatar name={user.name} src={user.src} size={32} status={user.status} />
                <span style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 13.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.name}</span>
                  {user.email && <span style={{ display: 'block', fontSize: 12, color: 'var(--f2-text-faint)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</span>}
                </span>
                <Icon name="ChevronsUpDown" size={15} color="var(--f2-text-faint)" />
              </button>
            )}
          </div>
        )}
      </aside>
    );
  }

  /* ====================== Topbar ====================== */
  function Topbar({ title, breadcrumb, search = false, onMenu, actions, user, style = {} }) {
    return (
      <header style={{ display: 'flex', alignItems: 'center', gap: 14, height: 60, padding: '0 18px', borderBottom: '1px solid var(--f2-border)', background: 'var(--f2-surface)', ...style }}>
        {onMenu && <IconButton variant="ghost" size="sm" aria-label="Toggle menu" onClick={onMenu}><Icon name="PanelLeft" size={18} /></IconButton>}
        {breadcrumb || (title && <div style={{ fontFamily: 'var(--f2-font-display)', fontWeight: 600, fontSize: 16, color: 'var(--f2-text)' }}>{title}</div>)}
        {search && (
          <div style={{ flex: 1, maxWidth: 360, display: 'flex', alignItems: 'center', gap: 9, height: 36, padding: '0 12px', background: 'var(--f2-surface-raised)', border: '1px solid var(--f2-border)', borderRadius: 'var(--f2-radius-control)' }}>
            <Icon name="Search" size={15} color="var(--f2-text-faint)" />
            <input placeholder="Search…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', color: 'var(--f2-text)', fontFamily: 'var(--f2-font-body)', fontSize: 14 }} />
          </div>
        )}
        <div style={{ flex: search ? '0 0 auto' : 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {actions}
          {user && <Avatar name={user.name} src={user.src} size={32} status={user.status} />}
        </div>
      </header>
    );
  }

  /* ====================== DashboardLayout (composite) ====================== */
  function DashboardLayout({ children, height = 540, style = {} }) {
    const [active, setActive] = React.useState('overview');
    const items = [
      { value: 'overview', label: 'Overview', icon: 'LayoutDashboard', section: 'Workspace' },
      { value: 'automations', label: 'Automations', icon: 'Workflow', badge: 7 },
      { value: 'runs', label: 'Runs', icon: 'Play' },
      { value: 'data', label: 'Data sources', icon: 'Database', section: 'Manage' },
      { value: 'team', label: 'Team', icon: 'Users' },
      { value: 'billing', label: 'Billing', icon: 'CreditCard' },
    ];
    const user = { name: 'Ana Ribeiro', email: 'ana@f2.tech', status: 'success' };
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '230px 1fr', height, border: '1px solid var(--f2-border-strong)', borderRadius: 'var(--f2-radius-md)', overflow: 'hidden', background: 'var(--f2-surface)', ...style }}>
        <SidebarNav items={items} active={active} onSelect={setActive} user={user} />
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <Topbar title="Overview" search actions={<><IconButton variant="ghost" size="sm" aria-label="Notifications"><Icon name="Bell" size={18} /></IconButton></>} user={user} />
          <div style={{ flex: 1, overflowY: 'auto', padding: 20, background: 'var(--f2-surface)' }}>
            {children || <DefaultDashboardBody />}
          </div>
        </div>
      </div>
    );
  }
  function DefaultDashboardBody() {
    const bars = [42, 55, 48, 63, 58, 71, 66, 82, 78, 91, 86, 99];
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 14 }}>
          <StatCard label="Processed" value="1,284" delta="+12.4%" icon="FileText" chart={[8, 10, 9, 13, 12, 16, 19]} />
          <StatCard label="Avg. latency" value="19s" delta="-31%" icon="Timer" chart={[40, 33, 35, 28, 26, 22, 19]} chartTone="success" />
          <StatCard label="Active agents" value="7" delta="+2" icon="Bot" active />
        </div>
        <Card style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <span style={{ fontFamily: 'var(--f2-font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--f2-text-muted)' }}>Runs · last 12h</span>
            <Badge tone="active"><StatusDot tone="active" live size={6} /> Live</Badge>
          </div>
          <MetricChart data={bars} type="bar" height={120} />
        </Card>
      </div>
    );
  }

  Object.assign(window.F2, { MetricChart, StatCard, SidebarNav, Topbar, DashboardLayout });
})();
