// ChangeTooltip.jsx — the §8.10 hover affordance for a tracked-change
// span. Extracted from DiffView in Phase 3 so the MarkdownPreview
// tracked-changes overlay can reuse it. Same shape: badge row,
// user-prompt + selection-quote, and the AI's reason.

import { MODEL_STYLES } from '../modelStyles'

function tooltipStyle(x, y) {
  const vw = window.innerWidth, vh = window.innerHeight
  const style = {}
  if (x > vw * 0.55) style.right = vw - x + 10
  else style.left = x + 14
  if (y > vh * 0.55) style.bottom = vh - y + 10
  else style.top = y + 14
  return style
}

export function changeContext(change, messages) {
  if (!change?.source_message_id || !messages) return {}
  const idx = messages.findIndex(m => m.id === change.source_message_id)
  if (idx < 0) return {}
  const assistant = messages[idx]
  const userMsg = [...messages].slice(0, idx).reverse().find(m => m.role === 'user')
  return { assistant, userMsg }
}

export default function ChangeTooltip({ change, messages, position }) {
  const { assistant, userMsg } = changeContext(change, messages)
  const style = { ...tooltipStyle(position.x, position.y), position: 'fixed' }
  const modelStyle = MODEL_STYLES[assistant?.model_id] || MODEL_STYLES.default

  return (
    <div className="diff-tooltip" style={style}>
      <div className="diff-tooltip-header">
        {change.kind === 'ai' ? (
          <span className="diff-tooltip-badge" style={{ background: modelStyle.bg, color: modelStyle.color }}>
            {modelStyle.label}
          </span>
        ) : (
          <span className="diff-tooltip-badge diff-tooltip-badge--manual">Manual edit</span>
        )}
        {change.was_edited_before_accept && (
          <span className="diff-tooltip-badge diff-tooltip-badge--edited">Edited before accept</span>
        )}
      </div>
      {userMsg && (
        <div className="diff-tooltip-prompt">
          {userMsg.quote && (
            <div className="diff-tooltip-quote">
              "{userMsg.quote.length > 120 ? userMsg.quote.slice(0, 120) + '…' : userMsg.quote}"
            </div>
          )}
          <div className="diff-tooltip-prompt-text">
            {userMsg.text.length > 240 ? userMsg.text.slice(0, 240) + '…' : userMsg.text}
          </div>
        </div>
      )}
      {change.reason && (
        <div className="diff-tooltip-reason">
          <span className="diff-tooltip-reason-label">Reason</span>
          {change.reason}
        </div>
      )}
      {!userMsg && change.kind === 'ai' && (
        <div className="diff-tooltip-no-context">
          No linked conversation message in this session.
        </div>
      )}
    </div>
  )
}
