// Loop — AI Action Queue + swipe-to-action + Editor modal.
// Exports (window): QueueScreen, EditorScreen

const { useState: qState, useRef: qRef, useEffect: qEffect } = React;

// Mail-style row with swipe-to-action via touch/pointer drag.
function QueueRow({ T, c, person, onOpen, onApprove, onSnooze, onArchive }) {
  const [dx, setDx] = qState(0);
  const [dragging, setDragging] = qState(false);
  const startX = qRef(0);
  const moved = qRef(false);

  const onPointerDown = e => {
    startX.current = e.clientX;
    moved.current = false;
    setDragging(true);
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch(_) {}
  };
  const onPointerMove = e => {
    if (!dragging) return;
    const d = e.clientX - startX.current;
    if (Math.abs(d) > 4) moved.current = true;
    setDx(Math.max(-180, Math.min(180, d)));
  };
  const onPointerUp = () => {
    setDragging(false);
    if (dx > 110) { onApprove(c.id); setDx(360); setTimeout(() => setDx(0), 0); return; }
    if (dx < -110) { onArchive(c.id); setDx(-360); setTimeout(() => setDx(0), 0); return; }
    setDx(0);
  };

  const rightHint = dx > 0;
  const leftHint = dx < 0;

  return (
    <div style={{ position: 'relative', marginBottom: 10, borderRadius: T.radius, overflow: 'hidden' }}>
      {/* underlay */}
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        background: rightHint ? T.cleared : (leftHint ? (T.dark ? '#2A1F1F' : '#EFE3E0') : 'transparent'),
        alignItems: 'center', padding: '0 22px', justifyContent: rightHint ? 'flex-start' : 'flex-end',
        color: rightHint ? '#fff' : (T.dark ? '#fff' : '#7A4A40'),
        fontFamily: T.fontSans, fontSize: 14, fontWeight: 580, gap: 8,
      }}>
        {rightHint && <><KindGlyph kind="approve" color="#fff" size={18}/>Approve & send</>}
        {leftHint && <>Archive<KindGlyph kind="reply" color={T.dark ? '#fff' : '#7A4A40'} size={16}/></>}
      </div>
      <div
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={() => { setDragging(false); setDx(0); }}
        onClick={(e) => { if (!moved.current) onOpen(c.id); }}
        style={{
          position: 'relative',
          background: T.card,
          border: `0.5px solid ${T.cardEdge}`,
          borderRadius: T.radius,
          padding: T.pad,
          transform: `translateX(${dx}px)`,
          transition: dragging ? 'none' : 'transform 320ms cubic-bezier(.2,.8,.2,1)',
          boxShadow: T.cardShadow,
          cursor: 'pointer', touchAction: 'pan-y',
        }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
          <Avatar p={person} size={36} dark={T.dark} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontFamily: T.fontSans, fontSize: 15, fontWeight: 570, color: T.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{person.name}</span>
              <span style={{ fontFamily: T.fontSans, fontSize: 12, color: T.textMuted }}>· {c.received}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
              <KindGlyph kind={c.kind} color={T.accent} size={11} />
              <span style={{ fontFamily: T.fontSans, fontSize: 12, fontWeight: 540, color: T.accent }}>{c.kindLabel}</span>
              <span style={{ fontFamily: T.fontSans, fontSize: 12, color: T.textMuted }}>· ~{c.minutes} min</span>
            </div>
          </div>
        </div>
        <div style={{ fontFamily: T.fontSerif, fontSize: 15.5, lineHeight: 1.4, color: T.text, marginBottom: 8 }}>{c.preview}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <ShimmerDot T={T} />
          <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.textSub, lineHeight: 1.45, flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {c.suggested}
          </div>
        </div>
      </div>
    </div>
  );
}

