// Peek-on-hover sidebar. Rail ~56px always visible; expands to 280px on hover.
// Content: Tabs (active + groups) + Pinned Bookmarks.

const RAIL = 56;
const EXPANDED = 288;

const SIDEBAR_TABS = [
  { id: 't1', title: 'New Tab', url: 'ajna://newtab', active: true, fav: <AjnaMark size={16}/> },
  { id: 't2', title: 'Gmail — Inbox (12)', fav: <Favicon domain="gmail.com" size={16} radius={4}/> },
  { id: 't3', title: 'GitHub · pull/482', fav: <Favicon domain="github.com" size={16} radius={4}/> },
  { id: 't4', title: 'Linear — Sprint 14', fav: <Favicon domain="linear.app" size={16} radius={4}/> },
  { id: 't5', title: 'Notion · Weekly Notes', fav: <Favicon domain="notion.so" size={16} radius={4}/> },
  { id: 't6', title: 'YouTube', fav: <Favicon domain="youtube.com" size={16} radius={4}/> },
  { id: 't7', title: 'Stack Overflow', fav: <Favicon domain="stackoverflow.com" size={16} radius={4}/> },
  { id: 't8', title: 'MDN — CSS Grid', fav: <Favicon domain="developer.mozilla.org" size={16} radius={4}/> },
  { id: 't9', title: 'Hacker News', fav: <Favicon domain="news.ycombinator.com" size={16} radius={4}/> },
];
const TAB_GROUPS = [
  {
    name: 'Design',
    color: '#60A5FA',
    tabs: [
      { title: 'Figma — Ajna v4', fav: <Favicon domain="figma.com" size={14} radius={4}/> },
      { title: 'Dribbble', fav: <Favicon domain="dribbble.com" size={14} radius={4}/> },
      { title: 'Refactoring UI', fav: <Favicon domain="refactoringui.com" size={14} radius={4}/> },
    ],
  },
  {
    name: 'Research',
    color: '#A78BFA',
    tabs: [
      { title: 'Chromium docs', fav: <Favicon domain="chromium.org" size={14} radius={4}/> },
      { title: 'WebKit blog', fav: <Favicon domain="webkit.org" size={14} radius={4}/> },
    ],
  },
];
const PINNED = [
  { title: 'GitHub', domain: 'github.com' },
  { title: 'Linear', domain: 'linear.app' },
  { title: 'Notion', domain: 'notion.so' },
  { title: 'Gmail', domain: 'gmail.com' },
  { title: 'Calendar', domain: 'calendar.google.com' },
  { title: 'Slack', domain: 'slack.com' },
  { title: 'Figma', domain: 'figma.com' },
  { title: 'YouTube', domain: 'youtube.com' },
];

