// pwa-shell.jsx — Navigation host for 人生事業版圖 PWA
// Holds nav state + fetched data, mounts the active screen.
// In production this would be React Router; for a single-shell PWA
// a finite-state switch keeps the bundle tiny and is trivial to migrate.

const { useState, useEffect, useCallback } = React;

// 真實手機或已安裝 PWA → 跳過假手機框，全螢幕模式
const IS_REAL_MOBILE = (
  window.matchMedia('(display-mode: standalone)').matches ||
  /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
);

// ─── route map ─────────────────────────────────────────────
const ROUTES = ['welcome', 'profile', 'quiz', 'paywall', 'loading', 'dashboard', 'report', 'hr'];
const DESKTOP_ROUTES = new Set(['hr']);

// ─── tiny store: candidate id + drafts in memory ───────────
function useAppData() {
  const [candidateId, setCandidateId] = useState('C-2026-018');
  const [profile, setProfile] = useState(null);
  const [report, setReport] = useState(null);
  const [questions, setQuestions] = useState(null);
  const [welcome, setWelcome] = useState(null);
  const [paywall, setPaywall] = useState(null);
  const [quizPhase, setQuizPhase] = useState(1);
  const [unlocked, setUnlocked] = useState(false);

  // Initial fetch — Welcome content + first profile + first report
  useEffect(() => {
    api.getWelcomeContent().then(setWelcome);
    api.getPaywallInfo().then(setPaywall);
  }, []);

  // When candidate changes, refresh profile + report
  useEffect(() => {
    api.getProfile(candidateId).then(setProfile);
    api.getReport(candidateId).then(setReport);
  }, [candidateId]);

  const loadQuestions = useCallback(async (phase) => {
    const qs = await api.getQuestions(phase);
    setQuestions(qs);
  }, []);

  return {
    candidateId, setCandidateId,
    profile, report, questions, welcome, paywall,
    quizPhase, setQuizPhase,
    unlocked, setUnlocked,
    loadQuestions,
  };
}

// ─── Frame chooser ─────────────────────────────────────────
function PWAFrame({ fullscreen, desktop, children }) {
  if (desktop) {
    // HR desktop view — macOS-ish window chrome
    return (
      <div style={{ padding: 28, minHeight: '100vh' }}>
        <div style={{
          maxWidth: 1380, margin: '0 auto',
          background: 'var(--bg-stage)',
          borderRadius: 14, overflow: 'hidden',
          border: '1px solid rgba(255,255,255,0.08)',
          boxShadow: '0 40px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04) inset',
        }}>
          <DesktopChrome/>
          <div style={{ height: 820, overflow: 'hidden' }}>{children}</div>
        </div>
      </div>
    );
  }
  if (fullscreen) {
    return (
      <div style={{
        width: '100%', maxWidth: 430, height: '100dvh', margin: '0 auto',
        position: 'relative', overflow: 'hidden',
        background: 'var(--bg-stage)',
        // 保留 Dynamic Island 和 Home 條的安全距離
        paddingTop: 'env(safe-area-inset-top, 0px)',
        paddingBottom: 'env(safe-area-inset-bottom, 0px)',
        boxSizing: 'border-box',
      }}>{children}</div>
    );
  }
  // Mockup mode — show inside an iPhone device frame for review
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '24px 0' }}>
      <IOSDevice dark width={402} height={874}>
        <div style={{ width: '100%', height: '100%', overflow: 'hidden', position: 'relative' }}>
          {children}
        </div>
      </IOSDevice>
    </div>
  );
}

