// per-ai-calendar.jsx — PER 상하위, AI 추천, 월 일정 섹션

// ============ CCI 시그널 헬퍼 ============
// CCI(Commodity Channel Index): ≥+100 과매수(매도), ≤-100 과매도(매수), 그 외 관망
function cciSignal(cci, lang='ko') {
  if (cci >= 100)  return { kind:'SELL', labelKo:'매도', labelEn:'SELL', zoneKo:'과매수', zoneEn:'OVERBOUGHT', arrow:'▼' };
  if (cci <= -100) return { kind:'BUY',  labelKo:'매수', labelEn:'BUY',  zoneKo:'과매도', zoneEn:'OVERSOLD',  arrow:'▲' };
  return { kind:'HOLD', labelKo:'관망', labelEn:'HOLD', zoneKo:'중립', zoneEn:'NEUTRAL', arrow:'◆' };
}

function CCIBadge({ cci, compact=false }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const s = cciSignal(cci);
  const color = s.kind==='BUY' ? p.inkUp : s.kind==='SELL' ? p.inkDown : p.muted;
  const label = lang==='ko' ? s.labelKo : s.labelEn;
  const zone  = lang==='ko' ? s.zoneKo  : s.zoneEn;
  // CCI 게이지: -200..+200 을 0..100% 로 매핑
  const pct = Math.max(0, Math.min(100, (cci + 200)/4));

  if (compact) {
    return (
      <span style={{
        display:'inline-flex', alignItems:'center', gap:4,
        padding:'2px 7px', borderRadius:6,
        background: s.kind==='HOLD' ? p.surface2 : (dark? 'rgba(255,255,255,0.04)':'rgba(30,35,50,0.04)'),
        border: `0.5px solid ${color}${dark?'55':'44'}`,
        fontFamily:'"JetBrains Mono", monospace', fontSize:9.5,
        color, letterSpacing:'0.08em', whiteSpace:'nowrap',
      }}>
        <span style={{ fontWeight:700 }}>{s.arrow} {label}</span>
        <span style={{ opacity:0.7 }}>CCI {cci>0?'+':''}{cci}</span>
      </span>
    );
  }

  return (
    <div style={{
      marginTop:10, padding:'10px 11px', borderRadius:10,
      background: s.kind==='HOLD' ? p.surface2 : (dark? 'rgba(255,255,255,0.03)':'rgba(30,35,50,0.028)'),
      border:`0.5px solid ${color}${dark?'55':'44'}`,
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:10 }}>
        <div style={{ display:'flex', alignItems:'baseline', gap:8, minWidth:0 }}>
          <span style={{
            fontFamily:'"JetBrains Mono", monospace', fontSize:9.5,
            color: p.faint, letterSpacing:'0.18em',
          }}>CCI(20)</span>
          <span style={{
            fontFamily:'"Inter Tight", system-ui', fontSize:14, fontWeight:700,
            color, letterSpacing:-0.2,
          }}>
            {s.arrow} {lang==='ko' ? `${zone} · ${label} 시그널` : `${zone} · ${label} SIGNAL`}
          </span>
        </div>
        <span style={{
          fontFamily:'"JetBrains Mono", monospace', fontSize:12, fontWeight:600,
          color, fontVariantNumeric:'tabular-nums', letterSpacing:-0.2,
        }}>{cci>0?'+':''}{cci}</span>
      </div>
      {/* 게이지: -200..-100 빨강존 / -100..+100 중립존 / +100..+200 파랑존(매도) */}
      <div style={{
        position:'relative', marginTop:8, height:4,
        background: p.surface2, borderRadius:2, overflow:'hidden',
      }}>
        {/* 과매도 구간 */}
        <div style={{ position:'absolute', left:0, top:0, bottom:0, width:'25%', background: p.inkUp, opacity:0.25 }}/>
        {/* 과매수 구간 */}
        <div style={{ position:'absolute', right:0, top:0, bottom:0, width:'25%', background: p.inkDown, opacity:0.25 }}/>
        {/* 0 기준선 */}
        <div style={{ position:'absolute', left:'50%', top:-1, bottom:-1, width:1, background: p.line2 }}/>
        {/* 현재 값 마커 */}
        <div style={{
          position:'absolute', top:-2, bottom:-2, width:3,
          left:`calc(${pct}% - 1.5px)`,
          background: color, borderRadius:1,
        }}/>
      </div>
      <div style={{
        display:'flex', justifyContent:'space-between', marginTop:5,
        fontFamily:'"JetBrains Mono", monospace', fontSize:8.5,
        color: p.faint, letterSpacing:'0.12em',
      }}>
        <span>{lang==='ko'?'과매도':'OVERSOLD'} −100</span>
        <span>0</span>
        <span>+100 {lang==='ko'?'과매수':'OVERBOUGHT'}</span>
      </div>
    </div>
  );
}

