/* global React, window */
// ─────────────────────────────────────────────────────────────
// ThinkingTrace + TraceStep + PullChip
// Lifted from ref/mastermind-v2/components/response-ui.jsx:50–215
//
// B1 fixes applied (vs v2 source):
//   • Chip node: fixed 24px slot, centered, NO white ring, NO stroke
//     (v2 passed `boxShadow: 'none'` at the call-site — now built-in).
//   • Left padding of step body: 44px from edge (was 38 + 6-fudge marginLeft);
//     chip sits at left:12, slot width 24, gap 8 → hard 44px text baseline.
//   • Removed the marginLeft:6 hack from the name label.
//   • First/last padding simplified: every step uses the same rhythm (paddingY 10),
//     first/last just trim the outer edge to hug the rail endcaps.
//   • Kind pill: moved to a "tag" with its own baseline, no verticalAlign:1px fudge.
//   • Added `defaultOpen` prop honoring + `prefers-reduced-motion` for the chevron.
//   • Added `OpenByDefault` helper for playgrounds and a `compact` density.
//   • Exported TraceStep + PullChip so they can be composed headlessly.
// ─────────────────────────────────────────────────────────────

const TT_FONT = '"Inter", -apple-system, BlinkMacSystemFont, sans-serif';

// ── icons (local, tiny) ────────────────────────────────────
const TTIcon = {
  chev: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="6 9 12 15 18 9" />
    </svg>
  ),
  think: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9.5 2a6.5 6.5 0 00-4.6 11.1A5 5 0 008 22a5 5 0 005-5v-3M15 14h3a3 3 0 000-6h-.5"/>
      <path d="M13 9l2-2M11 13l-2-2"/>
    </svg>
  ),
  web: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/>
      <path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/>
    </svg>
  ),
  file: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z"/>
      <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/>
    </svg>
  ),
  memory: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 3v2M15 3v2M9 19v2M15 19v2M3 9h2M3 15h2M19 9h2M19 15h2"/>
      <rect x="7" y="7" width="10" height="10" rx="2"/>
    </svg>
  ),
  tool: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"/>
    </svg>
  ),
  book: () => (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 19.5A2.5 2.5 0 016.5 17H20V2H6.5A2.5 2.5 0 004 4.5v15zM4 19.5A2.5 2.5 0 006.5 22H20v-5H6.5A2.5 2.5 0 004 19.5z"/>
    </svg>
  ),
};

function knowledgeIcon(kind) {
  if (kind === 'web')    return <TTIcon.web />;
  if (kind === 'doc')    return <TTIcon.file />;
  if (kind === 'memory') return <TTIcon.memory />;
  if (kind === 'tool')   return <TTIcon.tool />;
  return <TTIcon.book />;
}

// Design tokens — hoisted as constants so they are tweak-friendly.
const TT_TOKENS = {
  chipSlot: 24,          // outer reserved square for the model chip
  chipSize: 18,          // visual chip diameter
  railGutter: 8,         // space between chip slot and text baseline
  stepPadY: 10,          // vertical step rhythm
  firstTrim: 4,          // trim top of first step to hug rail endcap
  lastTrim: 4,           // trim bottom of last step
};