function Sidebar({ forceExpanded, onOpenSettings, onOpenAllTabs, activeVariant, onNavigate, url = 'linear.app/inbox', onMenuAction }) {
  const [hover, setHover] = React.useState(false);
  const [mountedExpanded, setMountedExpanded] = React.useState(forceExpanded);

  // First-open behavior: on mount, sidebar opens then collapses after ~1.6s.
  React.useEffect(() => {
    if (forceExpanded) return;
    setMountedExpanded(true);
    const t = setTimeout(() => setMountedExpanded(false), 1800);
    return () => clearTimeout(t);
  }, [forceExpanded]);

  const expanded = hover || mountedExpanded || forceExpanded;
  // Layout width only changes when the sidebar is PINNED. On hover the panel
  // floats above the stage instead, so the web content never reflows.
  const layoutWidth = forceExpanded ? EXPANDED : RAIL;
  const floating = expanded && !forceExpanded;

  return (
    <aside
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative',
        width: layoutWidth, flexShrink: 0,
        transition: 'width 260ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        zIndex: 30,
      }}
    >
    <div style={{
      position: 'absolute', top: 0, bottom: 0, left: 0,
      width: expanded ? EXPANDED : RAIL,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      borderRadius: 14,
      background: floating ? 'var(--bg-elev)' : 'transparent',
      backdropFilter: floating ? 'blur(24px) saturate(1.6)' : 'none',
      WebkitBackdropFilter: floating ? 'blur(24px) saturate(1.6)' : 'none',
      border: '1px solid ' + (floating ? 'var(--border-soft)' : 'transparent'),
      boxShadow: floating ? 'var(--lift)' : 'none',
      transition: 'width 260ms cubic-bezier(0.2, 0.8, 0.2, 1), background 200ms, box-shadow 200ms, border-color 200ms',
    }}>
      {/* Top: nav + address + apps */}
      <div style={{ padding: '10px 6px 4px', display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 }}>
        <NavRow expanded={expanded} onMenuAction={onMenuAction}/>
        <AddressField expanded={expanded} url={url}/>
      </div>

      <Divider/>

      <div style={{ padding: '0 6px', display: 'flex', flexDirection: 'column', gap: 2, flexShrink: 0 }}>
        <AIRow expanded={expanded} open={activeVariant === 'ai'} onClick={() => onNavigate && onNavigate('ai')}/>
      </div>

      <Divider/>

      <div style={{ padding: '0 6px', display: 'flex', flexDirection: 'column', gap: 2, flexShrink: 0 }}>
        <RailRow expanded={expanded} icon={<Ic.plus/>} label="New tab" accent/>
        <RailRow expanded={expanded} icon={<Ic.search s={16}/>} label="Search tabs" hint="⌘K"/>
      </div>

      <Divider/>

      {/* Scrollable middle: open tabs + groups + pinned */}
      <div className="ajna-sidebar-scroll" style={{
        flex: 1, minHeight: 0,
        overflowY: 'auto', overflowX: 'hidden',
        overscrollBehavior: 'contain', minHeight: 200,
      }}>
        <SectionLabel expanded={expanded}>Apps</SectionLabel>
        <div style={{ padding: '0 6px 6px' }}>
          <AppsGrid expanded={expanded} apps={PINNED}/>
        </div>

        <Divider/>

        {/* Active tabs */}
        <SectionLabel expanded={expanded}>Open tabs</SectionLabel>
        <div style={{ padding: '0 6px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          {SIDEBAR_TABS.map((t, i) => (
            <TabRow key={i} expanded={expanded} tab={t}/>
          ))}
        </div>

        {/* Tab groups */}
        {TAB_GROUPS.map((g, i) => (
          <TabGroup key={i} group={g} expanded={expanded}/>
        ))}

      </div>

      {/* Footer — compact icon row so open tabs keep the space */}
      <div style={{
        padding: '6px', borderTop: '1px solid var(--border-soft)',
        display: 'flex', flexWrap: 'nowrap', gap: 2, flexShrink: 0,
        justifyContent: 'flex-start',
      }}>
        {[
          ['settings', <Ic.settings/>, 'Settings'],
          ['messages', <Ic.chat/>, 'Messages'],
          ['calls', <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>, 'Calls'],
          ['history', <HistIcon/>, 'History'],
          ['bookmarks', <BkmIcon/>, 'Bookmarks'],
          ['downloads', <DlIcon/>, 'Downloads'],
          ['alltabs', <Ic.grid/>, 'All tabs'],
        ].slice(0, expanded ? 7 : 1).map(([id, icon, label]) => {
          const active = activeVariant === id;
          return (
            <button key={id} title={label} onClick={() => {
              if (id === 'settings') return onOpenSettings && onOpenSettings();
              if (id === 'alltabs') return onOpenAllTabs && onOpenAllTabs();
              onNavigate && onNavigate(id);
            }} style={{
              width: 32, minWidth: 32, height: 30, borderRadius: 8, border: 0, cursor: 'pointer',
              display: 'grid', placeItems: 'center', flexShrink: 0,
              background: active ? 'oklch(from var(--accent-b) l c h / 0.14)' : 'transparent',
              color: active ? 'var(--accent-b)' : 'var(--fg-muted)',
            }}
            onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--hover)'; }}
            onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>{icon}</button>
          );
        })}
      </div>
    </div>
    </aside>
  );
}

