// ---- Left sidebar: nav tabs, credit usage bar, account ----
const NAV_GEO = {
  names: 'M12 3l9 9-9 9-9-9z',
  favorites: 'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z',
  history: 'M12 21a9 9 0 110-18 9 9 0 010 18zM12 7.5V12l3 1.8',
  identity: 'M12 2l2.2 5.8L20 10l-5.8 2.2L12 18l-2.2-5.8L4 10l5.8-2.2z',
  billing: 'M3 7.5a2.5 2.5 0 012.5-2.5h13A2.5 2.5 0 0121 7.5v9a2.5 2.5 0 01-2.5 2.5h-13A2.5 2.5 0 013 16.5z',
  whois: 'M16.5 16.5L21 21M4 10.5a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0Z',
  value: 'M12 2.5v19M7.5 6.5h7a3 3 0 010 6H9a3 3 0 000 6h7.5',
  hunt: 'M12 3v3M12 18v3M3 12h3M18 12h3M12 7.5a4.5 4.5 0 100 9 4.5 4.5 0 000-9z',
};
const NAV_GLYPHS = { names: '\u25c7', favorites: '\u2665', history: '\u25f7', identity: '@', billing: '\u25a4', whois: '\u25cb', value: '$', hunt: '\u25ce' };

// Rounded set uses friendlier real-world metaphors (search / heart / user / wallet)
function roundedIcon(id) {
  switch (id) {
    case 'names': return <React.Fragment><circle cx="11" cy="11" r="6.5"></circle><path d="M16 16l4.5 4.5"></path></React.Fragment>;
    case 'favorites': return <path d={NAV_GEO.favorites}></path>;
    case 'identity': return <React.Fragment><circle cx="12" cy="8.5" r="3.5"></circle><path d="M5.5 19.5a6.5 6.5 0 0113 0"></path></React.Fragment>;
    case 'billing': return <React.Fragment><rect x="3" y="6" width="18" height="12" rx="3"></rect><path d="M3 10.5h18"></path></React.Fragment>;
    case 'hunt': return <React.Fragment><circle cx="12" cy="12" r="4.5"></circle><path d="M12 3v3M12 18v3M3 12h3M18 12h3"></path></React.Fragment>;
    default: return null;
  }
}

function NavIcon({ id, set, active }) {
  if (set === 'glyph') {
    return <span className="nav-icon" aria-hidden="true">{NAV_GLYPHS[id]}</span>;
  }
  const line = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinejoin: 'round', strokeLinecap: 'round' };
  let body;
  if (set === 'solid') {
    body = <path d={NAV_GEO[id]} fill="currentColor"></path>;
  } else if (set === 'duotone') {
    body = <path d={NAV_GEO[id]} fill="currentColor" fillOpacity="0.22" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"></path>;
  } else if (set === 'rounded') {
    body = <g {...line}>{roundedIcon(id)}</g>;
  } else { // line
    body = id === 'billing'
      ? <g {...line}><path d={NAV_GEO.billing}></path><path d="M3 10.5h18"></path></g>
      : <path d={NAV_GEO[id]} {...line}></path>;
  }
  return (
    <span className="nav-icon" aria-hidden="true">
      <svg viewBox="0 0 24 24" width="16" height="16" style={{ display: 'block' }}>{body}</svg>
    </span>
  );
}

