// v2 IDEATE stage — parallel chat sessions + presets + saved seeds

// Detect structured patterns in AI replies based on preset hint + heuristics.
// Returns { kind: 'taglines' | 'ladder' | 'reasoning' | 'text', data: ... }
const parseAIReply = (text, presetKey) => {
  if (!text) return {kind: 'text', data: null};
  const lines = text.split('\n').map(l => l.trim()).filter(Boolean);

  // Taglines: lines like "1. KO COPY (en copy)" or "1) ..." — extract pairs
  if (presetKey === 'tagline' || /^\s*\d+[\.\)]/.test(lines[0])) {
    const items = [];
    for (const ln of lines) {
      const m = ln.match(/^\s*(\d+|\d+[a-z]?)[\.\):]\s*(.+)$/);
      if (!m) continue;
      const body = m[2];
      const enMatch = body.match(/^(.+?)\s*[—\-/·]\s*([A-Za-z][^—\-/·]+)$/) ||
                      body.match(/^(.+?)\s*\(([^)]+)\)\s*$/);
      if (enMatch) items.push({n: m[1], ko: enMatch[1].trim().replace(/['"]/g,''), en: enMatch[2].trim().replace(/['"]/g,'')});
      else items.push({n: m[1], ko: body.replace(/['"]/g,''), en: ''});
    }
    if (items.length >= 2) return {kind: 'taglines', data: {items}};
  }

  // Ladder: 5 tier labels in order (LITERAL/SENSORY/EMOTION/UNIVERSAL/METAPHOR)
  const TIERS = ['LITERAL','SENSORY','EMOTION','UNIVERSAL','METAPHOR'];
  const ladder = [];
  let txtRest = text;
  for (const tier of TIERS) {
    const re = new RegExp(`(?:^|\\n)\\s*\\*?\\*?(?:${tier}|${tier.toLowerCase()})\\*?\\*?[:\\s—\\-]+(.+?)(?=(?:\\n\\s*\\*?\\*?(?:${TIERS.join('|')}|${TIERS.map(t=>t.toLowerCase()).join('|')})\\*?\\*?[:\\s—\\-])|$)`, 'is');
    const m = txtRest.match(re);
    if (m) {
      const body = m[1].trim().replace(/^["']|["']$/g, '');
      const enMatch = body.match(/^(.+?)\s*\(([^)]+)\)\s*$/);
      if (enMatch) ladder.push({type: tier, copy: enMatch[1].trim(), en: enMatch[2].trim()});
      else ladder.push({type: tier, copy: body, en: ''});
    }
  }
  if (presetKey === 'ladder' || ladder.length >= 4) {
    return {kind: 'ladder', data: {items: ladder}};
  }

  // Reasoning: paragraph + bullet followups (lines starting with -/•/·)
  const followups = lines
    .filter(l => /^[-•·]\s+/.test(l))
    .map(l => l.replace(/^[-•·]\s+/, ''))
    .map(l => {
      const m = l.match(/^(.+?)\s*[—\-]\s*([A-Za-z].+)$/) || l.match(/^(.+?)\s*\(([^)]+)\)\s*$/);
      return m ? {ko: m[1].trim(), en: m[2].trim()} : {ko: l, en: ''};
    });
  if (followups.length >= 2) {
    const para = lines.filter(l => !/^[-•·]\s+/.test(l) && !/^\s*\d+[\.\)]/.test(l)).join(' ');
    return {kind: 'reasoning', data: {text: para || text.slice(0, 240), followups}};
  }

  return {kind: 'text', data: null};
};

const V2IdeateStage = ({palette, projectId, pinnedIds}) => {
  // Build keyword index
  const map = {};
  (palette.blocks || []).forEach(b => (b.keywords || []).forEach(k => map[k.id] = {...k, blockId: b.id, fileId: b.file}));
  const allPinned = pinnedIds.map(id => map[id]).filter(Boolean);

  const [sessions, setSessions] = React.useState(() => [
    {
      id: 's1', title: 'New chat',
      context: pinnedIds.slice(0, 4),
      messages: [],
    },
  ]);
  const [activeId, setActiveId] = React.useState('s1');
  const [savedSeeds, setSavedSeeds] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [thinking, setThinking] = React.useState(false);
  const active = sessions.find(s => s.id === activeId) || sessions[0];

  const presets = [
    {key:'combine',  label:'Combine',       sub:'결합'},
    {key:'twist',    label:'Twist',         sub:'클리셰 우회'},
    {key:'ladder',   label:'Ladder',        sub:'5층위'},
    {key:'tagline',  label:'Tagline',       sub:'7단어 헤드라인'},
    {key:'audience', label:'Audience swap', sub:'톤 이동'},
    {key:'why',      label:'Why this?',     sub:'근거 설명'},
  ];

  const newSession = () => {
    const id = 's' + (sessions.length + 1) + '_' + Math.floor(Math.random()*999);
    const next = {id, title: 'New chat', context: pinnedIds.slice(0, 4), messages: []};
    setSessions([...sessions, next]);
    setActiveId(id);
  };
  const removeContext = (kid) => {
    setSessions(sessions.map(s => s.id === activeId ? {...s, context: s.context.filter(c => c !== kid)} : s));
  };
  const addContext = (kid) => {
    setSessions(sessions.map(s => s.id === activeId ? {...s, context: [...new Set([...s.context, kid])]} : s));
  };

  const presetText = (key) => ({
    combine:  '핀된 키워드 두세 개를 결합한 새로운 표현 5개를 만들어줘.',
    twist:    '뻔한 광고 클리셰를 비껴가는 비틀어진 카피 3개를 만들어줘.',
    ladder:   '핀된 첫 번째 키워드로 LITERAL → SENSORY → EMOTION → UNIVERSAL → METAPHOR 5층위 카피 사다리를 만들어줘.',
    tagline:  '7단어 이내의 헤드라인 5종을 한국어와 영어로 각각 만들어줘.',
    audience: '현재 타깃을 다른 연령/성별로 옮겼을 때 카피의 어휘와 톤이 어떻게 변해야 하는지 분석해줘.',
    why:      '이 키워드들이 왜 이 브리프에 잘 맞는지, 헤리티지/감각/심리/원형 측면에서 한 단락씩 설명해줘.',
  })[key] || '';

  const send = async (textIn, presetKey) => {
    const text = (textIn || draft).trim();
    if (!text || thinking) return;
    setDraft('');
    const userMsg = {role:'user', text, preset: presetKey || null};
    const ctxKws = active.context.map(id => map[id]).filter(Boolean);
    const ctxLabel = ctxKws.length ? `[Context: ${ctxKws.map(k => `${k.en} · ${k.ko}`).join(' / ')}]\n\n` : '';
    const sessUpdated = {...active, messages: [...active.messages, userMsg]};
    setSessions(sessions.map(s => s.id === active.id ? sessUpdated : s));
    setThinking(true);
    try {
      const res = await window.API.brainstorm(projectId, 'omni', sessUpdated.messages.map(m => ({me: m.role==='user', text: ctxLabel + m.text})));
      const parsed = parseAIReply(res.reply || '', presetKey);
      const aiMsg = {role:'ai', text: res.reply || '', kws: res.kws || [], model: res.model, kind: parsed.kind, structured: parsed.data};
      setSessions(prev => prev.map(s => s.id === active.id ? {...s, messages: [...sessUpdated.messages, aiMsg], title: sessUpdated.title === 'New chat' ? text.slice(0, 32) : sessUpdated.title} : s));
    } catch(e) {
      setSessions(prev => prev.map(s => s.id === active.id ? {...s, messages: [...sessUpdated.messages, {role:'ai', text:'에러: '+e.message, kws:[]}]} : s));
    } finally { setThinking(false); }
  };

  const seedFromMsg = (text, from) => setSavedSeeds(prev => [...prev, {ko: text, from}]);

  const removeSeed = (idx) => setSavedSeeds(prev => prev.filter((_, i) => i !== idx));

  const regenerate = () => {
    const lastUser = [...active.messages].reverse().find(m => m.role === 'user');
    if (!lastUser) return;
    // Drop the latest AI reply and re-send
    const trimmed = active.messages.slice(0, active.messages.lastIndexOf(lastUser));
    setSessions(sessions.map(s => s.id === active.id ? {...s, messages: trimmed} : s));
    setTimeout(() => send(lastUser.text, lastUser.preset), 50);
  };

  const messageAction = (msg, action) => {
    const followups = {
      'Refine':    `방금 답변을 더 정교하게 다듬어줘. 같은 형식, 같은 길이로.`,
      'Shorter':   `방금 답변을 더 짧게 줄여줘. 핵심만.`,
      'Translate': `방금 답변을 영문 카피 톤으로 번역해줘.`,
      'Branch':    `방금 답변과 다른 방향으로 새 후보를 뽑아줘.`,
    }[action] || action;
    send(followups, null);
  };

  return (
    <div className="v2-app" style={{display:'grid',gridTemplateColumns:'248px 1fr 296px',height:'100%',background:'var(--bg)'}}>
      {/* LEFT — sessions */}
      <div style={{borderRight:'1px solid var(--rule)',background:'var(--paper-2)',display:'flex',flexDirection:'column'}}>
        <div style={{padding:'14px 14px 10px',borderBottom:'1px solid var(--rule)'}}>
          <button onClick={newSession} style={{
            display:'flex',alignItems:'center',gap:8,width:'100%',padding:'10px 12px',
            background:'var(--ink)',color:'#fff',border:'none',borderRadius:8,cursor:'pointer',
            fontSize:12,fontWeight:600,fontFamily:'inherit'
          }}>
            <V2Icon name="plus" size={12} color="#fff"/> 새 채팅 세션
          </button>
        </div>
        <div className="tag" style={{color:'var(--muted)',padding:'14px 14px 6px'}}>SESSIONS · {sessions.length}</div>
        <div className="scroll" style={{flex:1,overflow:'auto',padding:'0 8px 12px'}}>
          {sessions.map(s => (
            <button key={s.id} onClick={()=>setActiveId(s.id)} style={{
              display:'block',width:'100%',textAlign:'left',padding:'10px 12px',marginBottom:4,
              background: s.id===activeId ? 'var(--paper)' : 'transparent',
              border: s.id===activeId ? '1px solid var(--rule)' : '1px solid transparent',
              borderLeft: s.id===activeId ? '2px solid var(--accent)' : '2px solid transparent',
              borderRadius:6,cursor:'pointer',fontFamily:'inherit',
            }}>
              <div style={{fontSize:12.5,fontWeight: s.id===activeId?600:500}}>{s.title}</div>
              <div style={{display:'flex',gap:3,marginTop:6,flexWrap:'wrap'}}>
                {s.context.slice(0,3).map(cid => map[cid] && (
                  <span key={cid} className="mono" style={{fontSize:9,color:'var(--muted)'}}>·{map[cid].en}</span>
                ))}
                {s.context.length>3 && <span className="mono" style={{fontSize:9,color:'var(--muted)'}}>+{s.context.length-3}</span>}
              </div>
            </button>
          ))}
        </div>
        <div style={{borderTop:'1px solid var(--rule)',padding:'14px',maxHeight:200,overflow:'auto'}}>
          <div className="tag" style={{color:'var(--muted)',marginBottom:8}}>BOARD · CLICK TO ATTACH</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:4}}>
            {allPinned.map(kw => (
              <span key={kw.id} className={`chip t-${kw.type}`} onClick={()=>addContext(kw.id)}
                style={{cursor:'pointer',fontSize:10}}>
                <span className="chip-en">{kw.en}</span>
              </span>
            ))}
            {allPinned.length === 0 && <span style={{fontSize:11,color:'var(--muted)'}}>핀된 키워드 없음</span>}
          </div>
        </div>
      </div>

      {/* CENTER — chat */}
      <div style={{display:'flex',flexDirection:'column',overflow:'hidden'}}>
        <div style={{padding:'14px 28px',borderBottom:'1px solid var(--rule)',background:'var(--paper)'}}>
          <div style={{display:'flex',alignItems:'baseline',gap:10,marginBottom:10}}>
            <h2 style={{margin:0,fontSize:16,fontWeight:600,letterSpacing:'-.01em'}}>{active.title}</h2>
            <span className="mono" style={{fontSize:10,color:'var(--muted)'}}>· {active.messages.length} turns · {active.context.length} keywords in context</span>
            <div style={{flex:1}}/>
            <button className="btn sm" onClick={regenerate} disabled={!active.messages.length || thinking}>
              <V2Icon name="refresh" size={11}/> Regenerate
            </button>
          </div>
          <div style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap'}}>
            <span className="mono" style={{fontSize:9.5,color:'var(--muted)',letterSpacing:'.08em',marginRight:4}}>CONTEXT</span>
            {active.context.map(cid => map[cid] && (
              <span key={cid} className={`chip t-${map[cid].type}`} style={{fontSize:10}}>
                <span className="chip-en">{map[cid].en}</span>
                <span className="chip-ko">·{map[cid].ko}</span>
                <button onClick={()=>removeContext(cid)} style={{background:'none',border:'none',marginLeft:2,cursor:'pointer',color:'var(--muted)',fontSize:11}}>×</button>
              </span>
            ))}
          </div>
        </div>
        <div className="scroll" style={{flex:1,overflow:'auto',padding:'24px 28px 12px',background:'var(--bg)'}}>
          {active.messages.length === 0 && (
            <div style={{textAlign:'center',padding:'80px 20px',color:'var(--muted)'}}>
              <div style={{fontSize:14,marginBottom:6}}>새 세션입니다.</div>
              <div className="mono" style={{fontSize:11}}>핀된 키워드는 자동으로 컨텍스트에 첨부됩니다. 아래 프리셋이나 자유 입력으로 시작하세요.</div>
            </div>
          )}
          {active.messages.map((m, i) => (
            <V2ChatTurn key={i} m={{...m, _sessionTitle: active.title}}
              onSeed={(t, from)=>seedFromMsg(t, from || active.title)}
              onAction={messageAction}/>
          ))}
          {thinking && (
            <div style={{display:'flex',gap:12,marginBottom:20}}>
              <div style={{width:28,height:28,borderRadius:14,background:'var(--accent)',color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                <V2Icon name="wand" size={12} color="#fff"/>
              </div>
              <div style={{padding:'14px 16px',background:'var(--paper)',border:'1px solid var(--rule)',borderRadius:'12px 12px 12px 2px',display:'flex',gap:6}}>
                <V2Dot delay={0}/><V2Dot delay={.15}/><V2Dot delay={.3}/>
              </div>
            </div>
          )}
        </div>
        <div style={{borderTop:'1px solid var(--rule)',background:'var(--paper)',padding:'12px 24px 16px'}}>
          <div style={{display:'flex',gap:5,marginBottom:10,flexWrap:'wrap'}}>
            {presets.map(p => (
              <button key={p.key} onClick={()=>send(presetText(p.key), p.key)} disabled={thinking} style={{
                display:'inline-flex',alignItems:'center',gap:5,padding:'5px 10px',
                background:'var(--paper-2)',border:'1px solid var(--rule)',borderRadius:999,
                fontSize:11,fontWeight:500,cursor: thinking?'wait':'pointer',
                fontFamily:'var(--font-mono)',letterSpacing:'.02em'
              }}>
                <V2Icon name="wand" size={9} color="var(--primary)"/> {p.label}
                <span style={{color:'var(--muted)',fontSize:9.5}}>· {p.sub}</span>
              </button>
            ))}
          </div>
          <div style={{border:'1px solid var(--rule)',borderRadius:10,background:'var(--paper-2)',padding:'10px 14px',display:'flex',gap:10,alignItems:'flex-end'}}>
            <textarea value={draft} onChange={e=>setDraft(e.target.value)}
              onKeyDown={e=>{ if ((e.metaKey||e.ctrlKey) && e.key==='Enter') send(); }}
              placeholder="자유롭게 물어보세요. 컨텍스트의 키워드가 함께 사용됩니다. (⌘↵)"
              rows={2}
              style={{flex:1,border:'none',outline:'none',background:'transparent',
                fontSize:13.5,lineHeight:1.5,resize:'none',fontFamily:'inherit'}}/>
            <button className="btn primary sm" onClick={()=>send()} disabled={thinking || !draft.trim()}>
              <V2Icon name="send" size={11} color="#fff"/> Send
            </button>
          </div>
        </div>
      </div>

      {/* RIGHT — saved seeds */}
      <div style={{borderLeft:'1px solid var(--rule)',background:'var(--paper-2)',display:'flex',flexDirection:'column'}}>
        <div style={{padding:'14px 16px',borderBottom:'1px solid var(--rule)',display:'flex',alignItems:'center',gap:8}}>
          <V2Icon name="spark" size={13} color="var(--accent)"/>
          <span style={{fontSize:12.5,fontWeight:600}}>Copy keys</span>
          <span className="mono" style={{fontSize:10,color:'var(--muted)',marginLeft:'auto'}}>{savedSeeds.length} saved</span>
        </div>
        <div className="scroll" style={{flex:1,overflow:'auto',padding:'12px 12px 60px'}}>
          {savedSeeds.map((s, i) => (
            <div key={i} draggable style={{padding:'12px 14px',background:'var(--paper)',border:'1px solid var(--rule)',
              borderRadius:8,marginBottom:8,position:'relative',cursor:'grab'}}>
              <button onClick={()=>removeSeed(i)} title="삭제"
                style={{position:'absolute',top:8,right:8,width:20,height:20,padding:0,
                  background:'transparent',border:'1px solid var(--rule)',borderRadius:'50%',
                  cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',
                  color:'var(--muted)',transition:'all .12s'}}>
                <V2Icon name="x" size={10}/>
              </button>
              <div className="mono" style={{fontSize:9,color:'var(--primary)',fontWeight:700,letterSpacing:'.08em',marginBottom:5,paddingRight:24}}>KEY #{String(i+1).padStart(2,'0')}</div>
              <div style={{fontSize:13,fontWeight:500,lineHeight:1.45,marginBottom:6,paddingRight:24}}>{s.ko}</div>
              <div className="mono" style={{fontSize:9,color:'var(--muted)'}}>from · {s.from}</div>
            </div>
          ))}
          {savedSeeds.length === 0 && (
            <div style={{padding:14,border:'1px dashed var(--rule)',borderRadius:8,
              color:'var(--muted)',fontSize:11,textAlign:'center'}}>
              채팅 응답에서 <b>+ key</b> 버튼으로 적립
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const V2ChatTurn = ({m, onSeed, onAction}) => {
  const isUser = m.role === 'user';
  const kind = !isUser && (m.kind || 'text');
  return (
    <div style={{display:'flex',gap:12,marginBottom:20,flexDirection: isUser?'row-reverse':'row'}}>
      <div style={{width:28,height:28,borderRadius:14,flexShrink:0,
        background: isUser ? 'var(--ink)' : 'var(--primary)',color:'#fff',
        display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,fontWeight:600,fontFamily:'var(--font-mono)'}}>
        {isUser ? 'YOU' : <V2Icon name="wand" size={12} color="#fff"/>}
      </div>
      <div style={{maxWidth:'min(720px, 86%)',display:'flex',flexDirection:'column',alignItems: isUser?'flex-end':'flex-start',gap:6}}>
        <div className="mono" style={{fontSize:9,color:'var(--muted)',letterSpacing:'.08em'}}>
          {isUser ? 'YOU' : (m.model || 'PALETTE AI')}
          {isUser && m.preset && <span style={{color:'var(--primary)',marginLeft:8}}>· /{m.preset}</span>}
        </div>
        {isUser && (
          <div style={{background:'var(--ink)',color:'#fff',padding:'10px 14px',borderRadius:'12px 12px 2px 12px',
            fontSize:13.5,lineHeight:1.5}}>{m.text}</div>
        )}
        {!isUser && kind === 'taglines' && (
          <div style={{background:'var(--paper)',border:'1px solid var(--rule)',
            borderRadius:'12px 12px 12px 2px',padding:'14px 16px',width:'100%',
            boxShadow:'var(--shadow-1)'}}>
            {(m.structured.items || []).map((t, idx) => (
              <div key={idx} style={{display:'flex',gap:14,alignItems:'center',padding:'10px 0',
                borderTop: idx > 0 ? '1px solid var(--rule)' : 'none'}}>
                <span className="mono" style={{fontSize:11,color:'var(--primary)',fontWeight:700,width:22}}>{t.n}.</span>
                <div style={{flex:1}}>
                  <div style={{fontSize:15.5,fontWeight:600,letterSpacing:'-.01em'}}>{t.ko}</div>
                  {t.en && <div style={{fontSize:12,color:'var(--sub)',fontStyle:'italic',marginTop:2}}>{t.en}</div>}
                </div>
                <button className="btn sm" onClick={()=>onSeed(t.ko, m._sessionTitle)}><V2Icon name="plus" size={10}/> key</button>
              </div>
            ))}
          </div>
        )}
        {!isUser && kind === 'ladder' && (
          <div style={{background:'var(--paper)',border:'1px solid var(--rule)',
            borderRadius:'12px 12px 12px 2px',padding:'14px 16px',width:'100%',
            boxShadow:'var(--shadow-1)'}}>
            <div className="mono" style={{fontSize:10,color:'var(--muted)',letterSpacing:'.08em',marginBottom:10}}>5-TIER COPY LADDER · LITERAL → METAPHOR</div>
            {(m.structured.items || []).map((t, idx) => (
              <div key={idx} style={{display:'grid',gridTemplateColumns:'88px 1fr auto',gap:12,padding:'10px 0',alignItems:'center',
                borderTop: idx > 0 ? '1px solid var(--rule)' : 'none'}}>
                <span className={`chip t-${t.type}`} style={{justifySelf:'start',fontSize:9.5}}>
                  <span className="chip-en">{t.type}</span>
                </span>
                <div>
                  <div style={{fontSize:14.5,fontWeight:500}}>{t.copy}</div>
                  {t.en && <div style={{fontSize:11.5,color:'var(--muted)',fontStyle:'italic',marginTop:2}}>{t.en}</div>}
                </div>
                <button className="btn sm" onClick={()=>onSeed(t.copy, m._sessionTitle)}><V2Icon name="plus" size={10}/></button>
              </div>
            ))}
          </div>
        )}
        {!isUser && kind === 'reasoning' && (
          <div style={{background:'var(--paper)',border:'1px solid var(--rule)',padding:'14px 16px',
            borderRadius:'12px 12px 12px 2px',fontSize:13.5,lineHeight:1.6,color:'var(--ink-2)',
            width:'100%'}}>
            <div>{m.structured.text}</div>
            {(m.structured.followups || []).length > 0 && (
              <div style={{marginTop:12,paddingTop:10,borderTop:'1px dashed var(--rule)'}}>
                {m.structured.followups.map((f, i) => (
                  <div key={i} style={{display:'flex',alignItems:'baseline',gap:10,padding:'4px 0'}}>
                    <span className="mono" style={{fontSize:9,color:'var(--muted)',width:12}}>·</span>
                    <div style={{flex:1}}>
                      <span style={{fontSize:13,fontWeight:500}}>{f.ko}</span>
                      {f.en && <span style={{fontSize:11.5,fontStyle:'italic',color:'var(--muted)',marginLeft:8}}>{f.en}</span>}
                    </div>
                    <button className="btn sm" onClick={()=>onSeed(f.ko, m._sessionTitle)}><V2Icon name="plus" size={9}/> key</button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
        {!isUser && (kind === 'text' || !kind) && (
          <div style={{background:'var(--paper)',border:'1px solid var(--rule)',padding:'14px 16px',
            borderRadius:'12px 12px 12px 2px',fontSize:13.5,lineHeight:1.65,color:'var(--ink-2)',width:'100%'}}>
            <div style={{whiteSpace:'pre-wrap'}}>{m.text}</div>
            {(m.kws || []).length > 0 && (
              <div style={{marginTop:14,paddingTop:12,borderTop:'1px dashed var(--rule)',display:'flex',flexDirection:'column',gap:6}}>
                {m.kws.map((c, j) => (
                  <div key={j} style={{display:'flex',gap:10,alignItems:'flex-start',padding:'8px 0'}}>
                    <span className={`chip t-${(c.tier||c.type||'LITERAL').toUpperCase()}`} style={{fontSize:10}}>
                      <span className="chip-type">{(c.tier||c.type||'').slice(0,3).toUpperCase()}</span>
                      <span className="chip-en">{c.w || c.en}</span>
                      <span className="chip-ko">· {c.ko}</span>
                    </span>
                    {(c.why || c.gloss) && <span style={{fontSize:11,fontStyle:'italic',color:'var(--muted)'}}>"{c.why || c.gloss}"</span>}
                    <div style={{flex:1}}/>
                    <button className="btn sm" onClick={()=>onSeed(c.ko || c.w || c.en, m._sessionTitle)}>+ key</button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
        {!isUser && (
          <div style={{display:'flex',gap:4,marginTop:2}}>
            {['Refine','Shorter','Translate','Branch'].map(a=>(
              <button key={a} onClick={()=>onAction?.(m, a)} style={{
                padding:'3px 8px',background:'transparent',border:'1px solid var(--rule)',
                borderRadius:999,fontSize:10,color:'var(--muted)',cursor:'pointer',
                fontFamily:'var(--font-mono)'}}>{a}</button>
            ))}
            <button className="btn xs ghost" onClick={()=>navigator.clipboard?.writeText(m.text)}
              style={{padding:'3px 8px',fontSize:10,color:'var(--muted)'}}>Copy</button>
          </div>
        )}
      </div>
    </div>
  );
};

window.V2IdeateStage = V2IdeateStage;
