import React from 'react';
import { useSearchParams } from 'react-router-dom';
import './_shell/tokens.css';
import './_shell/shell.css';
import useViewportMode from './_shell/useViewportMode';
import useSajuReading from './hooks/useSajuReading';
import BottomNav from './_shell/BottomNav';
import DesktopHeader from './_shell/DesktopHeader';
import Mascot from './_shell/Mascot';
import MascotBubble from './_shell/MascotBubble';
import GhostButton from './_shell/GhostButton';
import TodayMobile from './views/today.mobile.jsx';
import TodayDesktop from './views/today.desktop.jsx';
import sampleReading from './sampleReading';

export default function Today() {
  const mode = useViewportMode();
  const [params] = useSearchParams();
  const rid = params.get('rid');
  const ridNum = rid ? parseInt(rid, 10) : null;
  const { data, loading, error } = useSajuReading(ridNum);

  return (
    <div className="saju-v2">
      {mode === 'desktop' && <DesktopHeader />}
      {!rid && (mode === 'desktop'
        ? <TodayDesktop reading={sampleReading} />
        : <TodayMobile reading={sampleReading} />
      )}
      {rid && loading && <LoadingState />}
      {rid && error && <ErrorState />}
      {rid && data && (mode === 'desktop'
        ? <TodayDesktop reading={data} />
        : <TodayMobile reading={data} />
      )}
      {mode === 'mobile' && <BottomNav theme="ivory" />}
    </div>
  );
}

function LoadingState() {
  return (
    <main className="page paper-bg screen-in" style={{ padding: '60px 24px', textAlign: 'center' }}>
      <Mascot variant="thinking" size={160} style={{ margin: '0 auto 16px' }} />
      <MascotBubble tone="ivory" tail={false}
        text="호령이 오늘 운세를 살펴보고 있어요..."
        style={{ margin: '0 auto' }} />
    </main>
  );
}

function ErrorState() {
  return (
    <main className="page paper-bg screen-in" style={{ padding: '40px 24px', textAlign: 'center' }}>
      <Mascot variant="thinking" size={140} style={{ margin: '0 auto 16px' }} />
      <MascotBubble tone="ivory" tail={false}
        text="오늘 운세를 가져오지 못했어요."
        style={{ margin: '0 auto 20px' }} />
      <GhostButton color="#D4AF37" full={false} onClick={() => window.location.reload()}>다시 시도</GhostButton>
    </main>
  );
}
