/* global React */
// ─────────────────────────────────────────────────────────────
// skilowgue mock router (mobile single-view)
// 単純な state-based ルーター + コンサル相談モーダルのオーバーレイ制御
// ─────────────────────────────────────────────────────────────
const { useState, useEffect, useRef } = React;
const { C, FS, FF, FM, Icon, PhoneShell } = window.SKG;
const { AuthScreen } = window.SKG_AUTH;
const { CompanyProfileScreen } = window.SKG_PROFILE;
const { MatchingWaitScreen } = window.SKG_WAIT;
const { HomeScreen, InboxScreen } = window.SKG_HOME;
const { MatchDetailScreen, ConsultFormScreen } = window.SKG_MATCH;
const { SettingsScreen, CardUploadScreen } = window.SKG_SETTINGS;
const { CardListScreen, ContactDetailScreen } = window.SKG_CARDS;
const { CardImportScreen } = window.SKG_IMPORT;

const ROUTES = {
  signup:        { render: () => <AuthScreen mode="signup" />,                   inAuth: true,  group: 'auth' },
  login:         { render: () => <AuthScreen mode="login" />,                    inAuth: true,  group: 'auth' },
  profile:       { render: (nav) => <CompanyProfileScreen onComplete={(r) => r === 'back' ? nav.back() : nav.go('wait')} />, inAuth: true, group: 'auth' },
  wait:          { render: (nav) => <MatchingWaitScreen onAction={(id) => {
                     if (id === 'consult') nav.openConsult();
                     else if (id === 'card') nav.go('cards-upload');
                     else nav.go('home');
                   }} />, inAuth: true, group: 'auth' },
  home:          { render: () => <HomeScreen />,                                 group: 'main', tab: 'home' },
  inbox:         { render: () => <InboxScreen />,                                group: 'main', tab: 'inbox' },
  match:         { render: () => <MatchDetailScreen />,                          group: 'main', tab: 'inbox' },
  cards:         { render: () => <CardListScreen />,                             group: 'main', tab: 'cards' },
  contact:       { render: () => <ContactDetailScreen />,                        group: 'main', tab: 'cards' },
  'cards-upload':{ render: () => <CardUploadScreen />,                           group: 'main', tab: 'cards' },
  'cards-import':{ render: () => <CardImportScreen />,                           group: 'main', tab: 'cards' },
  settings:      { render: () => <SettingsScreen />,                             group: 'main', tab: 'settings' },
};

function App() {
  const [route, setRoute] = useState(() => {
    // Allow ?screen=home to deep-link
    const url = new URL(window.location.href);
    const r = url.searchParams.get('screen');
    return ROUTES[r] ? r : 'signup';
  });
  const [history, setHistory] = useState([]);
  const [consultOpen, setConsultOpen] = useState(false);

  // Sync route with URL hash so back button feels natural
  useEffect(() => {
    const url = new URL(window.location.href);
    url.searchParams.set('screen', route);
    window.history.replaceState(null, '', url.toString());
  }, [route]);

  const nav = {
    go: (next) => {
      if (!ROUTES[next]) {
        console.warn('Unknown route', next);
        return;
      }
      setHistory(h => [...h, route]);
      setRoute(next);
      // Re-render lucide icons after the screen swaps in
      setTimeout(() => window.lucide && window.lucide.createIcons(), 50);
    },
    back: () => {
      setHistory(h => {
        if (h.length === 0) return h;
        const prev = h[h.length - 1];
        setRoute(prev);
        setTimeout(() => window.lucide && window.lucide.createIcons(), 50);
        return h.slice(0, -1);
      });
    },
    openConsult: () => {
      setConsultOpen(true);
      setTimeout(() => window.lucide && window.lucide.createIcons(), 50);
    },
    closeConsult: () => setConsultOpen(false),
    current: () => route,
  };

  // Expose to all screens (read by shared.jsx, auth.jsx, etc.)
  window.SKG_NAV = nav;

  // Re-create lucide icons on every render
  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
    const t1 = setTimeout(() => window.lucide && window.lucide.createIcons(), 100);
    const t2 = setTimeout(() => window.lucide && window.lucide.createIcons(), 400);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  });

  const screen = ROUTES[route] ? ROUTES[route].render(nav) : ROUTES.signup.render(nav);

  return (
    <div style={{
      minHeight: '100vh',
      width: '100%',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'flex-start',
      background: '#07050D',
      padding: '0',
    }}>
      {/* Dev helper bar - dev only, hides via ?clean=1 */}
      <DevBar route={route} nav={nav} />

      {/* Phone viewport */}
      <div className="phone-frame" style={{
        width: '100%',
        maxWidth: 414,
        minHeight: '100dvh',
        position: 'relative',
        background: '#0B0814',
        boxShadow: '0 0 60px rgba(165,154,202,.12)',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
      }}>
        {screen}
        {consultOpen && <ConsultFormScreen />}
      </div>
    </div>
  );
}