// ============ PER 상하위 ============
function PERSection({ onPickStock }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const [mkt, setMkt] = React.useState('KOSPI');
  const [dir, setDir] = React.useState('low'); // low | high
  const data = PER_DATA[mkt][dir];

  const markets = ['KOSPI','KOSDAQ','DOW','NASDAQ'];

  return (
    <>
      <SectionLabel
        kicker={lang==='ko'?'밸류에이션':'VALUATION'}
        title={lang==='ko'?'PER 상·하위 5':'P/E Rankings'}
        right={lang==='ko'?'상장유지 종목 기준':'healthy issuers only'}
      />
      <Card padded={false}>
        {/* market tabs */}
        <div style={{
          display:'flex', gap:4, padding:'12px 12px 0',
          overflowX:'auto', WebkitOverflowScrolling:'touch',
        }}>
          {markets.map(m=>(
            <button key={m} onClick={()=>setMkt(m)} style={{
              appearance:'none', border:'none', cursor:'pointer',
              padding:'7px 11px', borderRadius:9,
              fontSize:11, fontWeight: mkt===m?600:500,
              color: mkt===m? (dark?'#0E0E10':'#FBF7EE') : p.muted,
              background: mkt===m? p.text : p.surface2,
              fontFamily:'"Inter Tight", system-ui',
              whiteSpace:'nowrap', letterSpacing:-0.1,
            }}>{m}</button>
          ))}
        </div>
        {/* dir segmented */}
        <div style={{ padding:'10px 12px 10px' }}>
          <div style={{
            display:'grid', gridTemplateColumns:'1fr 1fr', gap:4,
            background: p.surface2, borderRadius:10, padding:3,
          }}>
            {[
              ['low',  lang==='ko'?'↓ 낮은 PER':'↓ Low P/E'],
              ['high', lang==='ko'?'↑ 높은 PER':'↑ High P/E'],
            ].map(([k,l])=>(
              <button key={k} onClick={()=>setDir(k)} style={{
                appearance:'none', border:'none', cursor:'pointer',
                padding:'7px', borderRadius:8,
                fontSize:11, fontWeight: dir===k?600:500,
                color: dir===k? p.text : p.muted,
                background: dir===k? p.surface : 'transparent',
                boxShadow: dir===k? (dark?'0 0 0 1px rgba(255,255,255,0.05)':'0 1px 2px rgba(0,0,0,0.05)') : 'none',
                fontFamily:'"Inter Tight", system-ui',
              }}>{l}</button>
            ))}
          </div>
        </div>
        {/* column headers */}
        <div style={{
          padding:'0 16px 6px', display:'grid',
          gridTemplateColumns:'20px 1fr 54px 64px',
          gap:10, alignItems:'center',
          fontSize:9, letterSpacing:'0.12em', color:p.faint,
          fontFamily:'"JetBrains Mono", monospace',
        }}>
          <div>#</div>
          <div>{lang==='ko'?'종목':'NAME'}</div>
          <div style={{ textAlign:'right' }}>PER</div>
          <div style={{ textAlign:'right' }}>{lang==='ko'?'등락':'CHG'}</div>
        </div>
        {data.map((r,i)=>(
          <button key={r.sym} onClick={()=> onPickStock && onPickStock(r)} style={{
            display:'grid', gridTemplateColumns:'20px 1fr 54px 64px',
            alignItems:'center', gap:10, padding:'11px 16px',
            width:'100%', textAlign:'left', appearance:'none',
            background:'transparent', border:'none', cursor:'pointer',
            borderTop:`0.5px solid ${p.line}`, font:'inherit',
          }}>
            <div style={{
              fontFamily:'"JetBrains Mono", monospace', fontSize:10,
              color:p.faint, fontVariantNumeric:'tabular-nums',
            }}>{String(i+1).padStart(2,'0')}</div>
            <div style={{ minWidth:0 }}>
              <div style={{
                fontSize:13, fontWeight:600, color:p.text,
                letterSpacing:-0.2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap',
              }}>{r.name}</div>
              <div style={{
                fontFamily:'"JetBrains Mono", monospace', fontSize:10,
                color:p.faint, marginTop:2,
              }}>{r.sym} · {r.mcap}</div>
            </div>
            <div style={{
              textAlign:'right', fontFamily:'"JetBrains Mono", monospace',
              fontSize:12.5, color:p.text, fontVariantNumeric:'tabular-nums',
              fontWeight:500,
            }}>{r.per.toFixed(1)}</div>
            <div style={{ textAlign:'right' }}>
              <Delta pct={r.pct} size={11}/>
            </div>
          </button>
        ))}
      </Card>
    </>
  );
}