const HistIcon = () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 9"/><path d="M3 3v6h6"/><path d="M12 7v5l3 2"/></svg>;
const BkmIcon = () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21V5a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v16l7-4z"/></svg>;
const DlIcon = () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v12M6 11l6 6 6-6M5 21h14"/></svg>;

// Address field lives in the sidebar. Collapsed it shrinks to a lock chip.
function AddressField({ expanded, url }) {
  const [host, ...rest] = String(url).split('/');
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      height: 32, minWidth: 44, padding: '0 8px 0 10px',
      borderRadius: 9, background: 'var(--bg)',
      border: '1px solid var(--border-soft)',
      color: 'var(--fg)', fontSize: 12.5, cursor: 'text',
      overflow: 'hidden',
    }} title={url}>
      <span style={{ color: 'var(--fg-dim)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="4" y="10" width="16" height="11" rx="2.5"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>
      </span>
      <span style={{
        flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        opacity: expanded ? 1 : 0, transition: 'opacity 150ms',
      }}>
        {host}<span style={{ color: 'var(--fg-dim)' }}>{rest.length ? '/' + rest.join('/') : ''}</span>
      </span>
      <span style={{
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--fg-dim)',
        padding: '2px 5px', background: 'var(--bg-elev-2)', borderRadius: 4, flexShrink: 0,
        opacity: expanded ? 1 : 0, transition: 'opacity 150ms',
      }}>⌘L</span>
    </div>
  );
}

function NavRow({ expanded, onMenuAction }) {
  const [menu, setMenu] = React.useState(false);
  const btnRef = React.useRef(null);
  const [pos, setPos] = React.useState(null);
  const openMenu = () => {
    const r = btnRef.current.getBoundingClientRect();
    setPos({ left: r.left - 8, top: r.bottom - 30 });
    setMenu(true);
  };
  const btn = (child, dim, key, onClick, ref) => (
    <button key={key} ref={ref} onClick={onClick} style={{
      width: 28, height: 26, minWidth: 28, borderRadius: 7, border: 0, cursor: 'pointer',
      background: 'transparent', color: dim ? 'var(--fg-dim)' : 'var(--fg-muted)',
      display: 'grid', placeItems: 'center', flexShrink: 0,
    }}
    onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>{child}</button>
  );
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 2,
      opacity: expanded ? 1 : 0, transition: 'opacity 150ms',
      pointerEvents: expanded ? 'auto' : 'none',
    }}>
      {btn(<Ic.back/>, false, 'b')}
      {btn(<Ic.fwd/>, true, 'f')}
      {btn(<Ic.reload/>, false, 'r')}
      <span style={{ flex: 1 }}/>
      {btn(<Ic.more/>, false, 'm', () => (menu ? setMenu(false) : openMenu()), btnRef)}
      {menu && pos && ReactDOM.createPortal(
        <div style={{ position: 'fixed', left: pos.left, top: pos.top, width: 270, zIndex: 200 }}>
          <UrlBarMenu onClose={() => setMenu(false)} onAction={(id) => { setMenu(false); onMenuAction && onMenuAction(id); }}/>
        </div>, document.body)}
    </div>
  );
}

// Ajna AI entry — was in the old top bar, now a first-class sidebar action.
function AIRow({ expanded, open, onClick }) {
  const on = open;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '7px 8px', borderRadius: 8, cursor: 'pointer', width: '100%',
      background: on ? 'linear-gradient(135deg, var(--accent-a), var(--accent-b))' : 'var(--bg-elev-2)',
      color: on ? '#0B0C0F' : 'var(--fg)',
      fontSize: 13, fontWeight: 600,
    }} onClick={onClick}>
      <span style={{ width: 28, minWidth: 28, height: 22, display: 'grid', placeItems: 'center', flexShrink: 0, color: on ? '#0B0C0F' : 'var(--accent-b)' }}><Ic.sparkle s={15}/></span>
      <span style={{ flex: 1, whiteSpace: 'nowrap', opacity: expanded ? 1 : 0, transition: 'opacity 150ms' }}>Ajna AI</span>
    </div>
  );
}