// Tiny developer navigation bar to jump between screens — useful for the mock
function DevBar({ route, nav }) {
  const [open, setOpen] = useState(false);
  const url = new URL(window.location.href);
  if (url.searchParams.get('clean') === '1') return null;

  const groups = [
    { title: '認証 / オンボーディング', items: ['signup', 'login', 'profile', 'wait'] },
    { title: 'コア体験', items: ['home', 'inbox', 'match'] },
    { title: '名刺管理', items: ['cards', 'contact', 'cards-upload', 'cards-import'] },
    { title: 'アカウント', items: ['settings'] },
  ];
  const labels = {
    signup: '01 サインアップ',
    login: '02 ログイン',
    profile: '会社プロフィール入力',
    wait: 'マッチング待機 (準備完了)',
    home: '03 ホーム',
    inbox: '04 受信トレイ',
    match: '05 マッチング提案詳細',
    cards: '09 名刺一覧',
    contact: '10 連絡先詳細',
    'cards-upload': '08 名刺アップロード · OCR',
    'cards-import': '11 名刺一括インポート (CSV)',
    settings: '07 アカウント設定',
  };

  return (
    <>
      {/* Toggle */}
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          position: 'fixed', top: 12, right: 12, zIndex: 100,
          padding: '8px 12px',
          background: 'rgba(11,8,20,.92)',
          border: `1px solid ${C.border2}`,
          color: C.lilac, cursor: 'pointer',
          fontFamily: FM, fontSize: 11, letterSpacing: '.1em',
          backdropFilter: 'blur(8px)',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}
      >
        <Icon name={open ? 'x' : 'list'} size={13} color={C.lilac} />
        {open ? 'CLOSE' : 'SCREENS'}
      </button>
      {open && (
        <div style={{
          position: 'fixed', top: 50, right: 12, zIndex: 99,
          width: 240, maxHeight: '80vh', overflow: 'auto',
          background: 'rgba(11,8,20,.96)',
          border: `1px solid ${C.border2}`,
          padding: '12px 14px',
          backdropFilter: 'blur(8px)',
          boxShadow: '0 4px 24px rgba(0,0,0,.5)',
        }}>
          <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: '.2em', color: C.lilac, marginBottom: 10, textTransform: 'uppercase' }}>// MOCK DEV NAV</div>
          {groups.map((g, gi) => (
            <div key={gi} style={{ marginBottom: 10 }}>
              <div style={{ fontFamily: FM, fontSize: 9, color: C.fg3, letterSpacing: '.12em', marginBottom: 6, textTransform: 'uppercase' }}>{g.title}</div>
              {g.items.map(id => (
                <div
                  key={id}
                  onClick={() => { nav.go(id); setOpen(false); }}
                  style={{
                    padding: '7px 10px', cursor: 'pointer',
                    border: `1px solid ${route === id ? C.lilac : 'transparent'}`,
                    background: route === id ? 'rgba(165,154,202,.08)' : 'transparent',
                    color: route === id ? C.lilac : C.fg2,
                    fontFamily: FS, fontSize: 11.5, marginBottom: 2,
                    letterSpacing: '.02em',
                  }}
                >
                  {labels[id] || id}
                </div>
              ))}
            </div>
          ))}
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: `1px solid ${C.border}`, fontFamily: FM, fontSize: 9, color: C.fg3, letterSpacing: '.06em', lineHeight: 1.6 }}>
            <div onClick={() => { nav.openConsult(); setOpen(false); }} style={{ color: C.cyan, cursor: 'pointer', padding: '4px 0' }}>→ コンサル相談モーダル</div>
            <a href="canvas.html" style={{ color: C.lilac, textDecoration: 'underline', display: 'block', padding: '4px 0' }}>→ 全画面一覧 (canvas.html)</a>
          </div>
        </div>
      )}
    </>
  );
}

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