function Sidebar({ active, onNav, creditsUsed, creditsTotal, favCount, histCount, hasIdentity, planName, iconSet, night, onToggleNight, onTopUp, open, onClose, user, onSignIn }) {
  const pct = Math.min(100, Math.round((Math.min(creditsUsed, creditsTotal) / creditsTotal) * 100));
  const left = Math.max(0, creditsTotal - creditsUsed);
  const set = iconSet || 'line';
  const items = [
    { id: 'names', label: 'Names' },
    { id: 'favorites', label: 'Favorites', count: favCount },
    { id: 'history', label: 'History', count: hasIdentity ? histCount : 0, locked: !hasIdentity },
    { id: 'identity', label: 'Identity', locked: !hasIdentity },
  ];
  return (
    <React.Fragment>
      {open ? <div className="side-scrim" onClick={onClose}></div> : null}
      <nav className={'sidebar' + (open ? ' sidebar-open' : '')} aria-label="Main">
        <div className="side-wordmark">
          <span>namit<span className="wordmark-dot">.</span></span>
          <button className="night-toggle" onClick={onToggleNight} title={night ? 'Switch to day' : 'Switch to midnight'} aria-pressed={night}>
            {night ? (
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><circle cx="12" cy="12" r="4.5" fill="currentColor"></circle><g stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><path d="M12 2.5v2.5M12 19v2.5M2.5 12H5M19 12h2.5M5 5l1.8 1.8M17.2 17.2L19 19M19 5l-1.8 1.8M6.8 17.2L5 19"></path></g></svg>
            ) : (
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M21 12.8A8.5 8.5 0 1111.2 3a6.8 6.8 0 009.8 9.8z"></path></svg>
            )}
          </button>
        </div>
        <div className="nav">
          {items.map(it => (
            <button key={it.id}
              className={'nav-item' + (active === it.id ? ' nav-on' : '')}
              onClick={() => onNav(it.id)}>
              <NavIcon id={it.id} set={set} active={active === it.id} />
              {it.label}
              {it.count ? <span className="nav-count">{it.count}</span> : null}
              {it.locked ? <span className="nav-lock" title="Pro feature" aria-hidden="true">⚿</span> : null}
            </button>
          ))}
          <div className="nav-sep"></div>
          <button className={'nav-item' + (active === 'hunt' ? ' nav-on' : '')} onClick={() => onNav('hunt')}>
            <NavIcon id="hunt" set={set} active={active === 'hunt'} />
            Domain Hunt
            {!hasIdentity ? <span className="nav-lock" title="Pro feature" aria-hidden="true">⚿</span> : null}
          </button>
          <button className={'nav-item' + (active === 'whois' ? ' nav-on' : '')} onClick={() => onNav('whois')}>
            <NavIcon id="whois" set={set} active={active === 'whois'} />
            Domain WHOIS
          </button>
          <button className={'nav-item' + (active === 'value' ? ' nav-on' : '')} onClick={() => onNav('value')}>
            <NavIcon id="value" set={set} active={active === 'value'} />
            Domain value
          </button>
          <div className="nav-sep"></div>
          <button className={'nav-item' + (active === 'billing' ? ' nav-on' : '')} onClick={() => onNav('billing')}>
            <NavIcon id="billing" set={set} active={active === 'billing'} />
            Billing
          </button>
        </div>
        <div className="side-spacer"></div>
        <div className="credit-block">
          <div className="credit-head">
            <span>Credits</span>
            <span className="credit-nums">{left} left</span>
          </div>
          <div className="credit-bar"><div className="credit-fill" style={{ width: pct + '%' }}></div></div>
          <div className="credit-sub">
            <span>{planName} plan</span>
            <button className="btn-link credit-topup" onClick={onTopUp}>Top up</button>
          </div>
        </div>
        {user ? (
          <button className={'account' + (active === 'profile' ? ' account-on' : '')} title="Profile & settings" onClick={() => onNav('profile')}>
            <span className="avatar" style={user.imageUrl ? { backgroundImage: 'url(' + user.imageUrl + ')', backgroundSize: 'cover', backgroundPosition: 'center', color: 'transparent' } : null}>
              {user.imageUrl ? '' : (user.name || 'A').trim().charAt(0).toUpperCase()}
            </span>
            <span className="account-info">
              <span className="account-name">{user.name}</span>
              <span className="account-email">{user.email || '—'}</span>
            </span>
            <span className="account-chev" aria-hidden="true">›</span>
          </button>
        ) : (
          <button className="account" title="Sign in to save your work" onClick={onSignIn}>
            <span className="avatar" aria-hidden="true">↪</span>
            <span className="account-info">
              <span className="account-name">Sign in</span>
              <span className="account-email">Save your work</span>
            </span>
            <span className="account-chev" aria-hidden="true">›</span>
          </button>
        )}
      </nav>
    </React.Fragment>
  );
}

Object.assign(window, { Sidebar });
