/* eslint-disable */
/* timing-print.jsx — печатный A4-документ + библиотека + сводка. */

(function () {
  const R = window.React;
  const { useState } = R;
  const D = window.TimingData;

  /* ============ Библиотека блоков (drag-источник) ============ */
  function Library({ dragInfo, onAdd, onCollapse }) {
    const groups = D.TYPE_ORDER.map(ty => ({
      ty, label: D.TYPES[ty].label, color: D.TYPES[ty].color,
      blocks: D.LIBRARY.filter(b => b.y === ty),
    }));
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ padding: '14px 16px 10px', borderBottom: '1px solid var(--color-line-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ flex: 1, fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase' }}>Библиотека блоков</div>
            {onCollapse && (
              <button onClick={onCollapse} title="Свернуть библиотеку" style={{ flex: '0 0 auto', width: 24, height: 24, border: '1px solid var(--color-line-subtle)', borderRadius: 6, background: 'var(--color-surface)', color: 'var(--color-ink-500)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <Icon name="chevronLeft" size={15} />
              </button>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--color-ink-400)', marginTop: 4, lineHeight: 1.4 }}>Перетащите в тайминг или нажмите, чтобы добавить в конец</div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '10px 12px' }}>
          {groups.map(g => (
            <div key={g.ty} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '0 4px 6px' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: g.color }} />
                <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-700)' }}>{g.label}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {g.blocks.map((b, i) => (
                  <div key={i}
                    draggable
                    onDragStart={() => { dragInfo.current = { type: 'lib', block: b }; }}
                    onDragEnd={() => { dragInfo.current = null; }}
                    onClick={() => onAdd(b)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      padding: '8px 10px', background: 'var(--color-surface)',
                      border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)',
                      cursor: 'grab', userSelect: 'none',
                    }}>
                    <Icon name="grip" size={13} color="var(--color-ink-300)" />
                    <span style={{ flex: 1, fontSize: 12.5, color: 'var(--color-ink-900)', lineHeight: 1.3 }}>{b.t}</span>
                    <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--color-ink-400)', fontVariantNumeric: 'tabular-nums' }}>{b.d}м</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  /* ============ Сводка / инспектор ============ */
  function Summary({ doc, phase, computed, span, onMeta, onPhaseStart, days }) {
    const m = doc.meta;
    const rows = computed.filter(c => c.kind === 'row');
    const hasDays = days && days.length > 1;
    const byType = {};
    rows.forEach(r => { byType[r.type] = (byType[r.type] || 0) + r.dur; });
    const totalDur = rows.reduce((s, r) => s + r.dur, 0) || 1;
    const overlaps = rows.filter(r => r._overlap > 0);
    const phaseStart = phase === 'prep' ? doc.prepStart : doc.eventStart;

    const field = (label, key) => (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginBottom: 8 }}>
        <label style={{ fontSize: 10.5, color: 'var(--color-ink-400)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{label}</label>
        <input value={m[key] || ''} onChange={e => onMeta(key, e.target.value)} style={{
          border: '1px solid var(--color-line-subtle)', background: 'var(--color-canvas)', borderRadius: 'var(--radius-input)',
          padding: '6px 8px', fontSize: 12.5, color: 'var(--color-ink-900)', outline: 'none',
        }} />
      </div>
    );

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%', overflowY: 'auto', paddingRight: 2 }}>
        {/* Totals */}
        {hasDays ? (
          <div style={{ background: 'var(--color-accent-500)', color: '#fff', borderRadius: 'var(--radius-card)', padding: '16px 18px' }}>
            <div style={{ fontSize: 11, fontWeight: 600, opacity: .8, letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 8 }}>Подготовка и монтаж</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, fontVariantNumeric: 'tabular-nums' }}>
              <span style={{ fontSize: 30, fontWeight: 600, lineHeight: 1, fontFamily: 'var(--font-mono)' }}>{days.length}</span>
              <span style={{ fontSize: 14, opacity: .85 }}>{days.length < 5 ? 'дня' : 'дней'}</span>
            </div>
            <div style={{ fontSize: 12, opacity: .82, marginTop: 8 }}>{D.dur(days.reduce((s, d) => s + d.dur, 0))} работы · {rows.length} блоков</div>
          </div>
        ) : (
          <div style={{ background: 'var(--color-accent-500)', color: '#fff', borderRadius: 'var(--radius-card)', padding: '16px 18px' }}>
            <div style={{ fontSize: 11, fontWeight: 600, opacity: .8, letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 8 }}>
              {phase === 'prep' ? 'Подготовка и монтаж' : 'Мероприятие'}
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, fontVariantNumeric: 'tabular-nums' }}>
              <span style={{ fontSize: 26, fontWeight: 600, lineHeight: 1, fontFamily: 'var(--font-mono)' }}>{D.fmt(span.start)}</span>
              <Icon name="arrowRight" size={14} color="rgba(255,255,255,.7)" />
              <span style={{ fontSize: 26, fontWeight: 600, lineHeight: 1, fontFamily: 'var(--font-mono)' }}>{D.fmt(span.end)}</span>
            </div>
            <div style={{ fontSize: 12, opacity: .82, marginTop: 8 }}>{D.dur(span.total)} · {rows.length} блоков</div>
          </div>
        )}

        {/* Phase start */}
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--color-ink-500)' }}>Старт {phase === 'prep' ? 'подготовки' : 'мероприятия'}</div>
            <div style={{ fontSize: 11, color: 'var(--color-ink-400)' }}>якорь для авторасчёта</div>
          </div>
          <input value={D.fmt(phaseStart)} onChange={e => onPhaseStart(D.parse(e.target.value))} style={{
            width: 64, border: '1px solid var(--color-line-subtle)', background: 'var(--color-canvas)', borderRadius: 'var(--radius-input)',
            padding: '6px 8px', fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600, textAlign: 'center',
            color: 'var(--color-ink-900)', fontVariantNumeric: 'tabular-nums', outline: 'none',
          }} />
        </div>

        {hasDays && (
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '14px 16px' }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 8 }}>Дни подготовки</div>
            {days.map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderBottom: i < days.length - 1 ? '1px solid var(--color-line-subtle)' : 'none' }}>
                <span style={{ flex: '0 0 auto', width: 22, height: 22, borderRadius: '50%', background: 'var(--color-muted-50)', color: 'var(--color-accent-700)', fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, color: 'var(--color-ink-900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--color-ink-400)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}>{D.fmt(d.start)}–{D.fmt(d.end)}</div>
                </div>
                <span style={{ flex: '0 0 auto', fontSize: 11.5, color: 'var(--color-ink-500)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}>{D.dur(d.dur)}</span>
              </div>
            ))}
          </div>
        )}

        {/* Type breakdown */}
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '14px 16px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 10 }}>Распределение времени</div>
          {D.TYPE_ORDER.filter(ty => byType[ty]).map(ty => (
            <div key={ty} style={{ marginBottom: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: D.TYPES[ty].color }} />
                <span style={{ flex: 1, fontSize: 12, color: 'var(--color-ink-700)' }}>{D.TYPES[ty].label}</span>
                <span style={{ fontSize: 11.5, color: 'var(--color-ink-500)', fontVariantNumeric: 'tabular-nums' }}>{D.dur(byType[ty])}</span>
              </div>
              <div style={{ height: 5, background: 'var(--color-muted-50)', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{ width: (byType[ty] / totalDur * 100) + '%', height: '100%', background: D.TYPES[ty].color, opacity: .8 }} />
              </div>
            </div>
          ))}
          {!rows.length && <div style={{ fontSize: 12, color: 'var(--color-ink-400)' }}>Нет блоков</div>}
        </div>

        {/* Warnings */}
        {overlaps.length > 0 && (
          <div style={{ background: 'var(--color-warning-50)', border: '1px solid rgba(176,134,60,0.25)', borderRadius: 'var(--radius-card)', padding: '12px 14px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: 'var(--color-warning-700)', marginBottom: 6 }}>
              <Icon name="alertCircle" size={13} /> Накладки по времени
            </div>
            {overlaps.map(o => (
              <div key={o.id} style={{ fontSize: 11.5, color: 'var(--color-warning-700)', marginBottom: 2 }}>
                «{o.title || 'Блок'}» начинается на {D.dur(o._overlap)} раньше окончания предыдущего
              </div>
            ))}
          </div>
        )}

        {/* Event meta */}
        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '14px 16px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 10 }}>Шапка документа</div>
          {field('Мероприятие', 'event')}
          {field('Дата', 'date')}
          {field('Площадка', 'venue')}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {field('Масштаб', 'guests')}
            {field('Код', 'code')}
          </div>
          {field('Менеджер (PM)', 'pm')}
        </div>
      </div>
    );
  }

  /* ============ Сводка для сетки мероприятия ============ */
  function GridSummary({ doc, grid, span, onMeta }) {
    const m = doc.meta;
    const field = (label, key) => (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginBottom: 8 }}>
        <label style={{ fontSize: 10.5, color: 'var(--color-ink-400)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{label}</label>
        <input value={m[key] || ''} onChange={e => onMeta(key, e.target.value)} style={{
          border: '1px solid var(--color-line-subtle)', background: 'var(--color-canvas)', borderRadius: 'var(--radius-input)',
          padding: '6px 8px', fontSize: 12.5, color: 'var(--color-ink-900)', outline: 'none',
        }} />
      </div>
    );
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%', overflowY: 'auto', paddingRight: 2 }}>
        <div style={{ background: 'var(--color-accent-500)', color: '#fff', borderRadius: 'var(--radius-card)', padding: '16px 18px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, opacity: .8, letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 8 }}>Мероприятие</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, fontVariantNumeric: 'tabular-nums' }}>
            <span style={{ fontSize: 26, fontWeight: 600, lineHeight: 1, fontFamily: 'var(--font-mono)' }}>{D.fmt(span.start)}</span>
            <Icon name="arrowRight" size={14} color="rgba(255,255,255,.7)" />
            <span style={{ fontSize: 26, fontWeight: 600, lineHeight: 1, fontFamily: 'var(--font-mono)' }}>{D.fmt(span.end)}</span>
          </div>
          <div style={{ fontSize: 12, opacity: .82, marginTop: 8 }}>{D.dur(span.total)} · {grid.slots.length} слотов · {grid.cards.length} карточек</div>
        </div>

        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '14px 16px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 10 }}>Колонки (треки)</div>
          {grid.tracks.map(t => {
            const n = grid.cards.filter(c => c.trackId === t.id).length;
            return (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: D.trackColor(t.color), flex: '0 0 auto' }} />
                <span style={{ flex: 1, fontSize: 12.5, color: 'var(--color-ink-700)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</span>
                <span style={{ fontSize: 11.5, color: 'var(--color-ink-500)', fontVariantNumeric: 'tabular-nums' }}>{n}</span>
              </div>
            );
          })}
          {!grid.tracks.length && <div style={{ fontSize: 12, color: 'var(--color-ink-400)' }}>Нет колонок</div>}
        </div>

        <div style={{ background: 'var(--color-muted-50)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '12px 14px', fontSize: 11.5, color: 'var(--color-ink-500)', lineHeight: 1.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--color-ink-700)', fontWeight: 500, marginBottom: 4, whiteSpace: 'nowrap' }}>
            <Icon name="grip" size={13} /> Как пользоваться
          </div>
          Карточки тащите между ячейками. Блоки из библиотеки можно бросать прямо в ячейку. «+» в ячейке — новая карточка.
        </div>

        <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-line-subtle)', borderRadius: 'var(--radius-card)', padding: '14px 16px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--color-ink-500)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 10 }}>Шапка документа</div>
          {field('Мероприятие', 'event')}
          {field('Дата', 'date')}
          {field('Площадка', 'venue')}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {field('Масштаб', 'guests')}
            {field('Код', 'code')}
          </div>
          {field('Менеджер (PM)', 'pm')}
        </div>
      </div>
    );
  }

  /* ============ Печатный документ A4 ============ */
  function PrintTiming({ title, range, items, phaseStart }) {
    const computed = D.computeTimes(items, phaseStart);
    let dayNum = 0;
    return (
      <div className="pt-block">
        <div className="pt-phase-head">
          <span className="pt-phase-title">{title}</span>
          <span className="pt-phase-range">{range}</span>
        </div>
        <div className="pt-rows">
          {computed.map(it => {
            if (it.kind === 'day') {
              dayNum++;
              return (
                <div key={it.id} className="pt-dayhead">
                  <span className="pt-dayhead-n">День {dayNum}</span>
                  {it.date && <span className="pt-dayhead-d">{it.date}</span>}
                  <span className="pt-dayhead-t">старт {D.fmt(it.start)}</span>
                </div>
              );
            }
            if (it.kind === 'section') {
              return <div key={it.id} className="pt-section">{it.title}</div>;
            }
            const t = D.TYPES[it.type];
            return (
              <div key={it.id} className="pt-row">
                <div className="pt-time">
                  <span className="pt-start">{D.fmt(it._start)}–{D.fmt(it._end)}</span>
                  <span className="pt-dur">{D.dur(it.dur)}</span>
                </div>
                <div className="pt-bar" style={{ background: t.color }} />
                <div className="pt-body">
                  <div className="pt-titleline">
                    <span className="pt-tag" style={{ color: t.color }}>{t.label}</span>
                    <span className="pt-title">{it.title}</span>
                  </div>
                  <div className="pt-meta">
                    {it.who && <span>{it.who}</span>}
                    {it.zone && <span className="pt-zone">{it.zone}</span>}
                    {it.note && <span className="pt-note">{it.note}</span>}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  /* ============ Печатная сетка мероприятия ============ */
  function PrintGrid({ title, range, grid }) {
    const slots = grid.slots.slice().sort((a, b) => a.time - b.time);
    const cols = '46px repeat(' + grid.tracks.length + ', 1fr)';
    return (
      <div className="pt-block">
        <div className="pt-phase-head">
          <span className="pt-phase-title">{title}</span>
          <span className="pt-phase-range">{range}</span>
        </div>
        <div className="pt-grid" style={{ gridTemplateColumns: cols }}>
          <div className="pt-g-corner">Время</div>
          {grid.tracks.map(t => (
            <div key={t.id} className="pt-g-head">
              <span className="pt-g-dot" style={{ background: D.trackColor(t.color) }} />{t.name}
            </div>
          ))}
          {slots.map((slot, i) => {
            const next = slots[i + 1];
            const delta = next ? next.time - slot.time : 0;
            return (
              <React.Fragment key={slot.id}>
                <div className="pt-g-time">
                  <span className="pt-g-time-v">{D.fmt(slot.time)}</span>
                  {delta > 0 && <span className="pt-g-delta">+{D.dur(delta)}</span>}
                </div>
                {grid.tracks.map(t => {
                  const cards = grid.cards.filter(c => c.trackId === t.id && c.slotId === slot.id);
                  return (
                    <div key={t.id} className="pt-g-cell">
                      {cards.map(c => (
                        <div key={c.id} className="pt-g-card" style={{ borderLeftColor: D.trackColor(t.color) }}>
                          <div className="pt-g-card-t">{c.title}</div>
                          {(c.dur || c.who) && <div className="pt-g-card-m">{[c.dur ? D.dur(c.dur) : null, c.who || null].filter(Boolean).join(' · ')}</div>}
                        </div>
                      ))}
                    </div>
                  );
                })}
              </React.Fragment>
            );
          })}
        </div>
      </div>
    );
  }

  function PrintSheet({ tag, m, today, pageStyle, first, children }) {
    return (
      <div className={'print-doc print-sheet' + (first ? ' print-sheet-first' : '')} style={pageStyle}>
        <div className="pt-header">
          <div className="pt-brand">
            <div className="pt-logo">EZ</div>
            <div>
              <div className="pt-brand-name">EZ‑C</div>
              <div className="pt-brand-sub">EZS Events</div>
            </div>
          </div>
          <div className="pt-doc-tag">
            <div>{tag}</div>
            <div className="pt-version">{m.code || '—'} · напечатано {today}</div>
          </div>
        </div>
        <div className="pt-title-block">
          <h1>{m.event || 'Мероприятие'}</h1>
          <div className="pt-title-meta">
            {[m.date, m.venue, m.guests].filter(Boolean).join('  ·  ')}
            {m.pm && <span className="pt-pm">PM: {m.pm}</span>}
          </div>
        </div>
        {children}
      </div>
    );
  }

  function PrintDoc({ doc, pageStyle }) {
    const m = doc.meta;
    const pDays = D.dayBlocks(doc.prep, doc.prepStart);
    const hasDays = doc.prep.some(it => it.kind === 'day');
    const prepSpan = D.phaseSpan(D.computeTimes(doc.prep, doc.prepStart), doc.prepStart);
    const evSpan = D.gridSpan(doc.eventGrid);
    const today = new Date().toLocaleDateString('ru-RU', { day: '2-digit', month: 'short', year: 'numeric' });
    const prepRange = hasDays
      ? pDays.length + ' дн. · ' + D.dur(pDays.reduce((s, d) => s + d.dur, 0)) + ' работы'
      : D.fmt(prepSpan.start) + '–' + D.fmt(prepSpan.end) + ' · ' + D.dur(prepSpan.total);
    return (
      <React.Fragment>
        <PrintSheet first tag="ТАЙМИНГ · ПОДГОТОВКА" m={m} today={today} pageStyle={pageStyle}>
          <PrintTiming title="ПОДГОТОВКА И МОНТАЖ" range={prepRange} items={doc.prep} phaseStart={doc.prepStart} />
          <div className="pt-legend">
            <span className="pt-legend-lab">Типы работ:</span>
            {D.TYPE_ORDER.map(ty => (
              <span key={ty} className="pt-legend-item">
                <span className="pt-legend-dot" style={{ background: D.TYPES[ty].color }} />{D.TYPES[ty].label}
              </span>
            ))}
          </div>
        </PrintSheet>

        <PrintSheet tag="ТАЙМИНГ · МЕРОПРИЯТИЕ" m={m} today={today} pageStyle={pageStyle}>
          <PrintGrid title="СЦЕНАРИЙ МЕРОПРИЯТИЯ" range={D.fmt(evSpan.start) + '–' + D.fmt(evSpan.end) + ' · ' + D.dur(evSpan.total)} grid={doc.eventGrid} />
        </PrintSheet>
      </React.Fragment>
    );
  }

  window.TimingPrint = { Library, Summary, GridSummary, PrintDoc };
})();