function DesktopChrome() {
  return (
    <div style={{
      height: 36, background: 'rgba(11,14,24,0.95)',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      display: 'flex', alignItems: 'center', padding: '0 14px', gap: 14,
      fontSize: 11, color: 'var(--fg-3)',
    }}>
      <div style={{ display: 'flex', gap: 6 }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#FF5F57' }}/>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#FEBC2E' }}/>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#28C840' }}/>
      </div>
      <span style={{ flex: 1, textAlign: 'center', fontFamily: 'var(--font-mono)' }}>
        admin.lifebiz.app / hr-dashboard
      </span>
      <span style={{ opacity: 0.5 }}>HR · 桌機後台</span>
    </div>
  );
}

// ─── PWA Shell ─────────────────────────────────────────────
function PWAShell() {
  const [t, setTweak] = useTweaks(TWEAKS_DEFAULT);
  const [route, setRoute] = useState(t.startRoute || 'welcome');
  const data = useAppData();

  const goto = (r) => {
    setRoute(r);
    // hash for shareability + Back-button support
    if (typeof window !== 'undefined') history.replaceState(null, '', `#${r}`);
  };

  // Honour initial hash + react to hash changes
  useEffect(() => {
    const apply = () => {
      const h = (location.hash || '').replace('#', '');
      if (ROUTES.includes(h)) setRoute(h);
    };
    apply();
    window.addEventListener('hashchange', apply);
    return () => window.removeEventListener('hashchange', apply);
  }, []);

  // Tweak — jump to any screen
  useEffect(() => { if (t.startRoute && t.startRoute !== route) setRoute(t.startRoute); }, [t.startRoute]);
  useEffect(() => { if (data.candidateId !== t.candidate && CANDIDATE_IDS[t.candidate]) data.setCandidateId(CANDIDATE_IDS[t.candidate]); }, [t.candidate]);

  // Auto-load questions when entering quiz directly (without going through profile)
  useEffect(() => {
    if (route === 'quiz' && !data.questions) data.loadQuestions(data.quizPhase || 1);
  }, [route, data.questions, data.quizPhase]);

  // Screen renderer — each receives data + a `nav` callback
  const screen = (() => {
    switch (route) {
      case 'welcome':
        return <WelcomeScreen
                 content={data.welcome}
                 onStart={() => goto('profile')}
                 onSignIn={() => goto('dashboard')}/>;
      case 'profile':
        return <ProfileScreen
                 onBack={() => goto('welcome')}
                 initial={data.profile ? {
                   name: data.profile.name,
                   gender: data.profile.gender,
                   date: data.profile.birth.date,
                   hour: data.profile.birth.hour,
                   place: data.profile.birth.place,
                 } : {}}
                 onSubmit={async (form) => {
                   await api.submitProfile(form);
                   data.setQuizPhase(1);
                   await data.loadQuestions(1);
                   goto('quiz');
                 }}/>;
      case 'quiz':
        return <QuizScreen
                 phase={data.quizPhase}
                 questions={data.questions}
                 onBack={() => goto('profile')}
                 onComplete={async (answers, completedPhase) => {
                   await api.submitAnswers(data.candidateId, answers);
                   if (completedPhase === 1) {
                     // TODO [BlockLib-extract]: payment gate — controlled by PAYMENT_CONFIG.isPaymentEnabled
                     if (PAYMENT_CONFIG.isPaymentEnabled) {
                       goto('paywall');
                     } else {
                       // Feature flag OFF：直接進入 Phase 2（MVP 全功能開放模式）
                       data.setQuizPhase(2);
                       await data.loadQuestions(2);
                       goto('quiz');
                     }
                   } else {
                     goto('loading');
                   }
                 }}/>;
      case 'paywall':
        // isPaymentEnabled=false 時直連 #paywall → 重導至 quiz（不顯示付費畫面）
        if (!PAYMENT_CONFIG.isPaymentEnabled) { goto('quiz'); return null; }
        return <PaywallScreen
                 content={data.paywall}
                 onBack={() => goto('quiz')}
                 onUnlock={async (plan) => {
                   await api.unlockPhase2(data.candidateId, plan);
                   data.setUnlocked(true);
                   data.setQuizPhase(2);
                   await data.loadQuestions(2);
                   goto('quiz');
                 }}
                 onSkip={() => goto('loading')}/>;
      case 'loading':
        return <LoadingScreen
                 candidateId={data.candidateId}
                 runAnalysis={async (cid, onProgress) => {
                   const result = await api.runAnalysis(cid, onProgress);
                   // Phase 2 complete — generate mock AI report (safe, no external API)
                   try { await api.generateAIReport(cid); } catch (_) {}
                   return result;
                 }}
                 onDone={() => goto('dashboard')}/>;
      case 'dashboard':
        return <DashboardScreen
                 profile={data.profile} report={data.report}
                 onAction={(a) => goto('report')}
                 onOpenReport={() => goto('report')}
                 onHome={() => goto('welcome')}
                 onSchedule={() => alert('預約功能即將開放，請先完成報告並與顧問確認時間。')}/>;
      case 'report':
        return <ReportScreen
                 profile={data.profile} report={data.report} tone={t.tone || 'hybrid'}
                 onBack={() => goto('dashboard')}
                 onSchedule={() => alert('預約功能即將開放，請先完成報告並與顧問確認時間。')}/>;
      case 'hr':
        return <HRDashboardScreen tone={t.tone || 'hybrid'}
                                  onOpenCandidate={(id) => {
                                    data.setCandidateId(id);
                                    goto('report');
                                  }}/>;
      default:
        return <WelcomeScreen content={data.welcome} onStart={() => goto('profile')}/>;
    }
  })();

  const effectiveFullscreen = IS_REAL_MOBILE || t.frame === 'fullscreen';

  return (
    <div style={{ minHeight: '100vh' }}>
      <PWAFrame fullscreen={effectiveFullscreen} desktop={DESKTOP_ROUTES.has(route)}>
        {screen}
      </PWAFrame>

      {/* dev hint — 只在桌機 mockup 模式顯示，手機上永遠隱藏 */}
      {!IS_REAL_MOBILE && !effectiveFullscreen && !DESKTOP_ROUTES.has(route) && (
        <div style={{
          position: 'fixed', top: 12, left: '50%', transform: 'translateX(-50%)',
          fontSize: 11, color: 'var(--fg-3)', display: 'flex', gap: 10, alignItems: 'center',
          background: 'rgba(20,22,36,0.92)',
          padding: '6px 12px', borderRadius: 99,
          border: '1px solid var(--line)',
          backdropFilter: 'blur(12px)', zIndex: 100,
        }}>
          <button onClick={() => {
            const i = ROUTES.indexOf(route);
            const next = ROUTES[Math.max(0, i-1)];
            goto(next); setTweak('startRoute', next);
          }} style={navHintBtn}>‹</button>
          <span style={{ color: 'var(--fg-2)', minWidth: 92, textAlign: 'center' }}>
            <span className="num">{ROUTES.indexOf(route)+1}/{ROUTES.length}</span>
            <span style={{ margin: '0 6px', opacity: 0.5 }}>·</span>
            <span>{ROUTE_LABELS[route]}</span>
          </span>
          <button onClick={() => {
            const i = ROUTES.indexOf(route);
            const next = ROUTES[Math.min(ROUTES.length-1, i+1)];
            goto(next); setTweak('startRoute', next);
          }} style={navHintBtn}>›</button>
        </div>
      )}

      {!IS_REAL_MOBILE && <TweaksPanel title="Tweaks">
        <TweakSection label="畫面">
          <TweakSelect
            label="目前畫面"
            value={t.startRoute || route}
            options={ROUTES.map(r => ({ value: r, label: `${ROUTES.indexOf(r)+1}. ${ROUTE_LABELS[r]}` }))}
            onChange={v => { setTweak('startRoute', v); goto(v); }}/>
          <TweakRadio label="框架"
            value={t.frame || 'mockup'}
            options={[{value:'mockup',label:'iPhone'},{value:'fullscreen',label:'全螢幕'}]}
            onChange={v => setTweak('frame', v)}/>
        </TweakSection>
        <TweakSection label="候選人">
          <TweakSelect
            label="範例資料"
            value={String(t.candidate || 0)}
            options={CANDIDATE_IDS.map((id, i) => {
              const f = FIXTURES.profiles.find(p => p.id === id);
              return { value: String(i), label: `${f.name} · ${f.mbti}` };
            })}
            onChange={v => setTweak('candidate', Number(v))}/>
        </TweakSection>
        <TweakSection label="報告語氣">
          <TweakRadio
            label="語氣"
            value={t.tone || 'hybrid'}
            options={[
              { value: 'spiritual', label: '靈性' },
              { value: 'hybrid',    label: '交織' },
              { value: 'data',      label: '數據' },
            ]}
            onChange={v => setTweak('tone', v)}/>
        </TweakSection>
      </TweaksPanel>}
    </div>
  );
}

const ROUTE_LABELS = {
  welcome: '開場首頁',
  profile: '基本資料',
  quiz: '問卷',
  paywall: '解鎖 Phase 2',
  loading: 'AI 分析中',
  dashboard: '命運總覽',
  report: '個人化報告',
  hr: 'HR 後台',
};
const CANDIDATE_IDS = ['C-2026-018', 'C-2026-019', 'C-2026-020', 'C-2026-021', 'C-2026-022', 'C-2026-023'];

const navHintBtn = {
  background: 'rgba(255,255,255,0.06)', border: '1px solid var(--line)',
  width: 22, height: 22, borderRadius: 8, color: 'var(--fg-2)',
  fontFamily: 'inherit', cursor: 'pointer', fontSize: 12, lineHeight: 1,
};

const TWEAKS_DEFAULT = /*EDITMODE-BEGIN*/{
  "startRoute": "welcome",
  "frame": "fullscreen",
  "candidate": 0,
  "tone": "hybrid"
}/*EDITMODE-END*/;

ReactDOM.createRoot(document.getElementById('root')).render(<PWAShell/>);