function QueueScreen({ T, queue, cleared, openItem, approve, archive, snooze }) {
  const [filter, setFilter] = qState('all');
  const filters = [
    { id: 'all',      label: 'All' },
    { id: 'reply',    label: 'Replies' },
    { id: 'schedule', label: 'Schedule' },
    { id: 'thanks',   label: 'Thanks' },
    { id: 'followup', label: 'Follow-ups' },
  ];
  const shown = queue.filter(q => filter === 'all' || q.kind === filter);
  const elapsedMin = Math.round(shown.reduce((a, b) => a + b.minutes, 0));

  return (
    <ScreenScroll T={T}>
      <div style={{ padding: '8px 20px 0' }}>
        <div style={{ fontFamily: T.fontSans, fontSize: 13, fontWeight: 540, color: T.textSub, letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 6 }}>
          Action Queue
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
          <span style={{ fontFamily: T.fontSerif, fontSize: 36, color: T.text, letterSpacing: -0.9, fontWeight: 400 }}>{queue.length}</span>
          <span style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textSub }}>loops · ~{elapsedMin} min total</span>
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textMuted, marginBottom: 16 }}>
          Swipe right to approve · left to archive
        </div>

        {/* Filters */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 18, overflowX: 'auto', paddingBottom: 4, scrollbarWidth: 'none' }}>
          {filters.map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              all: 'unset', cursor: 'pointer', padding: '7px 14px', borderRadius: 999,
              background: filter === f.id ? T.accent : T.card,
              color: filter === f.id ? '#fff' : T.text,
              border: `0.5px solid ${filter === f.id ? T.accent : T.cardEdge}`,
              fontFamily: T.fontSans, fontSize: 13, fontWeight: 540,
              whiteSpace: 'nowrap', flexShrink: 0,
            }}>{f.label}</button>
          ))}
        </div>

        {shown.map(c => {
          const p = window.LoopData.PEOPLE.find(x => x.id === c.personId);
          return <QueueRow key={c.id} T={T} c={c} person={p}
            onOpen={openItem} onApprove={approve} onSnooze={snooze} onArchive={archive} />;
        })}

        {shown.length === 0 && (
          <div style={{
            padding: '60px 20px', textAlign: 'center',
            border: `1px dashed ${T.hairline}`, borderRadius: T.radius,
          }}>
            <div style={{ fontFamily: T.fontSerif, fontSize: 22, color: T.text, marginBottom: 6 }}>All clear here.</div>
            <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textSub }}>Nothing in this filter.</div>
          </div>
        )}

        {/* Cleared today */}
        {cleared > 0 && (
          <div style={{ marginTop: 24, padding: 16, borderRadius: T.radiusSm, background: T.dark ? 'rgba(62,142,111,0.12)' : 'rgba(62,142,111,0.08)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <KindGlyph kind="approve" color={T.cleared} size={18}/>
            <span style={{ fontFamily: T.fontSans, fontSize: 14, color: T.text, fontWeight: 540 }}>{cleared} cleared today</span>
          </div>
        )}
      </div>
    </ScreenScroll>
  );
}

