// ToolRail.jsx — fixed left-edge panel of tool icons (hidden on mobile).
const railSlug = (s) => 'tool-' + s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

const TOOL_RAIL_ITEMS = [
  { name: 'Override Dimensions', icon: 'assets/icon-override-dimensions.png', wip: false },
  { name: 'Filter Sort',         icon: 'assets/icon-filter-sort.png',         wip: false },
  { name: 'Layer Inspector',     icon: 'assets/icon-layer-inspector.png',     wip: false },
  { name: 'Structure Manager',   icon: 'assets/icon-structure-manager.png',   wip: false },
  { name: 'Clean Sheets',        icon: 'assets/icon-clean-sheets.png',        wip: false },
  { name: 'Crop Size',            icon: 'assets/icon-crop-size.png',           wip: false },
  { name: 'Favourite Views',           icon: 'assets/icon-favourite-views.png',  wip: true },
  { name: 'Selection List',            icon: 'assets/icon-selection-list.png',   wip: true },
  { name: 'Open DWG Folder Location',  icon: 'assets/icon-open-dwg-folder.png',  wip: true },
  { name: 'Reload DWG Link',           icon: 'assets/icon-reload-dwg.png',       wip: true },
  { name: 'Export Linked DWG State',   icon: 'assets/icon-export-dwg-state.png', wip: true },
  { name: 'Import Linked DWG State',   icon: 'assets/icon-import-dwg-state.png', wip: true },
];

const ToolRailItem = ({ item, interactive, lang }) => {
  const [hover, setHover] = React.useState(false);
  const it = lang === 'it';
  const clickable = interactive && !item.wip;

  const onClick = () => {
    if (!clickable) return;
    const el = document.getElementById(railSlug(item.name));
    if (!el) return;
    const targetY = el.getBoundingClientRect().top + window.scrollY - 76;
    const startY = window.scrollY;
    const dist = targetY - startY;
    if (Math.abs(dist) < 2) return;
    const duration = Math.min(900, Math.max(420, Math.abs(dist) * 0.5));
    const startT = performance.now();
    const easeInOutCubic = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    const step = (now) => {
      const p = Math.min(1, (now - startT) / duration);
      window.scrollTo(0, startY + dist * easeInOutCubic(p));
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  };

  const label = item.wip
    ? `${item.name} · ${it ? 'in arrivo' : 'coming soon'}`
    : item.name;

  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
      onKeyDown={e => { if (clickable && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onClick(); } }}
      aria-label={label}
      style={{
        position: 'relative',
        width: 44, height: 44, borderRadius: 'var(--radius-md)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: clickable ? 'pointer' : 'default',
        background: clickable && hover ? 'var(--brand-subtle)' : 'transparent',
        transition: 'background 120ms',
        outline: 'none',
      }}
    >
      <img
        src={item.icon}
        alt={item.name}
        draggable={false}
        style={{
          width: 30, height: 30, objectFit: 'contain', display: 'block',
          opacity: item.wip ? 0.32 : 1,
          filter: item.wip ? 'grayscale(1)' : 'none',
          transition: 'transform 120ms',
          transform: clickable && hover ? 'scale(1.08)' : 'scale(1)',
        }}
      />
      {hover && (
        <div style={{
          position: 'absolute', left: 'calc(100% + 10px)', top: '50%',
          transform: 'translateY(-50%)', whiteSpace: 'nowrap',
          background: 'var(--neutral-800)', color: 'var(--white)',
          fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 500,
          padding: '5px 10px', borderRadius: 'var(--radius-sm)',
          boxShadow: 'var(--shadow-2)', pointerEvents: 'none', zIndex: 1,
        }}>
          {label}
          <span style={{
            position: 'absolute', right: '100%', top: '50%', transform: 'translateY(-50%)',
            borderTop: '5px solid transparent', borderBottom: '5px solid transparent',
            borderRight: '5px solid var(--neutral-800)',
          }}/>
        </div>
      )}
    </div>
  );
};

const ToolRail = ({ page, lang }) => {
  const mobile = window.useIsMobile(768);
  if (mobile) return null;
  if (page !== 'home') return null;
  const interactive = page === 'home';

  return (
    <nav
      aria-label="Tools"
      style={{
        position: 'fixed', left: 12, top: '50%', transform: 'translateY(-50%)',
        zIndex: 90,
        display: 'flex', flexDirection: 'column', gap: 2,
        background: 'var(--white)', border: '1px solid var(--border)',
        borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-2)',
        padding: 6,
      }}
    >
      {TOOL_RAIL_ITEMS.map((item, i) => {
        const dividerBefore = i > 0 && item.wip && !TOOL_RAIL_ITEMS[i - 1].wip;
        return (
          <React.Fragment key={item.name}>
            {dividerBefore && (
              <div style={{ height: 1, background: 'var(--border)', margin: '4px 6px' }}/>
            )}
            <ToolRailItem item={item} interactive={interactive} lang={lang}/>
          </React.Fragment>
        );
      })}
    </nav>
  );
};

Object.assign(window, { ToolRail, railSlug, TOOL_RAIL_ITEMS });
window.TOOL_ICONS = TOOL_RAIL_ITEMS.reduce((m, t) => { m[t.name] = t.icon; return m; }, {});
