// splash-screens.jsx
// 4가지 스플래시 스크린 컨셉. 모두 기존 앱 팔레트(웜 샌드 베이스)를 사용.
// iOS 프레임 내부에 채워지는 내용만 담당. 6초 루프 애니메이션.

// 팔레트 (기존 primitives.jsx와 동일)
const SPLASH_P = {
  bg:        '#F4EEE3',
  surface:   '#FBF7EE',
  surface2:  '#EFE8D8',
  line:      'rgba(30,35,50,0.08)',
  line2:     'rgba(30,35,50,0.14)',
  text:      '#1E2332',
  muted:     'rgba(30,35,50,0.60)',
  faint:     'rgba(30,35,50,0.36)',
  inkUp:     '#1F8C78',
  inkDown:   '#C45A48',
  accent:    '#8B6F3A',
};

const SANS  = '"Inter Tight", -apple-system, system-ui, sans-serif';
const SERIF = '"Fraunces", Georgia, serif';
const MONO  = '"JetBrains Mono", ui-monospace, monospace';

// 공용 유틸: 시간 포맷
function useTicker(intervalMs = 1000){
  const [t, setT] = React.useState(Date.now());
  React.useEffect(()=>{
    const id = setInterval(()=>setT(Date.now()), intervalMs);
    return ()=>clearInterval(id);
  },[intervalMs]);
  return t;
}

// ────────────────────────────────────────────────
// 공통: 상태바 아래 안전영역을 고려한 풀-스크린 래퍼
// ────────────────────────────────────────────────
function SplashShell({ children, bg = SPLASH_P.bg, style = {} }){
  return (
    <div style={{
      width:'100%', height:'100%', background: bg,
      position:'relative', overflow:'hidden',
      fontFamily: SANS, color: SPLASH_P.text,
      ...style,
    }}>{children}</div>
  );
}