// ─── Editor / Approval ───────────────────────────────────────────
function EditorScreen({ T, item, person, onBack, onSend, onSnooze, onArchive }) {
  const [text, setText] = qState(item.suggested);
  const [showWhy, setShowWhy] = qState(false);
  const conf = Math.round(item.confidence * 100);

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg, display: 'flex', flexDirection: 'column' }}>
      <BackHeader T={T} title="Queue" onBack={onBack}
        trailing={
          <button onClick={onArchive} style={{ all: 'unset', cursor: 'pointer', fontFamily: T.fontSans, fontSize: 15, color: T.textSub }}>Archive</button>
        }
      />
      <div style={{ flex: 1, overflow: 'auto', padding: '0 20px 20px' }}>
        {/* sender + context */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 4, marginBottom: 16 }}>
          <Avatar p={person} size={52} dark={T.dark} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: T.fontSans, fontSize: 18, fontWeight: 580, color: T.text }}>{person.name}</div>
            <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.textSub }}>{person.org}</div>
          </div>
          <Pill dark={T.dark} color={T.accent} soft={T.accentSoft}>
            <KindGlyph kind={item.kind} color={T.accent} size={11} />{item.kindLabel}
          </Pill>
        </div>

        {/* original */}
        <div style={{ fontFamily: T.fontSans, fontSize: 11, fontWeight: 580, color: T.textMuted, letterSpacing: 1.3, textTransform: 'uppercase', marginBottom: 8 }}>
          They wrote · {item.received}
        </div>
        <div style={{
          background: T.dark ? 'rgba(255,255,255,0.04)' : 'rgba(20,20,20,0.035)',
          borderRadius: 14, padding: '14px 16px', marginBottom: 22,
          fontFamily: T.fontSerif, fontSize: 16.5, lineHeight: 1.45, color: T.text,
        }}>{item.preview}</div>

        {/* draft */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <ShimmerDot T={T} />
          <div style={{ fontFamily: T.fontSans, fontSize: 11, fontWeight: 580, color: T.accent, letterSpacing: 1.3, textTransform: 'uppercase' }}>
            Drafted in your voice
          </div>
          <span style={{ flex: 1 }} />
          <span style={{ fontFamily: T.fontSans, fontSize: 12, color: T.textMuted }}>{conf}% confidence</span>
        </div>
        <textarea
          value={text}
          onChange={e => setText(e.target.value)}
          rows={5}
          style={{
            width: '100%', boxSizing: 'border-box',
            background: T.card, border: `0.5px solid ${T.cardEdge}`,
            borderRadius: 18, padding: 16, resize: 'none',
            fontFamily: T.fontSerif, fontSize: 17, lineHeight: 1.45, color: T.text,
            outline: 'none', boxShadow: T.cardShadow,
          }}
        />

        {/* Why this */}
        <button onClick={() => setShowWhy(!showWhy)} style={{
          all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
          fontFamily: T.fontSans, fontSize: 13, color: T.accent, marginTop: 14, fontWeight: 540,
        }}>
          {showWhy ? '⌃' : '⌄'} Why Loop suggested this
        </button>
        {showWhy && (
          <div style={{
            marginTop: 10, padding: 14, borderRadius: 14,
            background: T.dark ? 'rgba(255,255,255,0.03)' : 'rgba(20,20,20,0.02)',
            border: `0.5px solid ${T.cardEdge}`,
          }}>
            <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textSub, lineHeight: 1.5 }}>{item.why}</div>
            <div style={{ display: 'flex', gap: 14, marginTop: 10 }}>
              <div>
                <div style={{ fontFamily: T.fontSans, fontSize: 11, color: T.textMuted, letterSpacing: 0.6, textTransform: 'uppercase' }}>Channel</div>
                <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.text, marginTop: 2 }}>{item.channel}</div>
              </div>
              <div>
                <div style={{ fontFamily: T.fontSans, fontSize: 11, color: T.textMuted, letterSpacing: 0.6, textTransform: 'uppercase' }}>Cadence</div>
                <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.text, marginTop: 2 }}>Weekly</div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* action bar */}
      <div style={{
        padding: '12px 16px 20px',
        background: T.bg,
        borderTop: `0.5px solid ${T.hairline}`,
        display: 'flex', gap: 10, alignItems: 'center',
      }}>
        <button onClick={onSnooze} style={{
          all: 'unset', cursor: 'pointer', padding: '14px 16px', borderRadius: 14,
          background: T.card, border: `0.5px solid ${T.cardEdge}`,
          fontFamily: T.fontSans, fontSize: 15, fontWeight: 540, color: T.text,
        }}>Snooze</button>
        <button onClick={() => onSend(text)} style={{
          all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center', padding: '14px 16px', borderRadius: 14,
          background: T.accent, color: '#fff',
          fontFamily: T.fontSans, fontSize: 15, fontWeight: 590, letterSpacing: -0.2,
          boxShadow: `0 6px 16px ${T.accent}40`,
        }}>Approve & send</button>
      </div>
    </div>
  );
}

window.QueueScreen = QueueScreen;
window.EditorScreen = EditorScreen;
