// Plazify · Supply landing — "Автоматизация процесса подсортировки и поставки"
// Reuses the approved /reviews analytics slider mechanics: segmented pill tabs + a fixed-aspect
// sliding viewport (stable height, no layout jump). Real product screenshots where available;
// the "Выгрузка в Excel" view is a clean TODO placeholder until the export mockup is provided.
const { useState: useStateSh, useRef: useRefSh } = React;

const SHIP_TABS = [
  { id: 'create', label: 'Создание поставки', kind: 'img', img: 'postavkiScreen', alt: 'Создание и список поставок, сгруппированных по складам и регионам', cap: 'Система формирует поставку, группирует её по складам и регионам и помечает статусы — вам остаётся подтвердить.' },
  { id: 'calc', label: 'Расчёт товаров', kind: 'img', img: 'skladScreen', alt: 'Расчёт количества товаров к поставке по каждой SKU', cap: 'Рассчитывает количество к поставке по каждой SKU с учётом оборачиваемости, рентабельности, логистики и сроков доставки.' },
  // TODO(asset): replace with the real "Выгрузка в Excel" export mockup when available.
  { id: 'export', label: 'Выгрузка в Excel', kind: 'todo', cap: 'Готовый расчёт поставки можно выгрузить для работы — например в Excel, если такая логика предусмотрена в реализации.' },
];

function ShipTodo() {
  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      gap: 16, background: '#F4F5FE', color: '#5C5C62', textAlign: 'center', padding: 40,
    }}>
      {/* TODO(asset): supply Excel-export mockup not provided in Figma — clean placeholder */}
      <span style={{ width: 64, height: 64, borderRadius: 18, background: '#E0E4FF', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
        <MIcon name="layers" size={28} color="#5E3EE5" stroke={2} />
      </span>
      <div style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 700, fontSize: 20, color: '#202023' }}>Выгрузка плана поставки</div>
      <div style={{ fontFamily: 'var(--plz-font-head)', fontSize: 15, lineHeight: 1.5, maxWidth: 440 }}>
        Готовый расчёт можно подготовить к выгрузке для работы команды.
      </div>
    </div>
  );
}

function Shipment() {
  const [tab, setTab] = useStateSh('create');
  const activeIndex = SHIP_TABS.findIndex(t => t.id === tab);
  const cap = SHIP_TABS[activeIndex].cap;
  // Mobile: prev/next arrows + horizontal swipe drive the SAME tab state as the desktop
  // segmented control, so the active label and the sliding viewport stay in sync.
  const touchX = useRefSh(null);
  const go = (dir) => {
    const ni = Math.min(SHIP_TABS.length - 1, Math.max(0, activeIndex + dir));
    if (ni === activeIndex) return;
    setTab(SHIP_TABS[ni].id);
    track('supply_ship_tab', { tab: SHIP_TABS[ni].id });
  };
  const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
  };
  return (
    <Section id="shipment" style={{ paddingTop: 144 }}>
      <div className="shipment-head" style={{ textAlign: 'center', marginBottom: 64 }}>
        <h2 className="plz-h2 sec-h2" style={{ margin: '0 0 16px' }}>Автоматизация процесса<br />подсортировки и поставок</h2>
        <p className="plz-lead" style={{ margin: '0 auto', maxWidth: 780, fontSize: 19 }}>
          Система создаёт поставку, сгруппированную по складам и регионам, и рассчитывает количество
          товаров с учётом рентабельности, оборачиваемости, логистики и сроков доставки.
        </p>
      </div>

      {/* desktop/tablet — segmented tabs (same pattern as /reviews analytics) */}
      <div className="ship-tabs-row" style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
        <div className="ship-tabs" style={{ display: 'inline-flex', background: '#fff', border: '1px solid #E4E6EB', borderRadius: 100, padding: 5, gap: 4, boxShadow: '0 4px 14px -8px rgba(32,32,35,.10)', maxWidth: '100%', flexWrap: 'wrap' }}>
          {SHIP_TABS.map(t => (
            <button key={t.id} onClick={() => { setTab(t.id); track('supply_ship_tab', { tab: t.id }); }} style={{
              border: 'none', cursor: 'pointer', borderRadius: 100, padding: '10px 20px',
              fontFamily: 'var(--plz-font-head)', fontWeight: 600, fontSize: 14.5, transition: 'background .2s ease, color .2s ease',
              background: tab === t.id ? '#202023' : 'transparent', color: tab === t.id ? '#fff' : '#5C5C62',
            }}>{t.label}</button>
          ))}
        </div>
      </div>

      {/* mobile-only — single active label with prev/next arrows (hidden by default; shown <=620px) */}
      <div className="ship-selector" style={{ display: 'none' }}>
        <button type="button" className="ship-arrow" aria-label="Предыдущий слайд" onClick={() => go(-1)}>‹</button>
        <div className="ship-active-label">{SHIP_TABS[activeIndex].label}</div>
        <button type="button" className="ship-arrow" aria-label="Следующий слайд" onClick={() => go(1)}>›</button>
      </div>

      {/* fixed-aspect sliding viewport — stable height across all states; swipeable on touch */}
      <div onTouchStart={onTouchStart} onTouchEnd={onTouchEnd} style={{
        maxWidth: 1080, margin: '0 auto', borderRadius: 24, overflow: 'hidden',
        background: '#fff', boxShadow: '0 18px 50px -22px rgba(32,32,35,.14), 0 3px 10px -5px rgba(32,32,35,.06)',
        touchAction: 'pan-y',
      }}>
        <div style={{ position: 'relative', width: '100%', aspectRatio: '1600 / 1000', overflow: 'hidden' }}>
          <div style={{
            display: 'flex', width: `${SHIP_TABS.length * 100}%`, height: '100%',
            transform: `translateX(-${activeIndex * (100 / SHIP_TABS.length)}%)`,
            transition: 'transform .42s cubic-bezier(.4,0,.2,1)',
          }}>
            {SHIP_TABS.map(t => (
              <div key={t.id} style={{ width: `${100 / SHIP_TABS.length}%`, height: '100%', flex: '0 0 auto' }}>
                {t.kind === 'img'
                  ? <img src={window.__resources[t.img]} alt={t.alt} loading="lazy" decoding="async" style={{ display: 'block', width: '100%', height: '100%', objectFit: 'contain' }} />
                  : <ShipTodo />}
              </div>
            ))}
          </div>
        </div>
      </div>

      <p className="ship-cap" style={{ textAlign: 'center', margin: '28px auto 0', maxWidth: 720, fontFamily: 'var(--plz-font-head)', fontSize: 15.5, lineHeight: 1.5, color: '#5C5C62' }}>{cap}</p>
    </Section>
  );
}
Object.assign(window, { Shipment });
