// Sidebar.jsx — internal app left nav with i18n + active prop.
// The bottom "Settings" item opens a modal with global app preferences
// (the same Label position pref used everywhere). Per-page overrides live
// on each page; this modal sets the default.

const Sidebar = ({ active = 'shipments' }) => {
  const [, , t] = useLang();
  const [prefs] = usePrefs();
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const itemsRaw = [
    { id: 'dash',      key: 'nav.dashboard', icon: 'chart',  href: 'index.html' },
    { id: 'shipments', key: 'nav.shipments', icon: 'ship',   href: 'Cases.html' },
    { id: 'stock',     key: 'nav.stock',     icon: 'boxes',  href: 'Stock List.html' },
    { id: 'customs',   key: 'nav.customs',   icon: 'customs',href: 'Customs.html' },
    { id: 'docs',      key: 'nav.docs',      icon: 'file',   href: 'Delivery Notes.html' },
    { id: 'invoices',  key: 'nav.invoices',  icon: 'inbox',  href: 'Invoices.html' },
    { id: 'vat',       key: 'nav.vat',       icon: 'file',   href: 'VAT Exemption.html' },
  ];
  // Apply user-defined order from prefs (Settings → Sidebar order).
  const order = effectiveSidebarOrder(prefs, itemsRaw.map(i => i.id));
  const byId = Object.fromEntries(itemsRaw.map(i => [i.id, i]));
  const items = order.map(id => byId[id]).filter(Boolean);

  const openSettings = (e) => {
    e.preventDefault();
    setSettingsOpen(true);
  };

  return (
    <aside className="sidebar" style={{ position: 'relative', display: 'flex', flexDirection: 'column', paddingBottom: 64 }}>
      <div className="sb-brand">
        <a href="index.html" style={{ display: 'inline-flex' }}>
          <img src="assets/frontline-logo-white.png" alt="Frontline" />
        </a>
      </div>

      <div className="sb-section">{t('nav.ops')}</div>
      <nav className="sb-nav">
        {items.map(it => (
          <a key={it.id} href={it.href} tabIndex={0}
             className={`${active === it.id ? 'active' : ''} ${it.danger ? 'danger' : ''}`}>
            <Icon name={it.icon} size={14} />
            <span>{t(it.key)}</span>
            {it.badge ? <span className="badge">{it.badge}</span> : null}
          </a>
        ))}
      </nav>

      <nav className="sb-nav" style={{ marginTop: 'auto' }}>
        <a href="#" tabIndex={0}
           className={`${active === 'settings' || settingsOpen ? 'active' : ''}`}
           onClick={openSettings}>
          <Icon name="cog" size={14} />
          <span>{t('nav.settings')}</span>
        </a>
      </nav>

      <div className="sb-foot">
        <span className="avt">JN</span>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.2 }}>
          <span style={{ color: '#fff', fontSize: 12 }}>Jordan Naka</span>
          <span style={{ fontSize: 10, opacity: 0.6 }}>Ocean ops · LAX</span>
        </div>
      </div>

      {settingsOpen ? <SettingsModal onClose={() => setSettingsOpen(false)} /> : null}
    </aside>
  );
};

