// more-sheets.jsx — 헤드라인 "더보기" 뉴스 시트 + AI 추천 더보기 시트

// ============ 공통 슬라이드업 컨테이너 ============
function BaseSheet({ open, onClose, title, kicker, children }) {
  const { dark } = useTheme();
  const p = palette(dark);
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => {
    if (open) { requestAnimationFrame(()=>setMounted(true)); }
    else { setMounted(false); }
  }, [open]);

  if (!open) return null;

  return (
    <div style={{ position:'absolute', inset:0, zIndex:105, pointerEvents:'auto' }}>
      <div onClick={onClose} style={{
        position:'absolute', inset:0,
        background:'rgba(0,0,0,0.42)',
        backdropFilter:'blur(3px)', WebkitBackdropFilter:'blur(3px)',
        opacity: mounted ? 1 : 0,
        transition:'opacity 220ms ease',
      }}/>
      <div style={{
        position:'absolute', left:0, right:0, bottom:0,
        background: p.bg,
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        height: '86%',
        display:'flex', flexDirection:'column',
        transform: mounted ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 340ms cubic-bezier(0.25, 1, 0.32, 1)',
        boxShadow:'0 -20px 48px rgba(0,0,0,0.28)',
        overflow:'hidden',
      }}>
        <div style={{ display:'flex', justifyContent:'center', padding:'10px 0 2px' }}>
          <div style={{ width:36, height:5, borderRadius:3, background:p.line2 }}/>
        </div>
        <div style={{ padding:'10px 22px 14px', display:'flex', alignItems:'flex-start', gap:12 }}>
          <div style={{ flex:1, minWidth:0 }}>
            {kicker && (
              <div style={{
                fontSize:10, letterSpacing:'0.16em', color:p.faint,
                fontFamily:'"JetBrains Mono", monospace', marginBottom:5,
              }}>{kicker}</div>
            )}
            <div style={{
              fontSize:22, fontWeight:600, color:p.text,
              fontFamily:'"Inter Tight", system-ui', letterSpacing:-0.5,
              lineHeight:1.1,
            }}>{title}</div>
          </div>
          <button onClick={onClose} aria-label="close" style={{
            width:34, height:34, borderRadius:'50%', border:'none', cursor:'pointer',
            background: p.surface2, color:p.muted, flexShrink:0,
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14">
              <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          </button>
        </div>
        <div style={{ flex:1, minHeight:0, overflowY:'auto', paddingBottom:30 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

// ============ 뉴스 더보기 시트 ============
function NewsMoreSheet({ open, onClose }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const [cat, setCat] = React.useState('ALL');
  const items = (MORE_NEWS && MORE_NEWS[lang]) || [];
  // MORE_NEWS categories: TECH, MACRO, EARN, POLICY, FLOW, COMM, CRYPTO, FX, M&A
  const CATS = lang==='ko'
    ? [['ALL','전체'],['MACRO','매크로'],['TECH','테크'],['EARN','실적'],['POLICY','정책'],['FLOW','수급'],['FX','환율']]
    : [['ALL','All'],['MACRO','Macro'],['TECH','Tech'],['EARN','Earn'],['POLICY','Policy'],['FLOW','Flow'],['FX','FX']];

  const filtered = cat==='ALL' ? items : items.filter(n=>n.cat===cat);

  return (
    <BaseSheet open={open} onClose={onClose}
      kicker={lang==='ko'?'오늘의 뉴스':'TODAY · NEWS'}
      title={lang==='ko'?'전체 헤드라인':'All Headlines'}>
      {/* filter tabs */}
      <div style={{ padding:'2px 16px 14px' }}>
        <div style={{
          display:'flex', gap:4, overflowX:'auto',
          scrollbarWidth:'none',
        }}>
          {CATS.map(([k,label])=>(
            <button key={k} onClick={()=>setCat(k)} style={{
              appearance:'none', cursor:'pointer', flexShrink:0,
              padding:'8px 14px', borderRadius:999,
              border: cat===k ? `0.5px solid transparent` : `0.5px solid ${p.line2}`,
              background: cat===k ? p.text : 'transparent',
              color: cat===k ? (dark?'#0E0E10':'#FBF7EE') : p.muted,
              fontSize:12, fontWeight:500, letterSpacing:-0.1,
              fontFamily:'"Inter Tight", system-ui',
            }}>{label}</button>
          ))}
        </div>
      </div>

      {/* list */}
      <div style={{ padding:'0 16px' }}>
        {filtered.map((n,i)=>{
          const clickable = !!n.link;
          const onRowClick = () => { if (clickable) window.open(n.link, '_blank', 'noopener'); };
          return (
            <div key={i}
              onClick={onRowClick}
              style={{
                padding:'14px 0',
                borderBottom: i===filtered.length-1 ? 'none' : `0.5px solid ${p.line}`,
                cursor: clickable ? 'pointer' : 'default',
              }}>
              <div style={{
                display:'flex', alignItems:'center', gap:8, marginBottom:6,
                fontFamily:'"JetBrains Mono", monospace', fontSize:10,
                color:p.faint, letterSpacing:'0.1em',
              }}>
                <span>{n.t}</span>
                <span style={{
                  padding:'2px 7px', borderRadius:4,
                  background: p.surface2, color:p.muted, letterSpacing:'0.14em',
                  fontSize:9, fontWeight:600,
                }}>{n.cat}</span>
                <span style={{ flex:1 }}/>
                <span style={{ display:'inline-flex', gap:1 }}>
                  {[1,2,3,4,5].map(k=>(
                    <svg key={k} width="8" height="8" viewBox="0 0 10 10">
                      <path d="M5 0.5l1.4 3 3.1.3-2.3 2.1.7 3.1L5 7.5 2.1 9l.7-3.1L0.5 3.8l3.1-.3z"
                        fill={k<=n.imp? p.muted : 'transparent'}
                        stroke={k<=n.imp? p.muted : p.line2} strokeWidth="0.5"/>
                    </svg>
                  ))}
                </span>
              </div>
              <div style={{
                fontSize:14, color:p.text, lineHeight:1.4,
                letterSpacing:-0.2, fontWeight:500, textWrap:'pretty',
              }}>{n.text}</div>
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div style={{
            padding:'40px 20px', textAlign:'center',
            color:p.faint, fontSize:12,
          }}>{lang==='ko'?'해당 카테고리의 뉴스가 없습니다.':'No news in this category.'}</div>
        )}
      </div>
    </BaseSheet>
  );
}

// ============ AI 추천 더보기 시트 ============
function AIMoreSheet({ open, onClose, onPickStock }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const picks = MORE_AI_PICKS || [];
  const [sort, setSort] = React.useState('score'); // score | upside

  const sorted = React.useMemo(() => {
    const list = [...picks];
    if (sort === 'score') list.sort((a,b)=>b.score-a.score);
    if (sort === 'upside') list.sort((a,b)=> ((b.target-b.px)/b.px) - ((a.target-a.px)/a.px));
    return list;
  }, [sort, picks]);

  return (
    <BaseSheet open={open} onClose={onClose}
      kicker={lang==='ko'?'AI 엔진 · 전체':'AI ENGINE · ALL'}
      title={lang==='ko'?'추가 추천 종목':'More AI Picks'}>
      {/* sort */}
      <div style={{ padding:'2px 16px 12px', display:'flex', gap:6 }}>
        {[
          ['score', lang==='ko'?'점수순':'Score'],
          ['upside', lang==='ko'?'상승여력순':'Upside'],
        ].map(([k,label])=>(
          <button key={k} onClick={()=>setSort(k)} style={{
            appearance:'none', cursor:'pointer',
            padding:'7px 12px', borderRadius:8,
            border: sort===k? 'none' : `0.5px solid ${p.line2}`,
            background: sort===k? p.surface2 : 'transparent',
            color: sort===k? p.text : p.muted,
            fontSize:11.5, fontWeight:500,
            fontFamily:'"Inter Tight", system-ui',
          }}>{label}</button>
        ))}
      </div>

      {/* picks grid */}
      <div style={{ padding:'0 14px', display:'flex', flexDirection:'column', gap:10 }}>
        {sorted.map((pk)=>{
          const upside = ((pk.target - pk.px)/pk.px*100);
          const sigs = lang==='ko'? pk.signalsKo : pk.signalsEn;
          const thesis = lang==='ko'? pk.thesisKo : pk.thesisEn;
          return (
            <button key={pk.sym} onClick={()=> onPickStock && onPickStock(pk)} style={{
              appearance:'none', cursor:'pointer', textAlign:'left',
              background: p.surface, border:'none', borderRadius:18, padding:14,
              boxShadow: dark ? '0 0 0 1px rgba(255,255,255,0.05)' : '0 0 0 1px rgba(0,0,0,0.04)',
              font:'inherit',
            }}>
              <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:10 }}>
                    <div style={{ minWidth:0 }}>
                      <div style={{
                        fontSize:15, fontWeight:600, color:p.text,
                        letterSpacing:-0.3,
                      }}>{pk.name} ›</div>
                      <div style={{
                        fontFamily:'"JetBrains Mono", monospace', fontSize:10,
                        color:p.faint, marginTop:2,
                      }}>{pk.sym}</div>
                    </div>
                    <div style={{ textAlign:'right', flexShrink:0 }}>
                      <div style={{
                        fontSize:10, letterSpacing:'0.14em', color:p.faint,
                        fontFamily:'"JetBrains Mono", monospace',
                      }}>SCORE</div>
                      <div style={{
                        fontSize:20, fontWeight:600, color:p.text, lineHeight:1,
                        fontFamily:'"Inter Tight", system-ui',
                        fontVariantNumeric:'tabular-nums', letterSpacing:-0.5,
                        marginTop:2,
                      }}>{pk.score}</div>
                    </div>
                  </div>
                  <div style={{ height:4, borderRadius:2, background:p.surface2, marginTop:8, overflow:'hidden' }}>
                    <div style={{ width:`${pk.score}%`, height:'100%', background:p.inkUp }}/>
                  </div>
                  <div style={{ marginTop:10, display:'flex', flexWrap:'wrap', gap:5 }}>
                    {sigs.map((s,j)=>(
                      <span key={j} style={{
                        fontSize:10.5, padding:'3px 8px', borderRadius:6,
                        background:p.surface2, color:p.muted, letterSpacing:-0.1,
                      }}>{s}</span>
                    ))}
                  </div>
                  <div style={{
                    marginTop:10, fontSize:12, color:p.muted,
                    lineHeight:1.45, letterSpacing:-0.1, textWrap:'pretty',
                  }}>{thesis}</div>
                  {pk.cci!=null && <div style={{ marginTop:10 }}><CCIBadge cci={pk.cci} compact/></div>}
                  <div style={{
                    marginTop:10, paddingTop:10, borderTop:`0.5px solid ${p.line}`,
                    display:'flex', justifyContent:'space-between', alignItems:'center',
                    fontFamily:'"JetBrains Mono", monospace', fontSize:11,
                  }}>
                    <span style={{ color:p.faint, letterSpacing:'0.1em' }}>
                      {lang==='ko'?'목표가':'TARGET'} {pk.target.toLocaleString('en-US')}
                    </span>
                    <span style={{ color: upside>=0? p.inkUp : p.inkDown, fontWeight:600 }}>
                      {upside>=0?'+':''}{upside.toFixed(1)}% · {pk.horizon}
                    </span>
                  </div>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </BaseSheet>
  );
}

Object.assign(window, { NewsMoreSheet, AIMoreSheet });
