/* global React, I */
// note: no top-level destructure of React hooks — each Babel file shares scope

/* ============ Sparkline ============ */
function Sparkline({ data, color = '#A78BFA', width = 84, height = 32 }) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const pad = 2;
  const pts = data.map((v, i) => {
    const x = pad + (i / (data.length - 1)) * (width - pad * 2);
    const y = pad + (1 - (v - min) / range) * (height - pad * 2);
    return [x, y];
  });
  const d = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = `${d} L${pts[pts.length-1][0]},${height} L${pts[0][0]},${height} Z`;
  const id = React.useMemo(() => 'sp-' + Math.random().toString(36).slice(2,8), []);
  const [drawn, setDrawn] = React.useState(0);
  React.useEffect(() => {
    const t = setTimeout(() => setDrawn(1), 60);
    return () => clearTimeout(t);
  }, []);
  return (
    <svg width={width} height={height} className="spark" style={{ overflow: 'visible' }}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${id})`} style={{ opacity: drawn, transition: 'opacity 500ms ease 200ms' }}/>
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round"
            style={{
              strokeDasharray: 500,
              strokeDashoffset: drawn ? 0 : 500,
              transition: 'stroke-dashoffset 900ms cubic-bezier(.2,.7,.2,1)',
            }}/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.5" fill={color}
              style={{ opacity: drawn, transition: 'opacity 300ms ease 700ms' }}/>
    </svg>
  );
}

/* ============ Top Nav ============ */
function TopNav({ collapsed, onToggle }) {
  const [userOpen, setUserOpen] = React.useState(false);
  const [bellOpen, setBellOpen] = React.useState(false);
  const userRef = React.useRef(null);
  const bellRef = React.useRef(null);

  React.useEffect(() => {
    const h = (e) => {
      if (userRef.current && !userRef.current.contains(e.target)) setUserOpen(false);
      if (bellRef.current && !bellRef.current.contains(e.target)) setBellOpen(false);
    };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  return (
    <header className="nav">
      <div className="nav-logo">
        <button className="nav-collapse-btn" onClick={onToggle} aria-label="Toggle sidebar" title="Toggle sidebar">
          <I.menu />
        </button>
        <div className="logo-mark"><I.logo/></div>
        <span className="logo-word">Nova</span>
      </div>

      <nav className="nav-items">
        <a className="nav-item active">Dashboard</a>
        <a className="nav-item">Analytics</a>
        <a className="nav-item">Customers</a>
        <a className="nav-item">Settings</a>
      </nav>

      <div className="nav-right">
        <div className="nav-search">
          <span className="ico"><I.search/></span>
          <input placeholder="Search orders, customers..."/>
          <kbd>⌘K</kbd>
        </div>

        <div ref={bellRef} style={{ position: 'relative' }}>
          <button className="icon-btn" onClick={() => setBellOpen(v => !v)} aria-label="Notifications">
            <I.bell/>
            <span className="badge-dot">3</span>
          </button>
          {bellOpen && (
            <div className="dropdown" style={{ width: 320 }}>
              <div className="dropdown-label">Notifications</div>
              <div className="dropdown-item">
                <div className="avatar sm" style={{ background: 'linear-gradient(135deg,#34D399,#10B981)' }}>MR</div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: 'var(--text)', fontSize: 12.5 }}><b style={{ fontWeight: 600 }}>Marcus Reed</b> upgraded to Pro</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>14 min ago</div>
                </div>
              </div>
              <div className="dropdown-item">
                <div className="avatar sm" style={{ background: 'linear-gradient(135deg,#FBBF24,#F59E0B)' }}>PP</div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: 'var(--text)', fontSize: 12.5 }}><b style={{ fontWeight: 600 }}>Priya Patel</b> left a 5-star review</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>38 min ago</div>
                </div>
              </div>
              <div className="dropdown-item">
                <div className="avatar sm" style={{ background: 'linear-gradient(135deg,#F87171,#EF4444)' }}>!</div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: 'var(--text)', fontSize: 12.5 }}>Low stock: <b style={{ fontWeight: 600 }}>Ultrabook M2</b></div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>2 hr ago</div>
                </div>
              </div>
              <div className="dropdown-divider"/>
              <button className="dropdown-item" style={{ justifyContent: 'center', color: 'var(--accent-2)' }}>View all notifications</button>
            </div>
          )}
        </div>

        <div ref={userRef} style={{ position: 'relative' }}>
          <button className="user-chip" onClick={() => setUserOpen(v => !v)}>
            <div className="avatar">AN</div>
            <div className="name-wrap">
              <span className="name">Andy</span>
              <span className="role">Admin</span>
            </div>
            <span className="caret"><I.chevDown/></span>
          </button>
          {userOpen && (
            <div className="dropdown">
              <div className="dropdown-label">Role</div>
              <button className="dropdown-item check">Admin <span className="check-ico"><I.check/></span></button>
              <button className="dropdown-item">Editor</button>
              <button className="dropdown-item">Viewer</button>
              <div className="dropdown-divider"/>
              <button className="dropdown-item">Profile settings</button>
              <button className="dropdown-item">Team & billing</button>
              <button className="dropdown-item">Keyboard shortcuts</button>
              <div className="dropdown-divider"/>
              <button className="dropdown-item">Sign out</button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

/* ============ Sidebar ============ */
function Sidebar({ active, onSelect }) {
  return (
    <aside className="side">
      {DATA.sidebar.map(it => {
        const Icn = it.icon;
        const isActive = it.key === active;
        return (
          <button key={it.key} className={`side-item ${isActive ? 'active' : ''}`} onClick={() => onSelect(it.key)}>
            <span className="ico"><Icn/></span>
            <span className="label">{it.label}</span>
            {it.badge && <span className="badge-count">{it.badge}</span>}
          </button>
        );
      })}
      <div className="side-spacer"/>
      <div className="upgrade-card">
        <div className="upgrade-icon"><I.sparkle/></div>
        <div className="up-title">Upgrade to Pro</div>
        <div className="up-sub">Unlock advanced analytics, unlimited exports, and priority support.</div>
        <button className="up-btn">Upgrade now →</button>
      </div>
      <div className="upgrade-mini" title="Upgrade to Pro"><I.sparkle/></div>
    </aside>
  );
}

Object.assign(window, { Sparkline, TopNav, Sidebar });
