/* eslint-disable */
/* timing-builder.jsx — интерактивный конструктор тайминга. */

(function () {
  const R = window.React;
  const { useState, useRef, useEffect, useMemo } = R;
  const D = window.TimingData;

  const STORE_KEY = 'ezc.timing.doc.v1';

  /* ============ Inline-редактируемый текст ============ */
  function EditText({ value, onChange, placeholder, mono, weight, size, color, align, width, flex, onEnter, autoFocus }) {
    return (
      <input
        value={value}
        placeholder={placeholder}
        autoFocus={autoFocus}
        onChange={e => onChange(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter' && onEnter) { e.preventDefault(); onEnter(); } }}
        style={{
          width: width || '100%', flex: flex,
          border: '1px solid transparent', background: 'transparent',
          borderRadius: 5, padding: '3px 6px', margin: '-3px -6px',
          fontFamily: mono ? 'var(--font-mono)' : 'inherit',
          fontWeight: weight || 400, fontSize: size || 13,
          color: color || 'var(--color-ink-900)',
          textAlign: align || 'left',
          fontVariantNumeric: mono ? 'tabular-nums' : 'normal',
          outline: 'none',
        }}
        onFocus={e => { e.target.style.background = 'var(--color-surface)'; e.target.style.borderColor = 'var(--color-line-strong)'; e.target.style.boxShadow = 'var(--ring)'; }}
        onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; e.target.style.boxShadow = 'none'; }}
      />
    );
  }

  /* ============ Селектор типа (цветная метка) ============ */
  function TypeSelect({ value, onChange }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    useEffect(() => {
      if (!open) return;
      const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
      document.addEventListener('mousedown', h);
      return () => document.removeEventListener('mousedown', h);
    }, [open]);
    const t = D.TYPES[value];
    return (
      <div ref={ref} style={{ position: 'relative', flex: '0 0 auto' }}>
        <button onClick={() => setOpen(o => !o)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '3px 8px 3px 7px', borderRadius: 'var(--radius-pill)',
          border: '1px solid var(--color-line-subtle)', background: 'var(--color-surface)',
          fontSize: 11.5, fontWeight: 500, color: 'var(--color-ink-700)', whiteSpace: 'nowrap',
        }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.color }} />
          {t.label}
          <Icon name="chevronDown" size={11} color="var(--color-ink-400)" />
        </button>
        {open && (
          <div style={{
            position: 'absolute', top: '100%', left: 0, marginTop: 4, zIndex: 30,
            background: 'var(--color-elevated)', border: '1px solid var(--color-line-subtle)',
            borderRadius: 'var(--radius-card)', boxShadow: 'var(--shadow-modal)', padding: 4, minWidth: 150,
          }}>
            {D.TYPE_ORDER.map(k => (
              <button key={k} onClick={() => { onChange(k); setOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '6px 8px', borderRadius: 5, border: 0, background: k === value ? 'var(--color-muted-50)' : 'transparent',
                fontSize: 12.5, color: 'var(--color-ink-900)', textAlign: 'left',
              }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: D.TYPES[k].color }} />
                <span style={{ flex: 1 }}>{D.TYPES[k].label}</span>
                {k === value && <Icon name="check" size={12} color="var(--color-accent-500)" />}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }

  /* ============ Строка тайминга ============ */
  function TimingRow({ item, idx, onPatch, onDelete, onDup, onGrab, grabbed, dragOver, onAddAfter, autoFocusId }) {
    const t = D.TYPES[item.type];
    const [hover, setHover] = useState(false);
    return (
      <div
        draggable={grabbed}
        onDragEnd={() => onGrab(null)}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          position: 'relative',
          display: 'grid', gridTemplateColumns: '20px 78px 4px 1fr 64px',
          gap: 10, alignItems: 'stretch',
          padding: '10px 12px 10px 6px',
          background: grabbed ? 'var(--color-muted-50)' : 'var(--color-surface)',
          borderBottom: '1px solid var(--color-line-subtle)',
          opacity: grabbed ? 0.5 : 1,
        }}>
        {/* drag handle */}
        <button
          onMouseDown={() => onGrab(item.id)}
          onMouseUp={() => onGrab(null)}
          title="Перетащить"
          style={{
            alignSelf: 'center', width: 20, height: 26, border: 0, background: 'transparent',
            color: hover ? 'var(--color-ink-400)' : 'var(--color-ink-300)', cursor: 'grab',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
          <Icon name="grip" size={14} />
        </button>

        {/* time rail */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'stretch', gap: 1, paddingTop: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <input
              value={D.fmt(item._start)}
              onChange={e => onPatch({ pin: D.parse(e.target.value) })}
              style={{
                width: 50, border: '1px solid transparent', background: 'transparent', borderRadius: 4,
                padding: '1px 3px', fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 600,
                color: 'var(--color-ink-900)', fontVariantNumeric: 'tabular-nums', outline: 'none',
              }}
              onFocus={e => { e.target.style.background = 'var(--color-surface)'; e.target.style.borderColor = 'var(--color-line-strong)'; }}
              onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; }}
            />
            {item.pin != null && (
              <button title="Снять фиксацию времени" onClick={() => onPatch({ pin: null })}
                style={{ border: 0, background: 'transparent', padding: 0, color: 'var(--color-accent-500)', display: 'flex' }}>
                <Icon name="flag" size={10} />
              </button>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 3, color: 'var(--color-ink-500)', fontSize: 11 }}>
            <input
              type="number" min="0" step="5"
              value={item.dur}
              onChange={e => onPatch({ dur: Math.max(0, parseInt(e.target.value || '0', 10)) })}
              style={{
                width: 26, border: '1px solid transparent', background: 'transparent', borderRadius: 4,
                padding: '0 2px', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--color-ink-500)',
                fontVariantNumeric: 'tabular-nums', outline: 'none', textAlign: 'right',
              }}
              onFocus={e => { e.target.style.background = 'var(--color-surface)'; e.target.style.borderColor = 'var(--color-line-strong)'; }}
              onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; }}
            />
            <span>мин</span>
          </div>
        </div>

        {/* color bar */}
        <div style={{ background: t.color, borderRadius: 2, opacity: 0.85 }} />

        {/* main */}
        <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <TypeSelect value={item.type} onChange={v => onPatch({ type: v })} />
            <EditText value={item.title} onChange={v => onPatch({ title: v })} placeholder="Действие…" weight={500} size={13.5} flex={1} onEnter={onAddAfter ? () => onAddAfter(item.id) : undefined} autoFocus={autoFocusId === item.id} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
              {item.who ? <Avatar name={item.who} size={18} /> : <Icon name="users" size={13} color="var(--color-ink-400)" />}
              <EditText value={item.who} onChange={v => onPatch({ who: v })} placeholder="Ответственный" size={12} color="var(--color-ink-700)" width={150} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, minWidth: 0 }}>
              <Icon name="target" size={12} color="var(--color-ink-400)" />
              <EditText value={item.zone} onChange={v => onPatch({ zone: v })} placeholder="Зона" size={12} color="var(--color-ink-500)" width={120} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, flex: 1, minWidth: 80 }}>
              <Icon name="messageSquare" size={12} color="var(--color-ink-400)" />
              <EditText value={item.note} onChange={v => onPatch({ note: v })} placeholder="Заметка" size={12} color="var(--color-ink-500)" flex={1} />
            </div>
          </div>
        </div>

        {/* actions */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end', gap: 2, opacity: hover ? 1 : 0, transition: 'opacity .12s' }}>
          <button title="Дублировать" onClick={onDup} style={actBtn}>
            <Icon name="copy" size={13} />
          </button>
          <button title="Удалить" onClick={onDelete} style={actBtn}>
            <Icon name="trash" size={13} />
          </button>
        </div>

        {dragOver === 'before' && <DropLine pos="top" />}
        {dragOver === 'after' && <DropLine pos="bottom" />}
      </div>
    );
  }
  const actBtn = {
    width: 26, height: 26, borderRadius: 5, border: 0, background: 'transparent',
    color: 'var(--color-ink-400)', display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
  function DropLine({ pos }) {
    return <div style={{
      position: 'absolute', left: 6, right: 12, height: 2, background: 'var(--color-accent-500)',
      borderRadius: 2, zIndex: 5, [pos]: -1, boxShadow: '0 0 0 2px rgba(44,58,87,0.15)',
    }} />;
  }

  /* ============ Заголовок раздела ============ */
  function SectionRow({ item, onPatch, onDelete, onGrab, grabbed, dragOver, collapsed, onToggle, subtotal }) {
    const [hover, setHover] = useState(false);
    return (
      <div
        draggable={grabbed}
        onDragEnd={() => onGrab(null)}
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          position: 'relative', display: 'grid', gridTemplateColumns: '20px 1fr auto 64px', gap: 10, alignItems: 'center',
          padding: '12px 12px 8px 6px', background: 'var(--color-canvas)',
          borderBottom: '1px solid var(--color-line-subtle)', borderTop: '1px solid var(--color-line-subtle)',
          opacity: grabbed ? 0.5 : 1,
        }}>
        <button onMouseDown={() => onGrab(item.id)} onMouseUp={() => onGrab(null)} style={{
          alignSelf: 'center', width: 20, height: 22, border: 0, background: 'transparent',
          color: hover ? 'var(--color-ink-400)' : 'var(--color-ink-300)', cursor: 'grab', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="grip" size={14} />
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
          <button onClick={onToggle} title={collapsed ? 'Развернуть' : 'Свернуть'} style={{
            flex: '0 0 auto', width: 18, height: 18, border: 0, background: 'transparent', padding: 0,
            color: 'var(--color-ink-400)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            transform: collapsed ? 'rotate(-90deg)' : 'none', transition: 'transform .12s',
          }}>
            <Icon name="chevronDown" size={13} />
          </button>
          <input
            value={item.title}
            onChange={e => onPatch({ title: e.target.value })}
            placeholder="Раздел…"
            style={{
              flex: 1, minWidth: 0,
              border: '1px solid transparent', background: 'transparent', borderRadius: 5, padding: '2px 6px', margin: '-2px -2px',
              fontSize: 11.5, fontWeight: 600, letterSpacing: '.07em', textTransform: 'uppercase',
              color: 'var(--color-ink-500)', outline: 'none',
            }}
            onFocus={e => { e.target.style.background = 'var(--color-surface)'; e.target.style.borderColor = 'var(--color-line-strong)'; }}
            onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; }}
          />
        </div>
        {subtotal && subtotal.count > 0
          ? <span style={{ flex: '0 0 auto', fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--color-ink-400)', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{D.dur(subtotal.dur)} · {subtotal.count}</span>
          : <span />}
        <div style={{ display: 'flex', justifyContent: 'flex-end', opacity: hover ? 1 : 0 }}>
          <button title="Удалить раздел" onClick={onDelete} style={actBtn}><Icon name="trash" size={13} /></button>
        </div>
        {dragOver === 'before' && <DropLine pos="top" />}
        {dragOver === 'after' && <DropLine pos="bottom" />}
      </div>
    );
  }

  /* ============ Разделитель дня ============ */
  function DayRow({ item, onPatch, onDelete, onGrab, grabbed, dragOver, collapsed, onToggle, subtotal, dayNum }) {
    const [hover, setHover] = useState(false);
    const focusOn = e => { e.target.style.background = 'var(--color-surface)'; e.target.style.borderColor = 'var(--color-line-strong)'; };
    const focusOff = e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; };
    return (
      <div
        draggable={grabbed}
        onDragEnd={() => onGrab(null)}
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          position: 'relative', display: 'grid', gridTemplateColumns: '20px auto 1fr auto auto 32px', gap: 10, alignItems: 'center',
          padding: '13px 12px 13px 6px', background: 'var(--color-muted-50)',
          borderTop: '1px solid var(--color-line-strong)', borderBottom: '1px solid var(--color-line-strong)',
          opacity: grabbed ? 0.5 : 1,
        }}>
        <button onMouseDown={() => onGrab(item.id)} onMouseUp={() => onGrab(null)} title="Перетащить день" style={{
          alignSelf: 'center', width: 20, height: 24, border: 0, background: 'transparent',
          color: hover ? 'var(--color-ink-400)' : 'var(--color-ink-300)', cursor: 'grab', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="grip" size={14} />
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={onToggle} title={collapsed ? 'Развернуть' : 'Свернуть'} style={{
            width: 18, height: 18, border: 0, background: 'transparent', padding: 0, color: 'var(--color-ink-500)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transform: collapsed ? 'rotate(-90deg)' : 'none', transition: 'transform .12s',
          }}>
            <Icon name="chevronDown" size={14} />
          </button>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 'var(--radius-pill)', background: 'var(--color-accent-500)', color: '#fff', fontSize: 11, fontWeight: 600, letterSpacing: '.02em', whiteSpace: 'nowrap' }}>
            <Icon name="calendar" size={12} color="rgba(255,255,255,.85)" /> День {dayNum}
          </span>
        </div>
        <input
          value={item.date || ''}
          onChange={e => onPatch({ date: e.target.value })}
          placeholder="Дата — напр. 10 июня, пн"
          style={{ minWidth: 0, border: '1px solid transparent', background: 'transparent', borderRadius: 5, padding: '3px 6px', margin: '-3px -6px', fontSize: 13, fontWeight: 600, color: 'var(--color-ink-900)', outline: 'none' }}
          onFocus={focusOn} onBlur={focusOff}
        />
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto' }}>
          <span style={{ fontSize: 11, color: 'var(--color-ink-400)' }}>старт</span>
          <input
            value={D.fmt(item.start)}
            onChange={e => onPatch({ start: D.parse(e.target.value) })}
            style={{ width: 52, border: '1px solid var(--color-line-subtle)', background: 'var(--color-surface)', borderRadius: 'var(--radius-input)', padding: '3px 6px', fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, textAlign: 'center', color: 'var(--color-ink-900)', fontVariantNumeric: 'tabular-nums', outline: 'none' }}
          />
        </div>
        {subtotal && subtotal.count > 0
          ? <span style={{ flex: '0 0 auto', fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--color-ink-500)', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{D.dur(subtotal.dur)} · {subtotal.count}</span>
          : <span />}
        <div style={{ display: 'flex', justifyContent: 'flex-end', opacity: hover ? 1 : 0 }}>
          <button title="Удалить день" onClick={onDelete} style={actBtn}><Icon name="trash" size={13} /></button>
        </div>
        {dragOver === 'before' && <DropLine pos="top" />}
        {dragOver === 'after' && <DropLine pos="bottom" />}
      </div>
    );
  }

  /* ============ Пауза между блоками ============ */
  function GapBar({ minutes }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 12px 4px 104px', background: 'var(--color-surface)', borderBottom: '1px solid var(--color-line-subtle)' }}>
        <span style={{ flex: '0 0 auto', display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--color-ink-400)', fontStyle: 'italic' }}>
          <Icon name="clock" size={11} /> пауза {D.dur(minutes)}
        </span>
        <span style={{ flex: 1, borderTop: '1px dashed var(--color-line-strong)' }} />
      </div>
    );
  }

  window.TimingBuilderParts = { EditText, TypeSelect, TimingRow, SectionRow, DayRow, GapBar, DropLine, actBtn };
})();
