// v2 FINAL stage — one-pager preview + revision chat with model picker

const V2_FINAL_MODELS = [
  {id:'nemotron',name:'Nemotron 3 Nano Omni', tag:'NVIDIA · multimodal', dot:'#76B900'},
  {id:'claude',  name:'Claude Opus 4.7', tag:'Anthropic', dot:'#006747'},
  {id:'gemini',  name:'Gemini 3.1 Pro',  tag:'Google',    dot:'#4285F4'},
  {id:'gpt',     name:'GPT-5',           tag:'OpenAI',    dot:'#10A37F'},
  {id:'omni',    name:'Palette Omni',    tag:'Hybrid',    dot:'#1A1A1A'},
];

const V2FinalStage = ({palette, projectId, pinnedIds, onExportDeck, onExportMarkdown}) => {
  const map = {};
  (palette.blocks || []).forEach(b => (b.keywords || []).forEach(k => map[k.id] = k));
  const pinned = pinnedIds.map(id => map[id]).filter(Boolean);
  const headlineKw = pinned.find(k => k.type === 'METAPHOR') || pinned[0];
  const [exporting, setExporting] = React.useState(null); // 'md' | 'deck' | null

  const exportMd = async () => {
    setExporting('md');
    try { await onExportMarkdown?.(); } finally { setExporting(null); }
  };
  const exportDeck = async () => {
    setExporting('deck');
    try { await onExportDeck?.(); } finally { setExporting(null); }
  };

  return (
    <div className="v2-app" style={{padding:'40px 60px',maxWidth:1100,margin:'0 auto',height:'100%',overflow:'auto'}}>
      <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:24}}>
        <h1 style={{margin:0,fontSize:28,fontWeight:700,letterSpacing:'-.02em'}}>최종 산출물</h1>
        <span className="mono" style={{fontSize:11,color:'var(--muted)'}}>{palette.project?.name} · v3 draft</span>
        <div style={{flex:1}}/>
        <button className="btn" onClick={exportMd} disabled={!!exporting}>
          {exporting === 'md' ? <><V2Spinner size="sm"/> <span>생성 중…</span></>
                              : <><V2Icon name="doc" size={12}/> Markdown</>}
        </button>
        <button className="btn primary" onClick={exportDeck} disabled={!!exporting}>
          {exporting === 'deck' ? <><V2Spinner size="sm" color="#fff"/> <span>여는 중…</span></>
                                : <><V2Icon name="send" size={12}/> HTML 덱 열기</>}
        </button>
      </div>

      <div style={{padding:'28px 36px',background:'var(--paper)',border:'1px solid var(--rule)',borderRadius:12,boxShadow:'var(--shadow-2)'}}>
        <div className="tag" style={{color:'var(--muted)',marginBottom:18}}>COPY · ONE-PAGER PREVIEW</div>
        {headlineKw ? (
          <>
            <h2 style={{margin:'0 0 12px',fontSize:32,fontWeight:700,letterSpacing:'-.025em'}}>
              {headlineKw.ko}
            </h2>
            <p style={{margin:'0 0 18px',fontSize:14,color:'var(--sub)',fontStyle:'italic'}}>{headlineKw.en}</p>
          </>
        ) : (
          <h2 style={{margin:'0 0 12px',fontSize:24,color:'var(--muted)'}}>아직 핀된 키워드가 없습니다</h2>
        )}
        <div style={{height:1,background:'var(--rule)',margin:'18px 0'}}/>
        <p style={{fontSize:14.5,lineHeight:1.7,color:'var(--ink-2)',margin:'0 0 14px'}}>
          {palette.project?.brief || '프로젝트 브리프가 없습니다. Data 단계에서 작성해주세요.'}
        </p>
        <div style={{fontSize:13,color:'var(--muted)',lineHeight:1.6,display:'flex',gap:14,flexWrap:'wrap'}}>
          <span className="mono" style={{fontSize:10,letterSpacing:'.06em'}}>BASED ON</span>
          {pinned.slice(0, 6).map(k => (
            <span key={k.id} style={{fontSize:13}}>· {k.ko || k.en}</span>
          ))}
        </div>
      </div>

      <V2FinalChat palette={palette} projectId={projectId} pinnedIds={pinnedIds}/>
    </div>
  );
};

