// Plazify · Reviews landing — "Глубокий анализ отзывов" с табами (по отзывам / SKU / конкретной SKU)
const { useState: useStateA, useRef: useRefA } = React;

function MetricBars({ items }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {items.map((it, i) => (
        <div key={i}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontFamily: 'var(--plz-font-ui)', fontSize: 13.5 }}>
            <span style={{ color: '#202023' }}>{it.label}</span>
            <span style={{ color: it.fg, fontWeight: 600 }}>{it.pct}%</span>
          </div>
          <div style={{ height: 8, borderRadius: 100, background: '#EEF0F5', overflow: 'hidden' }}>
            <div style={{ width: it.pct + '%', height: '100%', borderRadius: 100, background: it.fg }}></div>
          </div>
        </div>
      ))}
    </div>
  );
}

function Insight({ kind, label, text }) {
  const c = kind === 'good' ? { bg: '#E4F7F0', fg: '#40856C' } : { bg: '#FFEBEB', fg: '#D65151' };
  return (
    <div style={{ background: c.bg, borderRadius: 16, padding: '16px 18px' }}>
      <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 13, color: c.fg, marginBottom: 6 }}>{label}</div>
      <div style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 14.5, lineHeight: 1.5, color: '#202023' }}>{text}</div>
    </div>
  );
}

function PanelAll() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 28 }} className="an-split">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ background: '#F4F5FE', borderRadius: 16, padding: 22 }}>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 13, color: '#5C5C62', marginBottom: 8 }}>Средний рейтинг</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 700, fontSize: 44, color: '#202023', lineHeight: 1 }}>4,79</span>
            <Stars n={5} size={18} />
          </div>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 13, color: '#95959E', marginTop: 10 }}>312 отзывов · 1–30 сентября 2025</div>
        </div>
        <Insight kind="good" label="Главное преимущество" text="Качество материала и точность размеров — упоминают 41% покупателей." />
        <Insight kind="bad" label="Главная проблема" text="Поверхность ближе к низу скатывается — 12% негативных отзывов." />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div style={{ background: '#E0E4FF', borderRadius: 16, padding: '18px 20px' }}>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 13, color: '#5E3EE5', marginBottom: 6 }}>Главный вывод</div>
          <p style={{ margin: 0, fontFamily: 'var(--plz-font-ui)', fontSize: 15, lineHeight: 1.55, color: '#202023' }}>
            Товар оценивают высоко за качество и посадку. Основной негатив — износ велюра в нижней части: точечная доработка материала может поднять рейтинг до 4,9.
          </p>
        </div>
        <div>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 14, color: '#202023', marginBottom: 14 }}>Системные проблемы</div>
          <MetricBars items={[
            { label: 'Скатывание материала внизу', pct: 12, fg: '#D65151' },
            { label: 'Запах при распаковке', pct: 7, fg: '#AE7331' },
            { label: 'Сложность сборки', pct: 5, fg: '#AE7331' },
          ]} />
        </div>
        <div style={{ borderTop: '1px solid #EEF0F5', paddingTop: 18 }}>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 14, color: '#202023', marginBottom: 12 }}>Рекомендации</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {['Доработать износостойкость велюра в нижней зоне', 'Добавить памятку по сборке в карточку товара', 'Усилить упаковку для устранения запаха'].map((t, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <MIcon name="check" size={17} color="#5E3EE5" stroke={2.4} />
                <span style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 14, lineHeight: 1.45, color: '#5C5C62' }}>{t}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function PanelSku() {
  const rows = [
    { n: 'Кровать детская санни 160×100', art: '169765491', r: '4,79', cnt: 312, p: 'Скатывание материала' },
    { n: 'Кровать подростковая односпальная', art: '769478193', r: '4,62', cnt: 184, p: 'Сложность сборки' },
    { n: 'Матрас «Санни» 160×80', art: '551209348', r: '4,88', cnt: 97, p: 'Запах при распаковке' },
    { n: 'Бортик защитный универсальный', art: '903417762', r: '4,41', cnt: 56, p: 'Крепления слабые' },
  ];
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px 90px 110px 1fr', gap: 16, padding: '0 4px 12px', borderBottom: '1px solid #E4E6EB', fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 12.5, color: '#95959E' }}>
        <span>Товар</span><span>Арт. WB</span><span>Рейтинг</span><span>Отзывов</span><span>Главная проблема</span>
      </div>
      {rows.map((r, i) => (
        <div key={i} className="an-skurow" style={{ display: 'grid', gridTemplateColumns: '1fr 120px 90px 110px 1fr', gap: 16, padding: '16px 4px', borderBottom: '1px solid #EEF0F5', alignItems: 'center', fontFamily: 'var(--plz-font-ui)', fontSize: 14 }}>
          <span style={{ fontWeight: 600, color: '#202023' }}>{r.n}</span>
          <span style={{ color: '#5C5C62' }}>{r.art}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: '#202023', fontWeight: 600 }}><Stars n={5} size={12} /> {r.r}</span>
          <span style={{ color: '#5C5C62' }}>{r.cnt}</span>
          <span><span style={{ background: '#FFEBEB', color: '#D65151', borderRadius: 100, padding: '4px 11px', fontSize: 13, fontWeight: 600 }}>{r.p}</span></span>
        </div>
      ))}
    </div>
  );
}