// ─────────────────────────────────────────────────────────────
// ThinkingTrace — collapsible stepped reasoning
// ─────────────────────────────────────────────────────────────
function ThinkingTrace({
  trace,
  defaultOpen = false,
  elapsed = null,
  compact = false,
  MODELS_BY_ID,
  ModelChip,
}) {
  const [open, setOpen] = React.useState(defaultOpen);

  // Fall back to the globals if consumer hasn't wired them in.
  MODELS_BY_ID = MODELS_BY_ID || window.MODELS_BY_ID;
  ModelChip    = ModelChip    || window.ModelChip;

  if (!trace || !trace.length) return null;
  const totalMinds = new Set(trace.map(s => s.modelId)).size;
  const totalTools = trace.reduce((n, s) => n + (s.pulls?.length || 0), 0);

  const padY = compact ? 6 : 9;
  const padX = compact ? 10 : 12;

  return (
    <div style={{
      marginBottom: 14,
      borderRadius: 10,
      border: '1px solid rgba(0,0,0,0.07)',
      background: open
        ? 'linear-gradient(180deg, rgba(255,245,252,0.55), rgba(255,255,255,0.4))'
        : 'rgba(255,255,255,0.55)',
      overflow: 'hidden',
      backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)',
      transition: 'background 200ms ease',
    }}>
      {/* Header */}
      <button
        onClick={() => setOpen(v => !v)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          width: '100%', padding: `${padY}px ${padX}px`,
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: TT_FONT, fontSize: 12, textAlign: 'left',
          color: 'rgba(0,0,0,0.72)',
        }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 20, height: 20, borderRadius: 5,
          background: 'rgba(255, 45, 180, 0.08)',
          color: '#C01A7E',
        }}>
          <TTIcon.think />
        </span>
        <span style={{ fontWeight: 600, color: 'rgba(0,0,0,0.85)' }}>Reasoning</span>
        <span style={{ color: 'rgba(0,0,0,0.4)', fontSize: 11.5 }}>
          {trace.length} step{trace.length===1?'':'s'} · {totalMinds} mind{totalMinds===1?'':'s'}
          {totalTools ? ` · ${totalTools} pull${totalTools===1?'':'s'}` : ''}
        </span>
        {elapsed != null && (
          <span style={{ color: 'rgba(0,0,0,0.35)', fontSize: 11 }}>· {elapsed}</span>
        )}
        <span style={{ flex: 1 }} />
        {/* Stacked chips preview (collapsed only) */}
        {!open && ModelChip && (
          <div style={{ display: 'flex', marginRight: 4 }}>
            {[...new Set(trace.map(s => s.modelId))].slice(0, 5).map((id, i) => (
              <div key={id} style={{
                marginLeft: i === 0 ? 0 : -5,
                boxShadow: '0 0 0 1.5px #fff',
                borderRadius: '50%',
              }}>
                <ModelChip model={id} size={14} />
              </div>
            ))}
          </div>
        )}
        <span style={{
          transition: 'transform 180ms', display: 'inline-flex',
          transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          color: 'rgba(0,0,0,0.4)',
        }}><TTIcon.chev /></span>
      </button>

      {/* Steps */}
      {open && (
        <div style={{ padding: `0 ${padX}px ${padY}px`, position: 'relative' }}>
          {/* vertical rail — x = chipSlot/2 + padX = 12 + 12 = 24 */}
          <div style={{
            position: 'absolute',
            left: padX + TT_TOKENS.chipSlot / 2,
            top: TT_TOKENS.firstTrim + 10,
            bottom: TT_TOKENS.lastTrim + 6,
            width: 2, borderRadius: 1,
            transform: 'translateX(-1px)',
            background: 'linear-gradient(180deg, rgba(255,45,180,0.22), rgba(155,92,255,0.16) 50%, rgba(0,212,255,0.18))',
          }} />
          {trace.map((step, i) => (
            <TraceStep key={i}
                       step={step}
                       first={i === 0}
                       last={i === trace.length - 1}
                       compact={compact}
                       MODELS_BY_ID={MODELS_BY_ID}
                       ModelChip={ModelChip} />
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TraceStep — one step in the rail
// ─────────────────────────────────────────────────────────────
function TraceStep({ step, first, last, compact = false, MODELS_BY_ID, ModelChip }) {
  MODELS_BY_ID = MODELS_BY_ID || window.MODELS_BY_ID;
  ModelChip    = ModelChip    || window.ModelChip;
  const m = MODELS_BY_ID?.[step.modelId] || { name: step.modelId, color: '#888' };

  const { chipSlot, chipSize, railGutter, stepPadY, firstTrim, lastTrim } = TT_TOKENS;
  const paddingLeft = chipSlot + railGutter;        // 24 + 8 = 32 → text column
  const fontSize = compact ? 12 : 12.5;

  return (
    <div style={{
      position: 'relative',
      paddingLeft,
      paddingTop:    first ? firstTrim : stepPadY,
      paddingBottom: last  ? lastTrim  : stepPadY,
      fontFamily: TT_FONT,
    }}>
      {/* chip node — centered in the reserved slot, no ring, no stroke */}
      <div style={{
        position: 'absolute',
        left: 0,
        top: (first ? firstTrim : stepPadY) + 1,
        width: chipSlot, height: chipSlot,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: '#fff',                // occludes the rail behind
        borderRadius: '50%',
      }}>
        {ModelChip
          ? <ModelChip model={m} size={chipSize} style={{ boxShadow: 'none' }} />
          : <div style={{
              width: chipSize, height: chipSize, borderRadius: '50%', background: m.color,
            }} />
        }
      </div>

      {/* body */}
      <div style={{ fontSize, color: 'rgba(0,0,0,0.78)', lineHeight: 1.55 }}>
        <span style={{ fontWeight: 600, color: m.color, marginRight: 8 }}>
          {m.name}
        </span>
        {step.kind && (
          <span style={{
            display: 'inline-block',
            padding: '1px 6px',
            marginRight: 8,
            borderRadius: 3,
            fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase',
            background: 'rgba(0,0,0,0.05)', color: 'rgba(0,0,0,0.55)',
          }}>{step.kind}</span>
        )}
        {step.text}
      </div>

      {/* tool / knowledge pulls */}
      {step.pulls?.length > 0 && (
        <div style={{ display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
          {step.pulls.map((p, i) => <PullChip key={i} pull={p} />)}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PullChip — one tool / knowledge pull under a step
// ─────────────────────────────────────────────────────────────
function PullChip({ pull }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '3px 8px 3px 6px', borderRadius: 6,
      background: '#fff', border: '1px solid rgba(0,0,0,0.08)',
      fontFamily: TT_FONT, fontSize: 11, color: 'rgba(0,0,0,0.7)',
      cursor: 'pointer',
      maxWidth: 380,
    }} title={pull.meta || ''}>
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 16, height: 16, borderRadius: 4,
        background: pull.kind === 'web'    ? 'rgba(0, 212, 255, 0.12)'
                  : pull.kind === 'doc'    ? 'rgba(255, 45, 180, 0.10)'
                  : pull.kind === 'memory' ? 'rgba(155, 92, 255, 0.10)'
                  : 'rgba(0,0,0,0.05)',
        color:      pull.kind === 'web'    ? '#0088C8'
                  : pull.kind === 'doc'    ? '#C01A7E'
                  : pull.kind === 'memory' ? '#6A3BD2'
                  : 'rgba(0,0,0,0.6)',
      }}>
        {knowledgeIcon(pull.kind)}
      </span>
      <span style={{
        fontWeight: 500, whiteSpace: 'nowrap',
        overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 220,
      }}>{pull.title}</span>
      {pull.meta && (
        <span style={{ fontSize: 10.5, color: 'rgba(0,0,0,0.4)' }}>{pull.meta}</span>
      )}
    </div>
  );
}

// Exports
Object.assign(window, { ThinkingTrace, TraceStep, PullChip });