const V2FinalChat = ({palette, projectId, pinnedIds}) => {
  const [model, setModel] = React.useState(V2_FINAL_MODELS[0]);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    {role:'ai', text:'Final 덱의 카피·구조·톤을 자유롭게 다듬어 드릴 수 있어요. 무엇을 바꿔볼까요?', hint:true, model: V2_FINAL_MODELS[0].id},
  ]);
  const [draft, setDraft] = React.useState('');
  const [thinking, setThinking] = React.useState(false);

  const send = async () => {
    const v = draft.trim(); if (!v || thinking) return;
    const userMsg = {role:'user', text: v};
    const next = [...messages.filter(m => !m.hint), userMsg];
    setMessages([{role:'ai', text:'Final 덱의 카피·구조·톤을 자유롭게 다듬어 드릴 수 있어요. 무엇을 바꿔볼까요?', hint:true, model: model.id}, ...next]);
    setDraft(''); setThinking(true);
    try {
      const res = await window.API.brainstorm(projectId, model.id, next.map(m => ({me: m.role==='user', text: m.text})));
      setMessages(prev => [...prev, {role:'ai', text: res.reply, items: extractList(res.reply), kws: res.kws || [], model: model.id}]);
    } catch(e) {
      setMessages(prev => [...prev, {role:'ai', text:'에러: '+e.message, model: model.id}]);
    } finally { setThinking(false); }
  };

  const presets = ['더 짧게','시제 바꿔','감정 톤↑','영문 버전','한 줄 요약','전체 흐름 점검'];

  return (
    <div style={{marginTop:18,background:'var(--paper)',border:'1px solid var(--rule)',borderRadius:12,boxShadow:'var(--shadow-1)',overflow:'hidden'}}>
      <div style={{display:'flex',alignItems:'center',gap:10,padding:'14px 20px',borderBottom:'1px solid var(--rule)',background:'var(--paper-2)'}}>
        <div style={{position:'relative'}}>
          <button onClick={()=>setPickerOpen(!pickerOpen)} style={{
            display:'flex',alignItems:'center',gap:8,padding:'6px 10px',
            background:'var(--paper)',border:'1px solid var(--rule)',borderRadius:8,
            fontSize:12,fontWeight:500,cursor:'pointer',fontFamily:'inherit'}}>
            <span style={{width:8,height:8,borderRadius:4,background:model.dot}}/>
            {model.name}
            <V2Icon name="chevron-down" size={11} color="var(--muted)"/>
          </button>
          {pickerOpen && (
            <div style={{position:'absolute',top:36,left:0,zIndex:10,minWidth:240,
              background:'var(--paper)',border:'1px solid var(--rule)',borderRadius:10,
              boxShadow:'0 8px 24px rgba(0,0,0,.12)',padding:5}}>
              {V2_FINAL_MODELS.map(m => (
                <button key={m.id} onClick={()=>{setModel(m); setPickerOpen(false);}} style={{
                  display:'flex',alignItems:'center',gap:10,width:'100%',padding:'8px 10px',
                  background: m.id===model.id ? 'var(--paper-2)' : 'transparent',
                  border:'none',borderRadius:6,cursor:'pointer',textAlign:'left',fontFamily:'inherit'}}>
                  <span style={{width:8,height:8,borderRadius:4,background:m.dot}}/>
                  <div style={{flex:1}}>
                    <div style={{fontSize:12.5,fontWeight:500}}>{m.name}</div>
                    <div className="mono" style={{fontSize:9.5,color:'var(--muted)',marginTop:1}}>{m.tag}</div>
                  </div>
                  {m.id===model.id && <V2Icon name="check" size={11} color="var(--accent)"/>}
                </button>
              ))}
            </div>
          )}
        </div>
        <span className="mono" style={{fontSize:10,color:'var(--muted)',marginLeft:'auto'}}>FINAL · CHAT</span>
      </div>

      <div style={{display:'flex',flexDirection:'column',gap:18,padding:'24px 28px 16px',maxHeight:480,overflow:'auto'}}>
        {messages.map((m, i) => {
          const mdl = V2_FINAL_MODELS.find(x => x.id === m.model) || model;
          return (
            <div key={i} style={{display:'flex',justifyContent: m.role==='user' ? 'flex-end' : 'flex-start'}}>
              <div style={{maxWidth:'min(640px, 86%)',display:'flex',flexDirection:'column',gap:6,
                alignItems: m.role==='user' ? 'flex-end' : 'flex-start'}}>
                <div className="mono" style={{fontSize:9,color:'var(--muted)',letterSpacing:'.08em',display:'flex',alignItems:'center',gap:6}}>
                  {m.role==='user' ? 'YOU' : <><span style={{width:6,height:6,borderRadius:3,background:mdl.dot}}/>{mdl.name.toUpperCase()}</>}
                </div>
                <div style={{
                  padding: m.hint ? '10px 14px' : '14px 16px',
                  background: m.role==='user' ? 'var(--ink)' : 'var(--paper-2)',
                  color: m.role==='user' ? '#fff' : 'var(--ink)',
                  border: m.role==='user' ? 'none' : '1px solid var(--rule)',
                  borderRadius:10, fontSize: m.hint?12.5:13.5, lineHeight:1.55,
                  fontStyle: m.hint?'italic':'normal'}}>
                  <div style={{whiteSpace:'pre-wrap'}}>{m.text}</div>
                  {(m.items || []).length > 0 && (
                    <ol style={{margin:'10px 0 0',paddingLeft:20,fontSize:14,lineHeight:1.7}}>
                      {m.items.map((it,j) => (
                        <li key={j} style={{marginBottom:4}}>
                          {it}
                          <button className="btn sm" style={{marginLeft:8,padding:'2px 8px',fontSize:10}}>Final에 적용</button>
                        </li>
                      ))}
                    </ol>
                  )}
                </div>
              </div>
            </div>
          );
        })}
        {thinking && (
          <div style={{display:'flex',gap:10}}>
            <div style={{padding:'10px 12px',background:'var(--paper-2)',borderRadius:'2px 14px 14px 14px',display:'flex',gap:4}}>
              <V2Dot delay={0}/><V2Dot delay={.15}/><V2Dot delay={.3}/>
            </div>
          </div>
        )}
      </div>

      <div style={{display:'flex',flexWrap:'wrap',gap:6,padding:'4px 28px 12px'}}>
        {presets.map(p => (
          <button key={p} onClick={()=>setDraft(p)} style={{
            padding:'5px 11px',background:'var(--paper-2)',border:'1px solid var(--rule)',
            borderRadius:14,fontSize:11.5,color:'var(--sub)',cursor:'pointer',fontFamily:'inherit'}}>/ {p}</button>
        ))}
      </div>

      <div style={{padding:'0 20px 20px'}}>
        <div style={{display:'flex',background:'var(--paper-2)',border:'1px solid var(--rule)',borderRadius:10,overflow:'hidden'}}>
          <textarea value={draft} onChange={e=>setDraft(e.target.value)}
            onKeyDown={e=>{ if ((e.metaKey||e.ctrlKey) && e.key==='Enter') send(); }}
            placeholder={`${model.name}에게 Final 덱에 대해 물어보세요  ·  ⌘↵ 전송`}
            rows={2}
            style={{flex:1,border:'none',outline:'none',resize:'none',padding:'12px 14px',
              background:'transparent',fontFamily:'inherit',fontSize:13,lineHeight:1.5}}/>
          <button onClick={send} disabled={!draft.trim()||thinking} style={{
            padding:'0 20px',background:'var(--accent)',color:'#fff',border:'none',
            fontSize:13,fontWeight:600,cursor:'pointer',display:'flex',alignItems:'center',gap:7}}>
            <V2Icon name="send" size={12} color="#fff"/> 전송
          </button>
        </div>
      </div>
    </div>
  );
};

const extractList = (text) => {
  if (!text) return [];
  const lines = text.split('\n').filter(l => /^\s*([-*•·]|\d+\.)\s+/.test(l));
  return lines.map(l => l.replace(/^\s*([-*•·]|\d+\.)\s+/, '').trim()).slice(0, 6);
};

window.V2FinalStage = V2FinalStage;