// Apps: pinned sites as a launcher grid when expanded, a stack of icons when collapsed.
function AppsGrid({ apps, expanded }) {
  // Height is identical in both states (34px) so the tab list never shifts.
  if (!expanded) {
    return (
      <div title="Apps" style={{
        height: 34, borderRadius: 9, display: 'grid', placeItems: 'center', cursor: 'pointer',
        background: 'var(--bg-elev-2)', boxShadow: 'inset 0 0 0 1px var(--border-soft)',
      }}><Favicon domain={apps[0].domain} size={18} radius={5}/></div>
    );
  }
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 5 }}>
      {apps.slice(0, 4).map((a, i) => (
        <div key={i} title={a.title} style={{
          height: 34, borderRadius: 9, display: 'grid', placeItems: 'center', cursor: 'pointer',
          background: 'var(--bg-elev-2)', boxShadow: 'inset 0 0 0 1px var(--border-soft)',
          transition: 'transform 140ms, box-shadow 140ms',
        }}
        onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = 'inset 0 0 0 1px oklch(from var(--accent-b) l c h / 0.35)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'inset 0 0 0 1px var(--border-soft)'; }}>
          <Favicon domain={a.domain} size={18} radius={5}/>
        </div>
      ))}
      <div title="All apps" style={{
        height: 34, borderRadius: 9, display: 'grid', placeItems: 'center', cursor: 'pointer',
        color: 'var(--fg-dim)', fontSize: 11, fontFamily: 'JetBrains Mono, monospace',
        boxShadow: 'inset 0 0 0 1px var(--border-soft)',
      }}>+{Math.max(apps.length - 4, 0)}</div>
    </div>
  );
}

function Divider() {
  return <div style={{ height: 1, background: 'var(--border-soft)', margin: '8px 12px' }}/>;
}

function SectionLabel({ children, expanded }) {
  return (
    <div style={{
      height: 22, padding: '0 16px', display: 'flex', alignItems: 'center',
      fontSize: 10, fontWeight: 600, letterSpacing: '0.1em',
      color: 'var(--fg-dim)', textTransform: 'uppercase',
      opacity: expanded ? 1 : 0, transition: 'opacity 180ms',
      whiteSpace: 'nowrap',
    }}>{children}</div>
  );
}

function RailRow({ icon, label, expanded, hint, accent, onClick, active }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '7px 8px', borderRadius: 8,
      background: active
        ? 'oklch(from var(--accent-b) l c h / 0.14)'
        : accent ? 'var(--bg-elev-2)' : 'transparent',
      boxShadow: active ? 'inset 0 0 0 1px oklch(from var(--accent-b) l c h / 0.25)' : 'none',
      border: 0, cursor: 'pointer',
      color: active ? 'var(--fg)' : 'var(--fg)',
      fontSize: 13, textAlign: 'left', width: '100%',
      fontFamily: 'inherit',
    }}
      onMouseEnter={e => { if (!accent && !active) e.currentTarget.style.background = 'var(--hover)'; }}
      onMouseLeave={e => { if (!accent && !active) e.currentTarget.style.background = 'transparent'; }}
    >
      <span style={{ width: 28, minWidth: 28, height: 22, display: 'grid', placeItems: 'center', color: active ? 'var(--accent-b)' : 'var(--fg-muted)', flexShrink: 0 }}>{icon}</span>
      <span style={{ flex: 1, whiteSpace: 'nowrap', opacity: expanded ? 1 : 0, transition: 'opacity 150ms' }}>{label}</span>
      {hint && expanded && <span style={{
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--fg-dim)',
        padding: '2px 6px', background: 'var(--bg-elev-2)', borderRadius: 4,
      }}>{hint}</span>}
    </button>
  );
}