function PanelOne() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }} className="an-split">
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
          <div style={{ width: 56, height: 56, borderRadius: 12, background: 'linear-gradient(135deg, hsl(28 40% 90%), hsl(28 45% 78%))', flex: '0 0 auto' }}></div>
          <div>
            <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 15, color: '#202023' }}>Кровать детская санни 160×100</div>
            <div style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 13, color: '#95959E', marginTop: 4 }}>Арт. WB: 169765491</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 18 }}>
          <span style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 700, fontSize: 40, color: '#202023' }}>4,79</span>
          <Stars n={5} size={16} />
          <span style={{ fontFamily: 'var(--plz-font-ui)', fontSize: 13, color: '#95959E' }}>· 312 отзывов</span>
        </div>
        <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 14, color: '#202023', marginBottom: 12 }}>Что хвалят</div>
        <MetricBars items={[
          { label: 'Качество материала', pct: 41, fg: '#40856C' },
          { label: 'Точность размеров', pct: 33, fg: '#40856C' },
          { label: 'Быстрый возврат денег', pct: 18, fg: '#40856C' },
        ]} />
      </div>
      <div>
        <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 14, color: '#202023', marginBottom: 12 }}>На что жалуются</div>
        <MetricBars items={[
          { label: 'Скатывание материала внизу', pct: 12, fg: '#D65151' },
          { label: 'Запах при распаковке', pct: 7, fg: '#AE7331' },
          { label: 'Сложность сборки', pct: 5, fg: '#AE7331' },
        ]} />
        <div style={{ background: '#E0E4FF', borderRadius: 16, padding: '16px 18px', marginTop: 20 }}>
          <div style={{ fontFamily: 'var(--plz-font-ui)', fontWeight: 600, fontSize: 13, color: '#5E3EE5', marginBottom: 6 }}>Вывод по SKU</div>
          <p style={{ margin: 0, fontFamily: 'var(--plz-font-ui)', fontSize: 14.5, lineHeight: 1.55, color: '#202023' }}>
            Сильная посадка и материал. Доработка износостойкости велюра внизу — главный рычаг роста рейтинга.
          </p>
        </div>
      </div>
    </div>
  );
}

const TABS = [
  { id: 'all', label: 'По всем отзывам', img: 'analyticsAll', alt: 'Аналитика по всем отзывам — общая статистика и выводы' },
  { id: 'sku', label: 'По всем SKU', img: 'analyticsSku', alt: 'Аналитика по всем SKU — список товаров' },
  { id: 'one', label: 'По конкретной SKU', img: 'analyticsOne', alt: 'Аналитика по конкретной SKU — детали товара' },
];

function Analytics() {
  const [tab, setTab] = useStateA('all');
  const activeIndex = TABS.findIndex(t => t.id === tab);
  // Mobile (<=620px): 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 = useRefA(null);
  const go = (dir) => {
    const ni = Math.min(TABS.length - 1, Math.max(0, activeIndex + dir));
    if (ni === activeIndex) return;
    setTab(TABS[ni].id);
    track('analytics_tab', { tab: 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="analytics" style={{ paddingTop: 144 }}>
      <div className="analytics-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: 700, fontSize: 19 }}>
          Платформа разбирает все отзывы за период и показывает, что именно не так с товаром — по каждой SKU и по всей матрице.
        </p>
      </div>
      {/* desktop/tablet — segmented tabs (hidden <=620px) */}
      <div className="ship-tabs-row" style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
        <div 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)' }}>
          {TABS.map(t => (
            <button key={t.id} onClick={() => { setTab(t.id); track('analytics_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">{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 3 states (all images 1872×992); 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: '1872 / 992', overflow: 'hidden' }}>
          <div style={{
            display: 'flex', width: `${TABS.length * 100}%`, height: '100%',
            transform: `translateX(-${activeIndex * (100 / TABS.length)}%)`,
            transition: 'transform .42s cubic-bezier(.4,0,.2,1)',
          }}>
            {TABS.map(t => (
              <div key={t.id} style={{ width: `${100 / TABS.length}%`, height: '100%', flex: '0 0 auto' }}>
                <img src={window.__resources[t.img]} alt={t.alt} loading="lazy" decoding="async" style={{ display: 'block', width: '100%', height: '100%', objectFit: 'contain' }} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </Section>
  );
}
Object.assign(window, { Analytics });
