/* global React, FlowContext,
   S1_Landing, S2_AdminSignup, S3_AdminLogin,
   S4_WizardSlug, S5_WizardCategory, S6_WizardInvite, S7_WizardDone,
   S8_Switcher, S9_TeacherLogin, S11_InviteAccept, S12_TeacherReset,
   S13_WorkspaceNotFound */

// ============================================================================
// LessonHigh · Prototype shell — auth gate around the main app
// ============================================================================
// • Lives in front of the existing app. When the user has not "signed in"
//   (flow !== 'app'), an auth/onboarding screen is rendered full-bleed.
// • When flow === 'app', the children (the real dashboard) take over.
// • State persists in localStorage so refresh stays put. A tiny "demo reset"
//   chip in the bottom-left lets you replay the flow.
// ============================================================================

const FLOW_KEY = 'lh_demo_flow';

const SCREEN_MAP = {
  'landing':        { component: () => <S1_Landing/>,         label: 'Landing' },
  'admin-signup':   { component: () => <S2_AdminSignup/>,     label: '원장 가입' },
  'admin-login':    { component: () => <S3_AdminLogin/>,      label: '원장 로그인' },
  'wizard-slug':    { component: () => <S4_WizardSlug/>,      label: '마법사 1 · 슬러그' },
  'wizard-category':{ component: () => <S5_WizardCategory/>,  label: '마법사 2 · 카테고리' },
  'wizard-invite':  { component: () => <S6_WizardInvite/>,    label: '마법사 3 · 초대' },
  'wizard-done':    { component: () => <S7_WizardDone/>,      label: '마법사 완료' },
  'switcher':       { component: () => <S8_Switcher/>,        label: '스위처' },
  'teacher-login':  { component: () => <S9_TeacherLogin/>,    label: '강사 로그인' },
  'invite-accept':  { component: () => <S11_InviteAccept/>,   label: '초대 수락' },
  'teacher-reset':  { component: () => <S12_TeacherReset/>,   label: '비밀번호 재설정' },
  'workspace-404':  { component: () => <S13_WorkspaceNotFound/>, label: '워크스페이스 없음' },
};

function PrototypeShell({ children }) {
  const { useState, useEffect, useMemo, useCallback } = React;

  const [flow, setFlow] = useState(() => {
    try { return localStorage.getItem(FLOW_KEY) || 'landing'; }
    catch { return 'landing'; }
  });
  const [history, setHistory] = useState([]);

  useEffect(() => {
    try { localStorage.setItem(FLOW_KEY, flow); } catch (e) {}
  }, [flow]);

  const go = useCallback((next) => {
    setHistory(h => [...h, flow]);
    setFlow(next);
    window.scrollTo(0, 0);
  }, [flow]);

  const back = useCallback(() => {
    setHistory(h => {
      if (!h.length) return h;
      const prev = h[h.length - 1];
      setFlow(prev);
      return h.slice(0, -1);
    });
  }, []);

  const reset = useCallback(() => {
    setHistory([]);
    setFlow('landing');
  }, []);

  const flowApi = useMemo(() => ({ go, back, reset, current: flow }), [go, back, reset, flow]);

  const isApp = flow === 'app';
  const screenEntry = SCREEN_MAP[flow];

  return (
    <FlowContext.Provider value={flowApi}>
      {/* The real app is rendered always so its state isn't lost between
         flow transitions, but hidden behind the auth gate when needed. */}
      <div style={{ display: isApp ? 'contents' : 'none' }}>
        {children}
      </div>

      {!isApp && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 50,
          background: 'var(--bg-canvas)', overflow: 'auto',
        }}>
          {screenEntry ? screenEntry.component() : <S1_Landing/>}
        </div>
      )}

      <DemoReset
        flow={flow}
        canBack={history.length > 0}
        onBack={back}
        onReset={reset}
        onJump={go}
      />
    </FlowContext.Provider>
  );
}

// ─── Small persistent control to replay the flow ──────────────────────────
function DemoReset({ flow, canBack, onBack, onReset, onJump }) {
  const { useState } = React;
  const [open, setOpen] = useState(false);
  const label = flow === 'app' ? '대시보드' : (SCREEN_MAP[flow]?.label || flow);

  return (
    <div style={{
      position: 'fixed', left: 16, bottom: 16, zIndex: 100,
      display: 'flex', flexDirection: 'column-reverse', alignItems: 'flex-start', gap: 6,
    }}>
      <button
        onClick={() => setOpen(o => !o)}
        title="프로토타입 데모 컨트롤"
        style={{
          appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
          background: 'var(--text-primary)', color: 'var(--text-on-accent)',
          border: 'none', borderRadius: 99,
          padding: '8px 14px 8px 12px',
          fontSize: 12, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', gap: 8,
          boxShadow: 'var(--shadow-md)',
          letterSpacing: '-0.005em',
        }}>
        <span style={{
          width: 7, height: 7, borderRadius: 99,
          background: flow === 'app' ? '#7ad99e' : '#f6c068',
        }}/>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, opacity: 0.7, letterSpacing: '0.04em', textTransform: 'uppercase' }}>DEMO</span>
        {label}
        <span style={{ opacity: 0.5, fontSize: 11 }}>{open ? '▾' : '▴'}</span>
      </button>

      {open && (
        <div style={{
          background: 'var(--bg-surface)', border: '1px solid var(--border-default)',
          borderRadius: 10, padding: 10,
          boxShadow: 'var(--shadow-lg)',
          width: 260, maxHeight: 460, overflow: 'auto',
          fontSize: 12.5,
        }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
            <button className="btn is-sm" disabled={!canBack} onClick={onBack} style={{ flex: 1 }}>← 이전</button>
            <button className="btn is-sm is-primary" onClick={onReset} style={{ flex: 1 }}>처음부터</button>
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-tertiary)', padding: '4px 6px 6px' }}>
            장면 점프
          </div>
          {Object.entries(SCREEN_MAP).map(([key, s]) => (
            <button key={key} onClick={() => onJump(key)} style={{
              appearance: 'none', width: '100%', textAlign: 'left',
              background: flow === key ? 'var(--accent-subtle-bg)' : 'transparent',
              color: flow === key ? 'var(--accent-default)' : 'var(--text-primary)',
              border: 'none', borderRadius: 6, padding: '6px 8px',
              cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              fontWeight: flow === key ? 600 : 400,
            }}>
              <span>{s.label}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-tertiary)' }}>{key}</span>
            </button>
          ))}
          <div style={{ borderTop: '1px solid var(--border-default)', marginTop: 8, paddingTop: 8 }}>
            <button onClick={() => onJump('app')} style={{
              appearance: 'none', width: '100%', textAlign: 'left',
              background: flow === 'app' ? 'var(--accent-subtle-bg)' : 'transparent',
              color: flow === 'app' ? 'var(--accent-default)' : 'var(--text-primary)',
              border: 'none', borderRadius: 6, padding: '6px 8px',
              cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              fontWeight: flow === 'app' ? 600 : 400,
            }}>
              <span>→ 대시보드 입장</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-tertiary)' }}>app</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PrototypeShell });
