// reader.jsx — thread reading pane with AI summary, ascii-art thread spine, actions

function ActionButton({ theme, children, onClick, kbd, danger, accent }) {
  const [hover, setHover] = React.useState(false);
  const color = danger ? theme.danger : accent ? theme.accent : theme.text;
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        all: 'unset', cursor: 'pointer',
        fontFamily: theme.mono, fontSize: 11,
        padding: '5px 10px',
        color: hover ? theme.bg : color,
        background: hover ? color : 'transparent',
        border: `1px solid ${color}`,
        display: 'inline-flex', alignItems: 'center', gap: 6,
        letterSpacing: '0.02em',
        whiteSpace: 'nowrap',
        flexShrink: 0,
      }}
    >
      <span style={{ whiteSpace: 'nowrap' }}>{children}</span>
      {kbd && (
        <span style={{
          fontSize: 9, opacity: 0.6,
          padding: '1px 4px',
          border: `1px solid ${hover ? theme.bg : color}`,
        }}>{kbd}</span>
      )}
    </button>
  );
}

function AISummary({ theme, summary }) {
  if (!summary || summary.length === 0) return null;
  const [open, setOpen] = React.useState(true);
  return (
    <div style={{
      margin: '0 0 18px',
      border: `1px solid ${theme.border}`,
      background: theme.bg2,
      fontFamily: theme.mono,
    }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          all: 'unset', cursor: 'pointer',
          width: '100%', boxSizing: 'border-box',
          padding: '8px 12px',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 10, color: theme.textDim,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          borderBottom: open ? `1px solid ${theme.border}` : 'none',
        }}
      >
        <span style={{ color: theme.accent, fontSize: 12 }}>※</span>
        <span>summary · ai</span>
        <span style={{ flex: 1 }} />
        <span style={{ color: theme.textFaint }}>{open ? '−' : '+'}</span>
      </button>
      {open && (
        <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 4 }}>
          {summary.map((line, i) => (
            <div key={i} style={{
              fontSize: 12, color: theme.text,
              display: 'flex', gap: 8,
              lineHeight: 1.5,
              minHeight: '1.5em',
            }}>
              <span style={{ color: theme.accent, flexShrink: 0, lineHeight: 1.5 }}>&gt;</span>
              <span style={{ lineHeight: 1.5 }}>{line}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MessageBlock({ theme, message, index, total, expanded, onToggle, depth }) {
  // ascii-art thread spine
  const spine = total === 1 ? '' : index === 0 ? '┌' : index === total - 1 ? '└' : '├';
  const isLast = index === total - 1;

  return (
    <div style={{
      display: 'flex', gap: 0,
      borderBottom: isLast ? 'none' : `1px solid ${theme.border}`,
    }}>
      {/* spine column */}
      {total > 1 && (
        <div style={{
          width: 20, flexShrink: 0,
          display: 'flex', flexDirection: 'column',
          alignItems: 'center',
          fontFamily: theme.mono, fontSize: 12,
          color: theme.textFaint,
          paddingTop: 10,
        }}>
          <span>{spine}</span>
          {!isLast && (
            <div style={{ flex: 1, width: 1, background: theme.border }} />
          )}
        </div>
      )}

      <div style={{ flex: 1, minWidth: 0, padding: '12px 16px' }}>
        {/* header */}
        <button
          onClick={onToggle}
          style={{
            all: 'unset', cursor: 'pointer',
            width: '100%', boxSizing: 'border-box',
            display: 'flex', alignItems: 'baseline', gap: 10,
            fontFamily: theme.mono,
            minHeight: 20,
            lineHeight: 1.4,
          }}
        >
          <span style={{
            fontSize: 12, fontWeight: 600, color: theme.text,
            whiteSpace: 'nowrap', flexShrink: 0,
          }}>{message.from}</span>
          <span style={{
            fontSize: 11, color: theme.textFaint,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            minWidth: 0, flex: '0 1 auto',
          }}>&lt;{message.fromEmail}&gt;</span>
          <span style={{ flex: 1 }} />
          <span style={{
            fontSize: 11, color: theme.textFaint,
            fontVariantNumeric: 'tabular-nums',
            whiteSpace: 'nowrap', flexShrink: 0,
          }}>{message.date} · {message.time}</span>
          <span style={{
            fontSize: 10, color: theme.textFaint,
            padding: '0 4px',
          }}>{expanded ? '−' : '+'}</span>
        </button>

        {/* to line when expanded */}
        {expanded && (
          <div style={{
            fontFamily: theme.mono, fontSize: 10,
            color: theme.textFaint, marginTop: 4,
          }}>
            to: {message.to}
          </div>
        )}

        {/* body */}
        {expanded ? (
          <div style={{
            marginTop: 12,
            fontFamily: theme.mono, fontSize: 13, lineHeight: 1.6,
            color: theme.text,
            whiteSpace: 'pre-wrap',
          }}>
            {message.body.map((line, i) => (
              <div key={i} style={{ minHeight: line === '' ? '1em' : 'auto' }}>
                {line}
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            marginTop: 4,
            fontFamily: theme.mono, fontSize: 12,
            color: theme.textDim,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {message.body.find(l => l) || ''}
          </div>
        )}
      </div>
    </div>
  );
}

function Reader({ theme, thread, accounts, labels, aiSummary, onArchive, onDelete, onStar, onReply, onReplyAll, onForward }) {
  // thread state: latest msg expanded by default
  const [expanded, setExpanded] = React.useState(() => {
    if (!thread) return {};
    const last = thread.messages.length - 1;
    return { [last]: true };
  });

  React.useEffect(() => {
    if (!thread) return;
    const last = thread.messages.length - 1;
    setExpanded({ [last]: true });
  }, [thread?.id]);

  if (!thread) {
    return (
      <div style={{
        flex: 1, background: theme.bgInset,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: theme.mono, color: theme.textFaint, fontSize: 12,
        paddingTop: 32,
      }}>
        // select a message
      </div>
    );
  }

  const account = accounts.find(a => a.id === thread.account);
  const threadLabels = thread.labels.map(id => labels.find(l => l.id === id)).filter(Boolean);

  return (
    <div style={{
      flex: 1, background: theme.bgInset, minWidth: 0,
      display: 'flex', flexDirection: 'column',
      paddingTop: 32, // traffic lights clearance
    }}>
      {/* header: subject + metadata */}
      <div style={{
        borderBottom: `1px solid ${theme.border}`,
        padding: '14px 20px 12px',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          fontFamily: theme.mono, fontSize: 10,
          color: theme.textFaint, marginBottom: 8,
          letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>
          <span style={{
            color: `oklch(0.72 0.14 ${account.hue})`,
          }}>▪</span>
          <span>{account.email}</span>
          <span style={{ color: theme.border2 }}>/</span>
          <span>{thread.folder}</span>
          <span style={{ flex: 1 }} />
          <span>{thread.messages.length} msg{thread.messages.length !== 1 ? 's' : ''}</span>
        </div>
        <div style={{
          fontFamily: theme.mono, fontSize: 18, fontWeight: 600,
          color: theme.text,
          lineHeight: 1.3,
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          {thread.starred && <span style={{ color: theme.accent2, fontSize: 16 }}>★</span>}
          <span style={{ flex: 1 }}>{thread.subject}</span>
        </div>
        {threadLabels.length > 0 && (
          <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
            {threadLabels.map(l => <LabelTag key={l.id} theme={theme} label={l} />)}
          </div>
        )}
      </div>

      {/* action bar */}
      <div style={{
        padding: '10px 20px',
        borderBottom: `1px solid ${theme.border}`,
        display: 'flex', gap: 6, flexWrap: 'wrap',
      }}>
        <ActionButton theme={theme} onClick={onReply} kbd="R" accent>reply</ActionButton>
        <ActionButton theme={theme} onClick={onReplyAll} kbd="A">reply all</ActionButton>
        <ActionButton theme={theme} onClick={onForward} kbd="F">fwd</ActionButton>
        <div style={{ width: 1, background: theme.border, margin: '0 4px' }} />
        <ActionButton theme={theme} onClick={onArchive} kbd="E">archive</ActionButton>
        <ActionButton theme={theme} onClick={onStar} kbd="S">
          {thread.starred ? 'unstar' : 'star'}
        </ActionButton>
        <ActionButton theme={theme} onClick={onDelete} kbd="⌫" danger>delete</ActionButton>
      </div>

      {/* body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px 40px' }}>
        <AISummary theme={theme} summary={aiSummary} />

        <div style={{
          border: `1px solid ${theme.border}`,
          background: theme.bg,
        }}>
          {thread.messages.map((m, i) => (
            <MessageBlock
              key={i}
              theme={theme}
              message={m}
              index={i}
              total={thread.messages.length}
              expanded={!!expanded[i]}
              onToggle={() => setExpanded({ ...expanded, [i]: !expanded[i] })}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Reader, ActionButton, AISummary });