// ============ AI 추천 종목 ============
function AIPicks({ onPickStock, onMore }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(()=>setTick(t=>t+1), 2000);
    return () => clearInterval(id);
  }, []);

  // Only CCI-oversold (≤ -100), exclude financial sector.
  const FIN_RE = /금융|은행|증권|보험|지주/;
  const picks = AI_PICKS.filter(pk =>
    typeof pk.cci === 'number' && pk.cci <= -100 &&
    !(pk.sector && FIN_RE.test(pk.sector))
  );

  return (
    <>
      <SectionLabel
        kicker={lang==='ko'?'AI 분석':'AI ENGINE'}
        title={lang==='ko'?'실시간 추천 종목':'Live Picks'}
        right={
          <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
            <span style={{
              width:6, height:6, borderRadius:'50%', background:p.inkUp,
              animation:'dmr-pulse 1.4s ease-in-out infinite',
            }}/>
            {lang==='ko'?'과매도':'OVERSOLD'}
          </span>
        }
      />
      <div style={{ padding:'0 14px', display:'flex', flexDirection:'column', gap:10 }}>
        {picks.map((pk,i)=>{
          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;
          // 2초마다 score 가 ±1 흔들림
          const liveScore = Math.max(70, Math.min(99, pk.score + (((tick*(i+2)) % 5) - 2)));
          return (
            <div key={pk.sym} style={{
              background: p.surface, 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)',
            }}>
              <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
                {/* rank */}
                <div style={{
                  width:26, height:26, borderRadius:8,
                  background: p.text, color: dark? '#0E0E10':'#FBF7EE',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:12, fontWeight:700, flexShrink:0,
                  fontFamily:'"Inter Tight", system-ui',
                }}>{i+1}</div>
                {/* body */}
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:10 }}>
                    <button onClick={()=> onPickStock(pk)} style={{
                      appearance:'none', background:'none', border:'none', padding:0,
                      cursor:'pointer', textAlign:'left', 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>
                    </button>
                    <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:22, fontWeight:600, color:p.text, lineHeight:1,
                        fontFamily:'"Inter Tight", system-ui',
                        fontVariantNumeric:'tabular-nums', letterSpacing:-0.6,
                        marginTop:2,
                      }}>{liveScore}</div>
                    </div>
                  </div>
                  {/* score bar */}
                  <div style={{
                    height:4, borderRadius:2, background: p.surface2,
                    overflow:'hidden', marginTop:8,
                  }}>
                    <div style={{
                      width: `${liveScore}%`, height:'100%',
                      background: p.inkUp, transition:'width 500ms ease',
                    }}/>
                  </div>
                  {/* signals */}
                  <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>
                  {/* PER / PBR chip */}
                  {(pk.per != null || pk.pbr != null) && (
                    <div style={{
                      marginTop:10, display:'flex', gap:6, flexWrap:'wrap',
                    }}>
                      {pk.per != null && (
                        <span style={{
                          fontFamily:'"JetBrains Mono", monospace', fontSize:10.5,
                          padding:'3px 8px', borderRadius:6,
                          background: p.surface2, color:p.text, letterSpacing:'0.04em',
                        }}>PER <span style={{fontWeight:700}}>{pk.per.toFixed(1)}</span></span>
                      )}
                      {pk.pbr != null && (
                        <span style={{
                          fontFamily:'"JetBrains Mono", monospace', fontSize:10.5,
                          padding:'3px 8px', borderRadius:6,
                          background: p.surface2, color:p.text, letterSpacing:'0.04em',
                        }}>PBR <span style={{fontWeight:700}}>{pk.pbr.toFixed(2)}</span></span>
                      )}
                      {pk.sector && (
                        <span style={{
                          fontFamily:'"JetBrains Mono", monospace', fontSize:10.5,
                          padding:'3px 8px', borderRadius:6,
                          background:'transparent', border:`0.5px solid ${p.line2}`,
                          color:p.muted,
                        }}>{pk.sector}</span>
                      )}
                    </div>
                  )}
                  {/* thesis */}
                  <div style={{
                    marginTop:10, fontSize:12, color:p.muted,
                    lineHeight:1.45, letterSpacing:-0.1, textWrap:'pretty',
                  }}>{thesis}</div>
                  {/* CCI 시그널 */}
                  {pk.cci!=null && <CCIBadge cci={pk.cci}/>}
                  {/* target */}
                  <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)}% {lang==='ko'?'여력':'upside'} · {pk.horizon}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ padding:'12px 14px 0' }}>
        <button onClick={onMore} style={{
          appearance:'none', border:`0.5px solid ${p.line2}`,
          background:'transparent', color:p.text, cursor:'pointer',
          width:'100%', padding:'12px 14px', borderRadius:12,
          fontFamily:'"Inter Tight", system-ui',
          fontSize:13, fontWeight:500, letterSpacing:-0.1,
          display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6,
        }}>
          {lang==='ko'? 'AI 추천 더보기':'More AI picks'}
          <svg width="11" height="11" viewBox="0 0 11 11">
            <path d="M3 2L7 5.5L3 9" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </>
  );
}