// 앱 워드마크 — 간단한 모노그램 + 타이포 로고
function Wordmark({ size = 1, dark=false }){
  const c = dark ? '#F3EEE4' : SPLASH_P.text;
  const muted = dark ? 'rgba(243,238,228,0.55)' : SPLASH_P.muted;
  const s = (n)=> n*size;
  return (
    <div style={{ display:'inline-flex', alignItems:'center', gap: s(12) }}>
      <svg width={s(32)} height={s(32)} viewBox="0 0 32 32">
        <rect x="1" y="1" width="30" height="30" rx="7" fill="none" stroke={c} strokeWidth="1.2"/>
        <path d="M7 22 L13 14 L17 18 L25 8" fill="none" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="25" cy="8" r="1.8" fill={c}/>
      </svg>
      <div style={{ display:'flex', flexDirection:'column', lineHeight:1 }}>
        <div style={{
          fontFamily: SERIF, fontWeight:500, fontSize: s(22),
          letterSpacing:-0.4, color: c,
        }}>Daily Market</div>
        <div style={{
          fontFamily: MONO, fontSize: s(9.5), letterSpacing:'0.22em',
          color: muted, marginTop: s(4), textTransform:'uppercase',
        }}>Report · Since 2026</div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 1) TICKER TAPE — 가로 흐르는 시세 + 중앙 워드마크
// ───────────────────────────────────────────────────────────────
function SplashTicker(){
  const tickers = [
    { s:'KOSPI',   p:'2,687.34', d:'+0.42%', up:true },
    { s:'KOSDAQ',  p:'  872.15', d:'-0.18%', up:false },
    { s:'S&P 500', p:'5,483.20', d:'+0.71%', up:true },
    { s:'NASDAQ',  p:'17,842.9', d:'+1.12%', up:true },
    { s:'DOW',     p:'42,135.5', d:'-0.22%', up:false },
    { s:'USD/KRW', p:'1,383.20', d:'-0.15%', up:false },
    { s:'WTI',     p:'   78.42', d:'+0.88%', up:true },
    { s:'GOLD',    p:'2,341.10', d:'+0.34%', up:true },
    { s:'BTC',     p:'68,412.0', d:'-2.11%', up:false },
    { s:'10Y',     p:'   4.287', d:'+0.012', up:true },
  ];
  const row = (
    <div style={{ display:'flex', gap:36, flexShrink:0, paddingRight:36 }}>
      {tickers.map((t,i)=>(
        <div key={i} style={{
          display:'flex', alignItems:'baseline', gap:10,
          fontFamily: MONO, fontSize:12, letterSpacing:-0.1,
          whiteSpace:'nowrap',
        }}>
          <span style={{ color: SPLASH_P.text, fontWeight:500 }}>{t.s}</span>
          <span style={{ color: SPLASH_P.muted, fontVariantNumeric:'tabular-nums' }}>{t.p}</span>
          <span style={{ color: t.up ? SPLASH_P.inkUp : SPLASH_P.inkDown }}>
            {t.up?'▲':'▼'} {t.d}
          </span>
        </div>
      ))}
    </div>
  );

  // 진행바
  const [pct, setPct] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      const t = ((Date.now()-start) % 6000)/6000;
      setPct(t*100);
    }, 50);
    return ()=>clearInterval(id);
  },[]);

  return (
    <SplashShell>
      <style>{`
        @keyframes tickerSlide { from{transform:translateX(0)} to{transform:translateX(-50%)} }
      `}</style>
      {/* 상단 티커 */}
      <div style={{
        position:'absolute', top:90, left:0, right:0,
        borderTop:`0.5px solid ${SPLASH_P.line2}`,
        borderBottom:`0.5px solid ${SPLASH_P.line2}`,
        padding:'12px 0', overflow:'hidden',
        background: SPLASH_P.surface,
      }}>
        <div style={{
          display:'flex', width:'max-content',
          animation:'tickerSlide 30s linear infinite',
        }}>
          {row}{row}
        </div>
      </div>

      {/* 하단 티커 (역방향) */}
      <div style={{
        position:'absolute', bottom:140, left:0, right:0,
        borderTop:`0.5px solid ${SPLASH_P.line2}`,
        borderBottom:`0.5px solid ${SPLASH_P.line2}`,
        padding:'12px 0', overflow:'hidden',
        background: SPLASH_P.surface,
      }}>
        <div style={{
          display:'flex', width:'max-content',
          animation:'tickerSlide 42s linear infinite reverse',
        }}>
          {row}{row}
        </div>
      </div>

      {/* 중앙 워드마크 */}
      <div style={{
        position:'absolute', inset:0,
        display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'center',
        gap: 32,
      }}>
        <Wordmark size={1.15}/>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.28em',
          color: SPLASH_P.faint, textTransform:'uppercase',
        }}>Live Market Data · Sync</div>
      </div>

      {/* 진행바 */}
      <div style={{
        position:'absolute', bottom:72, left:40, right:40,
        height:1, background: SPLASH_P.line,
      }}>
        <div style={{
          height:'100%', width:`${pct}%`,
          background: SPLASH_P.text, transition:'width 50ms linear',
        }}/>
      </div>
      <div style={{
        position:'absolute', bottom:80, left:40, right:40,
        display:'flex', justifyContent:'space-between',
        fontFamily: MONO, fontSize:9, letterSpacing:'0.18em',
        color: SPLASH_P.faint, textTransform:'uppercase',
      }}>
        <span>Connecting</span>
        <span>{String(Math.round(pct)).padStart(2,'0')}%</span>
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 2) CANDLESTICK GROW — 캔들차트가 왼→오 그려지며 쌓이는 로딩
// ───────────────────────────────────────────────────────────────
function SplashCandle(){
  const N = 32;
  // 시드 고정된 캔들 데이터
  const candles = React.useMemo(()=>{
    let rng = 42;
    const rand = ()=>{ rng = (rng*9301+49297)%233280; return rng/233280; };
    let price = 100;
    const arr = [];
    for(let i=0;i<N;i++){
      const dir = (rand()>0.46) ? 1 : -1;
      const open = price;
      const chg = (rand()*2.4) * dir;
      const close = Math.max(20, open + chg);
      const high = Math.max(open, close) + rand()*1.5;
      const low  = Math.min(open, close) - rand()*1.5;
      arr.push({ open, close, high, low, up: close>=open });
      price = close;
    }
    return arr;
  },[]);

  const W = 340, H = 260;
  const padX = 20, padY = 10;
  const max = Math.max(...candles.map(c=>c.high));
  const min = Math.min(...candles.map(c=>c.low));
  const rng = max-min;
  const x = (i)=> padX + (i/(N-1))*(W - padX*2);
  const y = (v)=> padY + (1 - (v-min)/rng)*(H - padY*2);
  const cw = (W - padX*2)/N * 0.55;

  // 애니메이션 진행
  const [idx, setIdx] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      const t = ((Date.now()-start) % 6000)/6000;
      setIdx(Math.floor(t*N));
    }, 40);
    return ()=>clearInterval(id);
  },[]);

  const currentPrice = candles[Math.min(N-1, idx)]?.close ?? candles[0].close;
  const priceDisplay = (50 + currentPrice*15).toFixed(2);

  return (
    <SplashShell>
      {/* 상단: 심볼 + 가격 */}
      <div style={{
        position:'absolute', top:72, left:24, right:24,
        display:'flex', justifyContent:'space-between', alignItems:'flex-start',
      }}>
        <div>
          <div style={{ fontFamily: MONO, fontSize:10, letterSpacing:'0.22em',
              color: SPLASH_P.faint, textTransform:'uppercase' }}>Market Open</div>
          <div style={{ fontFamily: SERIF, fontSize:34, fontWeight:500,
              letterSpacing:-0.6, color: SPLASH_P.text, marginTop:4 }}>
            KOSPI
          </div>
        </div>
        <div style={{ textAlign:'right' }}>
          <div style={{
            fontFamily: MONO, fontSize:22, fontVariantNumeric:'tabular-nums',
            color: SPLASH_P.text, letterSpacing:-0.5, fontWeight:500,
          }}>{priceDisplay}</div>
          <div style={{
            fontFamily: MONO, fontSize:11, color: SPLASH_P.inkUp, marginTop:4,
          }}>▲ +0.42% +11.34</div>
        </div>
      </div>

      {/* 중앙 차트 */}
      <div style={{
        position:'absolute', top:190, left:'50%',
        transform:'translateX(-50%)',
      }}>
        <svg width={W} height={H}>
          {/* 격자 라인 */}
          {[0,1,2,3,4].map(i=>(
            <line key={i} x1={padX} x2={W-padX}
              y1={padY + (i/4)*(H-padY*2)}
              y2={padY + (i/4)*(H-padY*2)}
              stroke={SPLASH_P.line} strokeWidth="0.5" strokeDasharray="2 3"/>
          ))}
          {/* 캔들 */}
          {candles.slice(0, idx+1).map((c,i)=>{
            const cx = x(i);
            const col = c.up ? SPLASH_P.inkUp : SPLASH_P.inkDown;
            const yO = y(c.open), yC = y(c.close);
            const yT = Math.min(yO, yC), yB = Math.max(yO, yC);
            return (
              <g key={i} style={{
                opacity: i === idx ? 0 : 1,
                animation: i === idx ? 'candleIn 0.2s ease-out forwards' : 'none',
              }}>
                {/* 심지 */}
                <line x1={cx} x2={cx} y1={y(c.high)} y2={y(c.low)}
                  stroke={col} strokeWidth="0.8"/>
                {/* 몸통 */}
                <rect x={cx-cw/2} y={yT} width={cw} height={Math.max(1, yB-yT)}
                  fill={c.up ? col : 'transparent'}
                  stroke={col} strokeWidth="0.8"/>
              </g>
            );
          })}
          {/* 가격 라인 (현재점까지) */}
          {idx > 0 && (
            <path
              d={candles.slice(0, idx+1).map((c,i)=>
                `${i?'L':'M'}${x(i).toFixed(1)},${y(c.close).toFixed(1)}`
              ).join(' ')}
              fill="none" stroke={SPLASH_P.text} strokeWidth="0.8"
              strokeDasharray="2 2" opacity="0.3"
            />
          )}
        </svg>
        <style>{`@keyframes candleIn { from { opacity:0; transform: translateY(4px) } to { opacity:1; transform: translateY(0) } }`}</style>
      </div>

      {/* 하단 로고 + 로딩 상태 */}
      <div style={{
        position:'absolute', bottom:60, left:0, right:0,
        display:'flex', flexDirection:'column', alignItems:'center', gap:14,
      }}>
        <Wordmark size={0.8}/>
        <div style={{
          fontFamily: MONO, fontSize:9.5, letterSpacing:'0.24em',
          color: SPLASH_P.faint, textTransform:'uppercase',
        }}>
          Rendering Chart · {String(Math.round((idx/N)*100)).padStart(2,'0')}%
        </div>
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 3) DAILY BRIEF — 에디토리얼 + 투자 격언
// ───────────────────────────────────────────────────────────────
function SplashBrief(){
  const now = useTicker(1000);
  const d = new Date(now);
  const dateStr = d.toLocaleDateString('ko-KR', {
    year:'numeric', month:'long', day:'numeric', weekday:'long'
  });
  const timeStr = d.toLocaleTimeString('en-US', { hour12:false });

  const quotes = [
    { text:'The stock market is a device for transferring money from the impatient to the patient.',
      ko:'주식시장은 성급한 사람으로부터 인내심 있는 사람에게 돈이 이전되는 장치다.',
      author:'W. Buffett' },
    { text:'Risk comes from not knowing what you are doing.',
      ko:'리스크는 자신이 무엇을 하는지 모를 때 발생한다.',
      author:'W. Buffett' },
    { text:'The four most dangerous words in investing are: this time it\u2019s different.',
      ko:'투자에서 가장 위험한 네 마디는 "이번엔 다르다"이다.',
      author:'J. Templeton' },
  ];
  const [qi, setQi] = React.useState(0);
  React.useEffect(()=>{
    const id = setInterval(()=> setQi(i => (i+1) % quotes.length), 3000);
    return ()=>clearInterval(id);
  },[]);
  const q = quotes[qi];

  // 진행 도트
  const [dot, setDot] = React.useState(0);
  React.useEffect(()=>{
    const id = setInterval(()=> setDot(d=> (d+1)%4), 400);
    return ()=>clearInterval(id);
  },[]);

  return (
    <SplashShell>
      {/* 헤더: 매스트헤드 */}
      <div style={{
        position:'absolute', top:70, left:24, right:24,
        paddingBottom:18, borderBottom:`0.5px solid ${SPLASH_P.line2}`,
      }}>
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'baseline',
          fontFamily: MONO, fontSize:9, letterSpacing:'0.22em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginBottom:12,
        }}>
          <span>Vol. III · No. 124</span>
          <span>{timeStr} KST</span>
        </div>
        <div style={{
          fontFamily: SERIF, fontSize:44, fontWeight:400,
          letterSpacing:-1.2, lineHeight:0.95, color: SPLASH_P.text,
        }}>
          Daily<br/>
          <span style={{ fontStyle:'italic', fontWeight:300 }}>Market Report</span>
        </div>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.18em',
          color: SPLASH_P.muted, marginTop:14, textTransform:'uppercase',
        }}>{dateStr}</div>
      </div>

      {/* 인용구 영역 */}
      <div style={{
        position:'absolute', top:340, left:24, right:24, bottom:140,
        display:'flex', flexDirection:'column', justifyContent:'center',
      }}>
        <div style={{
          fontFamily: SERIF, fontSize:12, letterSpacing:'0.18em',
          color: SPLASH_P.accent, textTransform:'uppercase',
          marginBottom:16,
        }}>— On Investing</div>
        <div key={qi} style={{
          fontFamily: SERIF, fontSize:20, fontWeight:400,
          lineHeight:1.35, color: SPLASH_P.text,
          fontStyle:'italic', letterSpacing:-0.3,
          animation:'briefFade 0.6s ease-out',
        }}>
          &ldquo;{q.text}&rdquo;
        </div>
        <div style={{
          fontFamily: SANS, fontSize:13, color: SPLASH_P.muted,
          marginTop:14, letterSpacing:-0.1,
        }}>{q.ko}</div>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.2em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginTop:20,
        }}>— {q.author}</div>
        <style>{`@keyframes briefFade { from{opacity:0; transform:translateY(6px)} to{opacity:1; transform:translateY(0)} }`}</style>
      </div>

      {/* 하단: 로딩 인디케이터 */}
      <div style={{
        position:'absolute', bottom:64, left:24, right:24,
        display:'flex', justifyContent:'space-between', alignItems:'center',
      }}>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.22em',
          color: SPLASH_P.faint, textTransform:'uppercase',
        }}>Preparing Report{'.'.repeat(dot)}</div>
        <Wordmark size={0.55}/>
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 4) DATA SYNC — 숫자 카운트업 + 단계별 진행 상태
// ───────────────────────────────────────────────────────────────
function SplashSync(){
  const now = useTicker(1000);
  const d = new Date(now);
  const timeStr = d.toLocaleTimeString('en-US', { hour12:false });

  const targets = [
    { label:'KOSPI',      target: 2687.34, d:'+0.42%', up:true },
    { label:'S&P 500',    target: 5483.20, d:'+0.71%', up:true },
    { label:'NASDAQ',     target:17842.90, d:'+1.12%', up:true },
    { label:'USD/KRW',    target: 1383.20, d:'-0.15%', up:false },
    { label:'BTC/USD',    target:68412.00, d:'-2.11%', up:false },
  ];

  const steps = [
    'Connecting to market feed',
    'Fetching index snapshots',
    'Syncing sector data',
    'Loading AI picks',
    'Preparing report',
  ];

  const [progress, setProgress] = React.useState(0); // 0..1
  const [step, setStep] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      const t = Math.min(1, (Date.now()-start)/5500);
      setProgress(t);
      setStep(Math.min(steps.length-1, Math.floor(t*steps.length)));
      if(t>=1){
        // 루프
      }
    }, 40);
    return ()=>clearInterval(id);
  },[]);

  // 숫자 카운트업 (ease-out)
  const ease = 1 - Math.pow(1-progress, 3);

  return (
    <SplashShell>
      {/* 상단: 타이틀 */}
      <div style={{
        position:'absolute', top:72, left:24, right:24,
      }}>
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'center',
          marginBottom:18,
        }}>
          <Wordmark size={0.75}/>
          <div style={{
            fontFamily: MONO, fontSize:10, letterSpacing:'0.22em',
            color: SPLASH_P.faint, textTransform:'uppercase',
          }}>{timeStr}</div>
        </div>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.24em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginTop:28,
        }}>Market Data · Live</div>
        <div style={{
          fontFamily: SERIF, fontSize:30, fontWeight:400,
          letterSpacing:-0.6, lineHeight:1.1, color: SPLASH_P.text, marginTop:6,
        }}>
          Syncing the<br/>
          <span style={{ fontStyle:'italic' }}>global markets</span>
        </div>
      </div>

      {/* 지수 카운트업 테이블 */}
      <div style={{
        position:'absolute', top:280, left:24, right:24,
      }}>
        {targets.map((t, i)=>{
          const val = (t.target * ease).toFixed(2);
          const done = progress > (i+1)/targets.length * 0.9;
          return (
            <div key={i} style={{
              display:'flex', alignItems:'center',
              padding:'11px 0',
              borderBottom: i < targets.length-1 ? `0.5px solid ${SPLASH_P.line}` : 'none',
              opacity: done ? 1 : 0.9,
            }}>
              <div style={{
                width:10, height:10, borderRadius:'50%',
                background: done ? SPLASH_P.inkUp : 'transparent',
                border: done ? 'none' : `1px solid ${SPLASH_P.line2}`,
                marginRight:14, flexShrink:0,
                transition:'all 0.3s ease',
              }}/>
              <div style={{
                flex:1, fontFamily: MONO, fontSize:12,
                color: SPLASH_P.text, fontWeight:500,
              }}>{t.label}</div>
              <div style={{
                fontFamily: MONO, fontSize:13,
                fontVariantNumeric:'tabular-nums',
                color: SPLASH_P.text,
                letterSpacing:-0.2,
                marginRight:12,
              }}>{Number(val).toLocaleString('en-US',{minimumFractionDigits:2, maximumFractionDigits:2})}</div>
              <div style={{
                fontFamily: MONO, fontSize:11, minWidth:56, textAlign:'right',
                color: done ? (t.up ? SPLASH_P.inkUp : SPLASH_P.inkDown) : SPLASH_P.faint,
              }}>
                {done ? `${t.up?'▲':'▼'} ${t.d}` : '——'}
              </div>
            </div>
          );
        })}
      </div>

      {/* 하단: 진행 상태 + 바 */}
      <div style={{
        position:'absolute', bottom:60, left:24, right:24,
      }}>
        <div style={{
          display:'flex', justifyContent:'space-between',
          fontFamily: MONO, fontSize:10, letterSpacing:'0.18em',
          color: SPLASH_P.muted, textTransform:'uppercase', marginBottom:10,
        }}>
          <span>{steps[step]}</span>
          <span>{String(Math.round(progress*100)).padStart(3,'0')}%</span>
        </div>
        <div style={{
          height:2, background: SPLASH_P.line,
          borderRadius:2, overflow:'hidden',
        }}>
          <div style={{
            height:'100%', width:`${progress*100}%`,
            background: SPLASH_P.text, transition:'width 80ms linear',
          }}/>
        </div>
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 5) HEARTBEAT — 시세 펄스 + 큰 숫자 + 고요한 워드마크 (보너스)
// ───────────────────────────────────────────────────────────────
function SplashPulse(){
  // 펄스 루프: 0..1 반복
  const [phase, setPhase] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      setPhase(((Date.now()-start) % 2400)/2400);
    }, 30);
    return ()=>clearInterval(id);
  },[]);

  // 하트비트 파형 (ECG 스타일)
  const W = 360, H = 80;
  const beats = 60; // points
  const points = [];
  for(let i=0;i<beats;i++){
    const t = i/beats;
    // 두 개의 피크
    const p1 = t - 0.25, p2 = t - 0.55;
    const peak1 = Math.exp(-p1*p1*400) * (p1>0?-1:1) * 30;
    const peak2 = Math.exp(-p2*p2*500) * (p2>0?1:-1) * 18;
    const y = H/2 - peak1 - peak2;
    points.push([ (i/(beats-1))*W, y ]);
  }
  const path = points.map((p,i)=>`${i?'L':'M'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');

  // 진행되는 헤드 포인트
  const headIdx = Math.floor(phase * beats);
  const head = points[Math.min(beats-1, headIdx)];

  const pulse = 0.5 + 0.5*Math.sin(phase*Math.PI*2);

  return (
    <SplashShell>
      {/* 상단 */}
      <div style={{
        position:'absolute', top:80, left:0, right:0,
        display:'flex', justifyContent:'center',
      }}>
        <Wordmark size={0.85}/>
      </div>

      {/* 중앙: 큰 숫자 + 펄스 */}
      <div style={{
        position:'absolute', inset:0,
        display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'center',
        gap:24,
      }}>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.28em',
          color: SPLASH_P.faint, textTransform:'uppercase',
        }}>Market Pulse</div>

        <div style={{
          fontFamily: SERIF, fontSize:72, fontWeight:300,
          letterSpacing:-2, color: SPLASH_P.text, lineHeight:1,
          fontVariantNumeric:'tabular-nums',
          opacity: 0.85 + pulse*0.15,
        }}>
          2,687<span style={{ color: SPLASH_P.faint }}>.34</span>
        </div>

        <div style={{
          fontFamily: MONO, fontSize:13, color: SPLASH_P.inkUp,
          letterSpacing:-0.1,
        }}>▲ +11.34 · +0.42%</div>

        {/* 파형 */}
        <div style={{ marginTop:8 }}>
          <svg width={W*0.85} height={H} viewBox={`0 0 ${W} ${H}`}>
            <defs>
              <linearGradient id="pulseGrad" x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor={SPLASH_P.text} stopOpacity="0.15"/>
                <stop offset={`${phase*100}%`} stopColor={SPLASH_P.text} stopOpacity="0.9"/>
                <stop offset={`${Math.min(100, phase*100+5)}%`} stopColor={SPLASH_P.text} stopOpacity="0.15"/>
                <stop offset="100%" stopColor={SPLASH_P.text} stopOpacity="0.15"/>
              </linearGradient>
            </defs>
            <line x1="0" x2={W} y1={H/2} y2={H/2}
              stroke={SPLASH_P.line} strokeWidth="0.5" strokeDasharray="2 3"/>
            <path d={path} fill="none" stroke="url(#pulseGrad)" strokeWidth="1.5"
              strokeLinecap="round" strokeLinejoin="round"/>
            {head && (
              <>
                <circle cx={head[0]} cy={head[1]} r={3} fill={SPLASH_P.inkUp}/>
                <circle cx={head[0]} cy={head[1]} r={8}
                  fill="none" stroke={SPLASH_P.inkUp} strokeWidth="0.8"
                  opacity={1-pulse}/>
              </>
            )}
          </svg>
        </div>
      </div>

      {/* 하단 로딩 텍스트 */}
      <div style={{
        position:'absolute', bottom:72, left:0, right:0,
        textAlign:'center',
        fontFamily: MONO, fontSize:10, letterSpacing:'0.24em',
        color: SPLASH_P.faint, textTransform:'uppercase',
      }}>
        Listening to the market
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 6) GRID — 서브틀한 숫자 그리드 (매트릭스 느낌이 아닌, 거래소 데이터 테이블)
// ───────────────────────────────────────────────────────────────
function SplashGrid(){
  const cols = 4, rows = 9;
  const syms = ['KOSPI','KOSDAQ','S&P','NASDAQ','DOW','NIKKEI','HSI','FTSE','DAX','CAC','USD','EUR','JPY','CNY','WTI','GOLD','SILV','BTC','ETH','10Y','2Y','TLT','VIX','DXY'];
  // 셀 데이터
  const cells = React.useMemo(()=>{
    let rng = 137;
    const rand = ()=>{ rng = (rng*9301+49297)%233280; return rng/233280; };
    const arr = [];
    for(let i=0;i<rows*cols;i++){
      const s = syms[i % syms.length];
      const up = rand()>0.42;
      const val = (Math.pow(10, 1+Math.floor(rand()*4)) * (1+rand())).toFixed(2);
      const d = (rand()*2.5).toFixed(2);
      arr.push({ s, val, d, up, delay: rand()*1.5 });
    }
    return arr;
  },[]);

  const [t, setT] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      setT(((Date.now()-start) % 6000)/6000);
    },40);
    return ()=>clearInterval(id);
  },[]);

  return (
    <SplashShell>
      {/* 상단 워드마크 */}
      <div style={{
        position:'absolute', top:78, left:24, right:24,
        display:'flex', justifyContent:'space-between', alignItems:'center',
      }}>
        <Wordmark size={0.75}/>
        <div style={{
          width:6, height:6, borderRadius:'50%',
          background: SPLASH_P.inkUp,
          boxShadow:`0 0 0 4px ${SPLASH_P.inkUp}22`,
          animation:'pulse 1.2s ease-in-out infinite',
        }}/>
      </div>
      <style>{`
        @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes cellIn { from{opacity:0; transform:translateY(3px)} to{opacity:1; transform:translateY(0)} }
      `}</style>

      <div style={{
        position:'absolute', top:135, left:24, right:24,
        fontFamily: MONO, fontSize:9.5, letterSpacing:'0.22em',
        color: SPLASH_P.faint, textTransform:'uppercase',
        paddingBottom:10, borderBottom:`0.5px solid ${SPLASH_P.line2}`,
      }}>Global Markets · Initializing</div>

      {/* 셀 그리드 */}
      <div style={{
        position:'absolute', top:168, left:24, right:24, bottom:100,
        display:'grid',
        gridTemplateColumns:`repeat(${cols}, 1fr)`,
        gridAutoRows:'1fr',
        gap:0,
      }}>
        {cells.map((c, i)=>{
          const visible = t > c.delay/1.5;
          const col = c.up ? SPLASH_P.inkUp : SPLASH_P.inkDown;
          return (
            <div key={i} style={{
              borderRight: (i%cols < cols-1) ? `0.5px solid ${SPLASH_P.line}` : 'none',
              borderBottom: (Math.floor(i/cols) < rows-1) ? `0.5px solid ${SPLASH_P.line}` : 'none',
              padding:'6px 8px',
              display:'flex', flexDirection:'column', justifyContent:'center',
              opacity: visible ? 1 : 0,
              transition:'opacity 0.3s',
            }}>
              <div style={{
                fontFamily: MONO, fontSize:8.5, letterSpacing:'0.1em',
                color: SPLASH_P.faint, textTransform:'uppercase',
              }}>{c.s}</div>
              <div style={{
                fontFamily: MONO, fontSize:11, fontVariantNumeric:'tabular-nums',
                color: SPLASH_P.text, marginTop:2, letterSpacing:-0.2,
              }}>{c.val}</div>
              <div style={{
                fontFamily: MONO, fontSize:9, color: col, marginTop:1,
              }}>{c.up?'▲':'▼'}{c.d}%</div>
            </div>
          );
        })}
      </div>

      {/* 하단 진행 */}
      <div style={{
        position:'absolute', bottom:60, left:24, right:24,
      }}>
        <div style={{
          display:'flex', justifyContent:'space-between',
          fontFamily: MONO, fontSize:9, letterSpacing:'0.22em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginBottom:8,
        }}>
          <span>Loading {Math.round(t*rows*cols)} / {rows*cols}</span>
          <span>{String(Math.round(t*100)).padStart(2,'0')}%</span>
        </div>
      </div>
    </SplashShell>
  );
}

// ───────────────────────────────────────────────────────────────
// 7) BRIEF + TICKER — 에디토리얼 매스트헤드 + 격언 + 하단 흐르는 시세
// Row A #1(Ticker Tape) + #3(Daily Brief) 하이브리드
// ───────────────────────────────────────────────────────────────
function SplashBriefTicker(){
  const now = useTicker(1000);
  const d = new Date(now);
  const dateStr = d.toLocaleDateString('ko-KR', {
    year:'numeric', month:'long', day:'numeric', weekday:'long'
  });
  const timeStr = d.toLocaleTimeString('en-US', { hour12:false });

  const quotes = [
    { text:'The stock market is a device for transferring money from the impatient to the patient.',
      ko:'주식시장은 성급한 사람으로부터 인내심 있는 사람에게 돈이 이전되는 장치다.',
      author:'W. Buffett' },
    { text:'Risk comes from not knowing what you are doing.',
      ko:'리스크는 자신이 무엇을 하는지 모를 때 발생한다.',
      author:'W. Buffett' },
    { text:'The four most dangerous words in investing are: this time it\u2019s different.',
      ko:'투자에서 가장 위험한 네 마디는 "이번엔 다르다"이다.',
      author:'J. Templeton' },
  ];
  const [qi, setQi] = React.useState(0);
  React.useEffect(()=>{
    const id = setInterval(()=> setQi(i => (i+1) % quotes.length), 3000);
    return ()=>clearInterval(id);
  },[]);
  const q = quotes[qi];

  // 티커 데이터
  const tickers = [
    { s:'KOSPI',   p:'2,687.34', d:'+0.42%', up:true },
    { s:'KOSDAQ',  p:'872.15',   d:'-0.18%', up:false },
    { s:'S&P 500', p:'5,483.20', d:'+0.71%', up:true },
    { s:'NASDAQ',  p:'17,842.9', d:'+1.12%', up:true },
    { s:'DOW',     p:'42,135.5', d:'-0.22%', up:false },
    { s:'USD/KRW', p:'1,383.20', d:'-0.15%', up:false },
    { s:'WTI',     p:'78.42',    d:'+0.88%', up:true },
    { s:'GOLD',    p:'2,341.10', d:'+0.34%', up:true },
    { s:'BTC',     p:'68,412.0', d:'-2.11%', up:false },
    { s:'10Y',     p:'4.287',    d:'+0.012', up:true },
  ];
  const tickerRow = (
    <div style={{ display:'flex', gap:32, flexShrink:0, paddingRight:32 }}>
      {tickers.map((t,i)=>(
        <div key={i} style={{
          display:'flex', alignItems:'baseline', gap:8,
          fontFamily: MONO, fontSize:11, letterSpacing:-0.1,
          whiteSpace:'nowrap',
        }}>
          <span style={{ color: SPLASH_P.text, fontWeight:500 }}>{t.s}</span>
          <span style={{ color: SPLASH_P.muted, fontVariantNumeric:'tabular-nums' }}>{t.p}</span>
          <span style={{ color: t.up ? SPLASH_P.inkUp : SPLASH_P.inkDown }}>
            {t.up?'▲':'▼'} {t.d}
          </span>
        </div>
      ))}
    </div>
  );

  // 진행바
  const [pct, setPct] = React.useState(0);
  React.useEffect(()=>{
    const start = Date.now();
    const id = setInterval(()=>{
      const t = ((Date.now()-start) % 6000)/6000;
      setPct(t*100);
    }, 50);
    return ()=>clearInterval(id);
  },[]);

  return (
    <SplashShell>
      <style>{`
        @keyframes bt_slide { from{transform:translateX(0)} to{transform:translateX(-50%)} }
        @keyframes briefFade { from{opacity:0; transform:translateY(6px)} to{opacity:1; transform:translateY(0)} }
      `}</style>

      {/* 상단 티커 */}
      <div style={{
        position:'absolute', top:62, left:0, right:0,
        borderBottom:`0.5px solid ${SPLASH_P.line2}`,
        padding:'10px 0', overflow:'hidden',
        background: SPLASH_P.surface,
      }}>
        <div style={{
          display:'flex', width:'max-content',
          animation:'bt_slide 36s linear infinite',
        }}>
          {tickerRow}{tickerRow}
        </div>
      </div>

      {/* 매스트헤드 — 상단 1/3 중앙 정렬 */}
      <div style={{
        position:'absolute', top:0, left:0, right:0, height:'33.33%',
        paddingTop:110, paddingLeft:24, paddingRight:24,
        display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'center',
      }}>
        <div style={{
          display:'flex', gap:18, alignItems:'baseline',
          fontFamily: MONO, fontSize:9, letterSpacing:'0.22em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginBottom:12,
        }}>
          <span>Vol. III · No. 124</span>
          <span style={{ color: SPLASH_P.line2 }}>·</span>
          <span>{timeStr} KST</span>
        </div>
        <div style={{
          fontFamily: SERIF, fontSize:40, fontWeight:400,
          letterSpacing:-1, lineHeight:0.95, color: SPLASH_P.text,
          textAlign:'center',
        }}>
          Daily<br/>
          <span style={{ fontStyle:'italic', fontWeight:300 }}>Market Report</span>
        </div>
        <div style={{
          fontFamily: MONO, fontSize:9.5, letterSpacing:'0.18em',
          color: SPLASH_P.muted, marginTop:14, textTransform:'uppercase',
          textAlign:'center',
        }}>{dateStr}</div>
      </div>

      {/* 인용구 */}
      <div style={{
        position:'absolute', top:360, left:24, right:24, bottom:180,
        display:'flex', flexDirection:'column', justifyContent:'center',
      }}>
        <div style={{
          fontFamily: SERIF, fontSize:11, letterSpacing:'0.18em',
          color: SPLASH_P.accent, textTransform:'uppercase',
          marginBottom:14,
        }}>— On Investing</div>
        <div key={qi} style={{
          fontFamily: SERIF, fontSize:18, fontWeight:400,
          lineHeight:1.35, color: SPLASH_P.text,
          fontStyle:'italic', letterSpacing:-0.3,
          animation:'briefFade 0.6s ease-out',
        }}>
          &ldquo;{q.text}&rdquo;
        </div>
        <div style={{
          fontFamily: SANS, fontSize:12, color: SPLASH_P.muted,
          marginTop:12, letterSpacing:-0.1, lineHeight:1.45,
        }}>{q.ko}</div>
        <div style={{
          fontFamily: MONO, fontSize:10, letterSpacing:'0.2em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginTop:16,
        }}>— {q.author}</div>
      </div>

      {/* 하단 티커 (역방향) */}
      <div style={{
        position:'absolute', bottom:108, left:0, right:0,
        borderTop:`0.5px solid ${SPLASH_P.line2}`,
        borderBottom:`0.5px solid ${SPLASH_P.line2}`,
        padding:'10px 0', overflow:'hidden',
        background: SPLASH_P.surface,
      }}>
        <div style={{
          display:'flex', width:'max-content',
          animation:'bt_slide 48s linear infinite reverse',
        }}>
          {tickerRow}{tickerRow}
        </div>
      </div>

      {/* 진행바 */}
      <div style={{
        position:'absolute', bottom:56, left:24, right:24,
      }}>
        <div style={{
          display:'flex', justifyContent:'space-between',
          fontFamily: MONO, fontSize:9, letterSpacing:'0.2em',
          color: SPLASH_P.faint, textTransform:'uppercase', marginBottom:8,
        }}>
          <span>Preparing Report</span>
          <span>{String(Math.round(pct)).padStart(2,'0')}%</span>
        </div>
        <div style={{
          height:1, background: SPLASH_P.line,
        }}>
          <div style={{
            height:'100%', width:`${pct}%`,
            background: SPLASH_P.text, transition:'width 50ms linear',
          }}/>
        </div>
      </div>
    </SplashShell>
  );
}

Object.assign(window, {
  SplashTicker, SplashCandle, SplashBrief, SplashSync, SplashPulse, SplashGrid,
  SplashBriefTicker,
});