function TabRow({ tab, expanded }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '4px 8px', borderRadius: 10,
      background: tab.active
        ? 'linear-gradient(90deg, oklch(from var(--accent-a) l c h / 0.14), oklch(from var(--accent-b) l c h / 0.08))'
        : 'transparent',
      boxShadow: tab.active
        ? 'inset 0 0 0 1px oklch(from var(--accent-b) l c h / 0.18)'
        : 'none',
      color: 'var(--fg)', fontSize: 13, cursor: 'pointer',
      position: 'relative',
    }}>
      <span style={{
        width: 28, minWidth: 28, height: 28, borderRadius: 8,
        display: 'grid', placeItems: 'center', flexShrink: 0,
        background: tab.active ? 'var(--bg-elev-2)' : 'transparent',
        boxShadow: tab.active
          ? '0 0 0 1px oklch(from var(--accent-b) l c h / 0.25), 0 4px 12px oklch(from var(--accent-b) l c h / 0.15)'
          : 'none',
      }}>{tab.fav}</span>
      <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', opacity: expanded ? 1 : 0, transition: 'opacity 150ms' }}>{tab.title}</span>
      {tab.active && expanded && <span style={{
        width: 6, height: 6, borderRadius: '50%',
        background: 'var(--accent-grad)', flexShrink: 0,
        boxShadow: '0 0 8px oklch(from var(--accent-b) l c h / 0.5)',
      }}/>}
    </div>
  );
}

function TabGroup({ group, expanded }) {
  // Groups render as a bounded box. Collapsed: box shows group header tile +
  // every member favicon vertically (no dead space). Expanded: same box grows
  // to show favicon + title rows. Icons stay in the same 28px slot throughout.
  return (
    <div style={{ padding: '4px 6px' }}>
      <div style={{
        borderRadius: 10,
        background: `${group.color}10`,
        boxShadow: `inset 0 0 0 1px ${group.color}33`,
        padding: 4,
        display: 'flex', flexDirection: 'column', gap: 2,
      }}>
        {/* Header row */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '4px 4px', borderRadius: 7, cursor: 'pointer',
          color: 'var(--fg)', fontSize: 12.5, fontWeight: 600,
        }}
        onMouseEnter={e => e.currentTarget.style.background = `${group.color}20`}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
          <span style={{
            position: 'relative',
            width: 28, minWidth: 28, height: 28, borderRadius: 8,
            background: `${group.color}33`,
            boxShadow: `inset 0 0 0 1px ${group.color}66`,
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <div style={{ display: 'flex', position: 'relative', width: 18, height: 12, justifyContent: 'center' }}>
              {group.tabs.slice(0, 3).map((t, i) => (
                <div key={i} style={{
                  position: 'absolute', left: i * 5,
                  width: 11, height: 11, borderRadius: 3,
                  background: 'var(--sidebar-bg)',
                  boxShadow: `0 0 0 1.2px ${group.color}`,
                  display: 'grid', placeItems: 'center',
                  overflow: 'hidden', zIndex: 3 - i,
                }}>
                  <span style={{ transform: 'scale(0.6)' }}>{t.fav}</span>
                </div>
              ))}
            </div>
            <div style={{
              position: 'absolute', bottom: -3, right: -4,
              minWidth: 14, height: 14, padding: '0 3px', borderRadius: 7,
              background: group.color, color: '#0F1114',
              fontSize: 8, fontWeight: 700,
              display: 'grid', placeItems: 'center',
              fontFamily: 'JetBrains Mono, monospace',
              boxShadow: '0 0 0 2px var(--sidebar-bg)',
            }}>{group.tabs.length}</div>
          </span>
          <span style={{
            flex: 1, whiteSpace: 'nowrap',
            opacity: expanded ? 1 : 0, transition: 'opacity 150ms',
          }}>{group.name}</span>
        </div>
        {/* Nested tabs — always rendered. Icon always visible; title fades in. */}
        {group.tabs.map((t, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '2px 4px', borderRadius: 7, cursor: 'pointer',
            color: 'var(--fg-muted)', fontSize: 12.5,
          }}
          onMouseEnter={e => e.currentTarget.style.background = `${group.color}20`}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span style={{
              width: 28, minWidth: 28, height: 24, position: 'relative',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <span style={{ transform: 'scale(1.05)' }}>{t.fav}</span>
              <span style={{
                position: 'absolute', left: 0, top: 6, bottom: 6, width: 2,
                borderRadius: 1, background: group.color, opacity: 0.55,
              }}/>
            </span>
            <span style={{
              flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              opacity: expanded ? 1 : 0, transition: 'opacity 150ms',
            }}>{t.title}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, RAIL, EXPANDED });