// ============ 월간 주요 일정 ============
function MonthCalendar() {
  const { dark, lang } = useTheme();
  const p = palette(dark);
  const [region, setRegion] = React.useState('ALL'); // ALL | US | KR

  const filtered = CALENDAR.filter(e =>
    (region==='ALL' || e.region===region) && e.stars >= 5
  );

  // group by date
  const grouped = {};
  filtered.forEach(e => {
    (grouped[e.date] = grouped[e.date] || []).push(e);
  });
  const dates = Object.keys(grouped).sort();

  const flag = (r) => r === 'US'
    ? <svg width="14" height="10" viewBox="0 0 14 10" style={{ borderRadius:1.5, overflow:'hidden', flexShrink:0 }}>
        <rect width="14" height="10" fill={dark?'#4A4A54':'#D6D1C2'}/>
        {[0.5,2.5,4.5,6.5,8.5].map(y => <rect key={y} x="0" y={y} width="14" height="1" fill={dark?'#2A2D3A':'#8B8575'}/>)}
        <rect width="6" height="5" fill={dark?'#2A2D3A':'#8B8575'}/>
      </svg>
    : (
      // 한국: 태극 문양 (원 안에 S자 곡선으로 음양) + 좌우 괘 라인
      <svg width="14" height="10" viewBox="0 0 14 10" style={{ borderRadius:1.5, overflow:'hidden', flexShrink:0 }}>
        <rect width="14" height="10" fill={dark?'#3A3D4A':'#EFE8D8'}/>
        {/* 좌측 괘 3줄 */}
        <g stroke={dark?'#8B8575':'#4A4A54'} strokeWidth="0.6">
          <line x1="0.8" x2="3" y1="3"   y2="3"/>
          <line x1="0.8" x2="3" y1="5"   y2="5"/>
          <line x1="0.8" x2="3" y1="7"   y2="7"/>
        </g>
        {/* 태극 (음양 곡선) */}
        <g transform="translate(7,5)">
          <circle r="2.2" fill="none" stroke={dark?'#8B8575':'#4A4A54'} strokeWidth="0.5"/>
          <path d="M 0,-2.2 A 1.1,1.1 0 0 1 0,0 A 1.1,1.1 0 0 0 0,2.2 A 2.2,2.2 0 0 1 0,-2.2 Z"
            fill={dark?'#4A90C2':'#2E6FA6'}/>
          <path d="M 0,-2.2 A 1.1,1.1 0 0 0 0,0 A 1.1,1.1 0 0 1 0,2.2 A 2.2,2.2 0 0 0 0,-2.2 Z"
            fill={dark?'#D95A4A':'#C23E2E'}/>
        </g>
        {/* 우측 괘 3줄 */}
        <g stroke={dark?'#8B8575':'#4A4A54'} strokeWidth="0.6">
          <line x1="11" x2="13.2" y1="3"   y2="3"/>
          <line x1="11" x2="13.2" y1="5"   y2="5"/>
          <line x1="11" x2="13.2" y1="7"   y2="7"/>
        </g>
      </svg>
    );

  return (
    <>
      <SectionLabel
        kicker={lang==='ko'?'일정':'CALENDAR'}
        title={lang==='ko'?'주요 경제지표 · 1개월':'Key Events · 1 Month'}
        right={lang==='ko'? `${filtered.length}건 · ★5` : `${filtered.length} · ★5`}
      />
      <Card padded={false}>
        {/* filters */}
        <div style={{ padding:'12px 14px 10px', display:'flex', gap:8, flexWrap:'wrap' }}>
          <div style={{
            display:'flex', gap:3, background:p.surface2,
            borderRadius:9, padding:3,
          }}>
            {[
              ['ALL', lang==='ko'?'전체':'ALL'],
              ['US',  'US'],
              ['KR',  'KR'],
            ].map(([k,l])=>(
              <button key={k} onClick={()=>setRegion(k)} style={{
                appearance:'none', border:'none', cursor:'pointer',
                padding:'5px 10px', borderRadius:7,
                fontSize:10.5, fontWeight: region===k?600:500,
                color: region===k? p.text : p.muted,
                background: region===k? p.surface : 'transparent',
                boxShadow: region===k? (dark?'0 0 0 1px rgba(255,255,255,0.05)':'0 1px 2px rgba(0,0,0,0.04)') : 'none',
                fontFamily:'"Inter Tight", system-ui',
              }}>{l}</button>
            ))}
          </div>
          <div style={{
            display:'inline-flex', alignItems:'center', padding:'5px 10px',
            background:p.surface2, borderRadius:9,
            fontFamily:'"Inter Tight", system-ui',
            fontSize:10.5, fontWeight:600, color:p.text, letterSpacing:-0.05,
          }}>
            <span style={{ letterSpacing:'0.06em', color:p.muted, marginRight:6, fontSize:9.5 }}>
              {lang==='ko'?'중요도':'IMPORTANCE'}
            </span>
            ★★★★★
          </div>
        </div>

        {dates.map(date => (
          <div key={date} style={{ borderTop:`0.5px solid ${p.line}` }}>
            <div style={{
              padding:'8px 16px 4px', display:'flex', gap:8, alignItems:'baseline',
              fontFamily:'"JetBrains Mono", monospace',
            }}>
              <div style={{
                fontSize:12, color:p.text, fontWeight:600,
                letterSpacing:-0.1,
              }}>{date}</div>
              <div style={{
                fontSize:9, color:p.faint, letterSpacing:'0.14em',
              }}>{grouped[date][0].wd.toUpperCase()}</div>
            </div>
            {grouped[date].map((e,i)=>(
              <div key={i} style={{
                padding:'8px 16px 10px',
                display:'grid', gridTemplateColumns:'16px 1fr auto',
                gap:10, alignItems:'center',
              }}>
                <div>{flag(e.region)}</div>
                <div style={{
                  fontSize:13, color:p.text, letterSpacing:-0.2, lineHeight:1.35,
                }}>{e.evt}</div>
                <div style={{
                  display:'flex', gap:1,
                  fontSize:10, color: e.stars>=5? p.inkDown : p.text,
                  letterSpacing:-0.5,
                }}>{'★'.repeat(e.stars)}<span style={{ color:p.line2 }}>{'★'.repeat(5-e.stars)}</span></div>
              </div>
            ))}
          </div>
        ))}
        {dates.length === 0 && (
          <div style={{
            padding:'30px 16px', textAlign:'center', color:p.faint,
            fontSize:12,
          }}>{lang==='ko'?'조건에 맞는 일정 없음':'No events match filter'}</div>
        )}
      </Card>
    </>
  );
}

Object.assign(window, { PERSection, AIPicks, MonthCalendar, CCIBadge, cciSignal });