// ---------------------------------------------------------------------------
// SettingsModal — global app preferences. Today: form label position + language.
// The label-position control here writes to the same `labels` pref used by the
// in-page <LabelPositionSwitch>; a per-page override beats this default on the
// page that set it.
const SettingsModal = ({ onClose }) => {
  const [prefs, setPref] = usePrefs();
  const [lang, changeLang, t] = useLang();
  const overlayRef = React.useRef(null);

  // Esc closes; focus the panel so keyboard nav lands inside.
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const onOverlayClick = (e) => {
    if (e.target === overlayRef.current) onClose();
  };

  const labels = prefs.labels || 'side';
  const tableMode = prefs.tableMode || 'compact';

  return ReactDOM.createPortal(
    <div ref={overlayRef} className="stk-modal-overlay settings-overlay" onClick={onOverlayClick}>
      <div className="stk-modal settings-modal" role="dialog" aria-modal="true" aria-label={t('settings.title')}>
        <div className="stk-modal-head">
          <div>
            <div className="eyebrow">{t('nav.settings').toUpperCase()}</div>
            <h2>{t('settings.title')}</h2>
            <p className="sub">{t('settings.sub')}</p>
          </div>
          <button type="button" className="icon-x" onClick={onClose} aria-label={t('settings.close')}>
            <Icon name="close" size={16} />
          </button>
        </div>

        <div className="stk-modal-body">
          <div className="settings-section">
            <div className="settings-section-title">{t('settings.appearance')}</div>

            <div className="settings-row">
              <div className="settings-row-text">
                <div className="lab">{t('settings.labels')}</div>
                <div className="hint">{t('settings.labels.hint')}</div>
              </div>
              <div className="lp-switch settings-switch">
                <div className="lp-seg">
                  <button type="button"
                          className={labels === 'side' ? 'on' : ''}
                          aria-pressed={labels === 'side'}
                          onClick={() => setPref('labels', 'side')}>
                    {t('switch.labels.side')}
                  </button>
                  <button type="button"
                          className={labels === 'top' ? 'on' : ''}
                          aria-pressed={labels === 'top'}
                          onClick={() => setPref('labels', 'top')}>
                    {t('switch.labels.top')}
                  </button>
                </div>
              </div>
            </div>

            <div className="settings-row">
              <div className="settings-row-text">
                <div className="lab">{t('settings.tables')}</div>
                <div className="hint">{t('settings.tables.hint')}</div>
              </div>
              <div className="lp-switch settings-switch is-wide">
                <div className="lp-seg">
                  <button type="button"
                          className={tableMode === 'compact' ? 'on' : ''}
                          aria-pressed={tableMode === 'compact'}
                          onClick={() => setPref('tableMode', 'compact')}>
                    {t('switch.table.compact')}
                  </button>
                  <button type="button"
                          className={tableMode === 'wide' ? 'on' : ''}
                          aria-pressed={tableMode === 'wide'}
                          onClick={() => setPref('tableMode', 'wide')}>
                    {t('switch.table.wide')}
                  </button>
                </div>
              </div>
            </div>

            <div className="settings-row">
              <div className="settings-row-text">
                <div className="lab">{t('settings.lang')}</div>
              </div>
              <LanguageToggle />
            </div>
          </div>

          <SidebarOrderSection />
        </div>

        <div className="stk-modal-foot end">
          <button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>
            {t('settings.close')}
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
};

window.Sidebar = Sidebar;
window.SettingsModal = SettingsModal;

// ---------------------------------------------------------------------------
// SidebarOrderSection — lets the user reorder nav items in the sidebar.
// Drag the grip to move; up/down arrows give keyboard-friendly reordering.
// Persists `sidebarOrder` (array of ids) into prefs; sidebars re-render
// instantly via the prefschange event.
const SIDEBAR_ITEM_DEFS = [
  { id: 'dash',      key: 'nav.dashboard', icon: 'chart'   },
  { id: 'shipments', key: 'nav.shipments', icon: 'ship'    },
  { id: 'stock',     key: 'nav.stock',     icon: 'boxes'   },
  { id: 'customs',   key: 'nav.customs',   icon: 'customs' },
  { id: 'docs',      key: 'nav.docs',      icon: 'file'    },
  { id: 'invoices',  key: 'nav.invoices',  icon: 'inbox'   },
  { id: 'vat',       key: 'nav.vat',       icon: 'file'    },
];

const SidebarOrderSection = () => {
  const [prefs] = usePrefs();
  const [, , t] = useLang();
  const defaultIds = SIDEBAR_ITEM_DEFS.map(i => i.id);
  const order = effectiveSidebarOrder(prefs, defaultIds);
  const byId = Object.fromEntries(SIDEBAR_ITEM_DEFS.map(i => [i.id, i]));

  const [dragId, setDragId] = React.useState(null);
  const [overId, setOverId] = React.useState(null);

  const commit = (next) => {
    // If the new order matches default, clear the pref (back to "default").
    const matchesDefault = next.length === defaultIds.length
      && next.every((id, i) => id === defaultIds[i]);
    setPref('sidebarOrder', matchesDefault ? null : next);
  };

  const move = (id, delta) => {
    const idx = order.indexOf(id);
    const target = idx + delta;
    if (idx < 0 || target < 0 || target >= order.length) return;
    const next = order.slice();
    next.splice(idx, 1);
    next.splice(target, 0, id);
    commit(next);
  };

  const reset = () => setPref('sidebarOrder', null);
  const isDefault = !prefs.sidebarOrder || !prefs.sidebarOrder.length;

  const onDragStart = (id) => (e) => {
    setDragId(id);
    try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', id); }
    catch (err) {}
  };
  const onDragOver = (id) => (e) => {
    e.preventDefault();
    try { e.dataTransfer.dropEffect = 'move'; } catch (err) {}
    if (overId !== id) setOverId(id);
  };
  const onDragLeave = (id) => () => {
    if (overId === id) setOverId(null);
  };
  const onDrop = (id) => (e) => {
    e.preventDefault();
    const from = dragId;
    setDragId(null);
    setOverId(null);
    if (!from || from === id) return;
    const next = order.slice();
    const fromIdx = next.indexOf(from);
    next.splice(fromIdx, 1);
    const toIdx = next.indexOf(id);
    next.splice(toIdx, 0, from);
    commit(next);
  };
  const onDragEnd = () => { setDragId(null); setOverId(null); };

  return (
    <div className="settings-section">
      <div className="settings-section-title settings-section-title--with-action">
        <span>{t('settings.nav')}</span>
        {!isDefault ? (
          <button type="button" className="settings-link" onClick={reset}>
            {t('settings.navorder.reset')}
          </button>
        ) : null}
      </div>

      <div className="settings-row settings-row--block">
        <div className="settings-row-text" style={{ marginBottom: 8 }}>
          <div className="lab">{t('settings.navorder')}</div>
          <div className="hint">{t('settings.navorder.hint')}</div>
        </div>

        <ul className="reorder-list" role="list">
          {order.map((id, i) => {
            const it = byId[id];
            if (!it) return null;
            const dragging = dragId === id;
            const over = overId === id && dragId && dragId !== id;
            return (
              <li key={id}
                  className={`reorder-item${dragging ? ' is-dragging' : ''}${over ? ' is-over' : ''}`}
                  draggable="true"
                  onDragStart={onDragStart(id)}
                  onDragOver={onDragOver(id)}
                  onDragLeave={onDragLeave(id)}
                  onDrop={onDrop(id)}
                  onDragEnd={onDragEnd}>
                <span className="reorder-grip" aria-hidden="true" title={t('settings.navorder.drag')}>
                  <Icon name="grip" size={14} />
                </span>
                <span className="reorder-icon" aria-hidden="true">
                  <Icon name={it.icon} size={14} />
                </span>
                <span className="reorder-label">{t(it.key)}</span>
                <span className="reorder-index">{i + 1}</span>
                <span className="reorder-actions">
                  <button type="button"
                          className="reorder-btn"
                          aria-label={t('settings.navorder.up')}
                          title={t('settings.navorder.up')}
                          disabled={i === 0}
                          onClick={() => move(id, -1)}>
                    <Icon name="chev_u" size={14} />
                  </button>
                  <button type="button"
                          className="reorder-btn"
                          aria-label={t('settings.navorder.down')}
                          title={t('settings.navorder.down')}
                          disabled={i === order.length - 1}
                          onClick={() => move(id, +1)}>
                    <Icon name="chev_d" size={14} />
                  </button>
                </span>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
};

window.SidebarOrderSection = SidebarOrderSection;