// Main app — routing, tweaks panel, device frame wrappers

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "pastel",
  "metaphor": "forest",
  "age": "school",
  "playfulness": 2,
  "frame": "phone"
}/*EDITMODE-END*/;

function App() {
  const [state, setState] = useState(() => {
    try {
      const saved = localStorage.getItem('pandicka-state');
      return saved ? JSON.parse(saved) : { screen: 'profile', profile: null, category: null, level: null };
    } catch {
      return { screen: 'profile', profile: null, category: null, level: null };
    }
  });

  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [showTweaks, setShowTweaks] = useState(false);

  // Auth + consent + subscription lifecycle
  const [authUser, setAuthUser] = useState(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [consented, setConsented] = useState(() => hasLocalConsent());
  const [subscription, setSubscription] = useState({ tier: 'free', role: 'parent' });

  useEffect(() => {
    initA11y();
    initFirebase();
    const unsub = onAuthChange(async (u) => {
      setAuthUser(u);
      setAuthChecked(true);
      if (u) {
        const sub = await loadSubscription(u);
        setSubscription(sub);
      } else {
        setSubscription({ tier: 'free', role: 'parent' });
      }
    });
    // i bez Firebase označ checked, ať nečekáme na něco, co nepřijde
    setTimeout(() => setAuthChecked(true), 800);
    return () => typeof unsub === 'function' && unsub();
  }, []);

  useEffect(() => {
    try { localStorage.setItem('pandicka-state', JSON.stringify(state)); } catch {}
    trackPageview(state.screen);
  }, [state]);

  // Edit-mode protocol
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setShowTweaks(true);
      else if (e.data?.type === '__deactivate_edit_mode') setShowTweaks(false);
    };
    window.addEventListener('message', onMsg);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const updateTweak = (key, val) => {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  };

  const palette = PALETTES[tweaks.palette] || PALETTES.pastel;
  const metaphor = tweaks.metaphor;

  // Profile je null, dokud si dítě nevybere — žádné defaulty
  const profile = state.profile;
  if (profile && !profile.progress) profile.progress = {};
  const isAdmin = subscription?.role === 'admin';

  const go = (screen, extra = {}) => setState(s => ({ ...s, screen, ...extra }));

  const [newAchievement, setNewAchievement] = useState(null);

  const persistProfile = (updated) => {
    setState(s => ({ ...s, profile: updated }));
    if (authUser?.uid) saveProfile(authUser.uid, updated).catch(() => {});
  };

  const handleTaskComplete = ({ xp = 10, coins = 5, attempts = 0, feedback } = {}) => {
    const cat = state.category || { id: 'hearing' };
    const newXp = (profile.xp || 0) + xp;
    const newCoins = (profile.coins || 0) + coins;
    const newLevel = Math.max(1, Math.floor(newXp / 100) + 1);
    const currentProg = (profile.progress && profile.progress[cat.id]) || 0;
    let updated = {
      ...profile,
      xp: newXp,
      coins: newCoins,
      level: newLevel,
      progress: { ...(profile.progress || {}), [cat.id]: currentProg + 1 },
    };
    // Daily streak
    updated = touchStreak(updated);
    // Perfect streak (správně napoprvé)
    updated = recordAttempt(updated, { correct: true, firstTry: attempts === 0 });
    // Nové odznáčky
    const newly = checkNewAchievements(updated);
    newly.forEach(a => { updated = grantAchievement(updated, a.id); });
    if (newly[0]) {
      setNewAchievement(newly[0]);
      announceAssertive(`Nový odznáček: ${newly[0].name}!`);
    }

    const taskId = state.level?.task?.id;
    trackTaskComplete({ taskId, categoryId: cat.id, xp, coins });
    logProgress(authUser?.uid, profile.id || 'local', {
      taskId, categoryId: cat.id, xp, coins, attempts, feedback,
    });
    if (authUser?.uid) saveProfile(authUser.uid, updated).catch(() => {});
    announce(`Super! Získal jsi ${xp} bodů a ${coins} mincí.`);
    setState(s => ({ ...s, profile: updated, screen: 'map' }));
  };

  let content;
  const commonProps = { palette, metaphor, age: tweaks.age, playfulness: tweaks.playfulness };

  // Auth gate — bez přihlášení nic nepokračuje
  const fbConfigured = typeof window.PANDICKA_FIREBASE_CONFIG === 'object' && window.PANDICKA_FIREBASE_CONFIG?.apiKey;
  if (authChecked && fbConfigured && !authUser) {
    return (
      <AppFrame palette={palette} metaphor={metaphor} frame={tweaks.frame} label="Auth">
        <AuthScreen {...commonProps}
          onAuthenticated={() => {}}
        />
      </AppFrame>
    );
  }

  // Consent gate
  if (authUser && !consented) {
    return (
      <AppFrame palette={palette} metaphor={metaphor} frame={tweaks.frame} label="Consent">
        <ConsentScreen {...commonProps} user={authUser}
          onAccept={() => setConsented(true)}
          onDecline={() => signOutParent().then(() => location.reload())}
        />
      </AppFrame>
    );
  }

  // Pokud dítě nebylo vybráno, vyhoď ho na profile picker (kromě rodiče / administrace)
  if (!profile && !['profile', 'parent', 'admin', 'privacy'].includes(state.screen)) {
    return (
      <AppFrame palette={palette} metaphor={metaphor} frame={tweaks.frame} label="Profil">
        <ProfilePickerScreen {...commonProps} user={authUser}
          onPick={(p) => {
            const enriched = { ...p, progress: p.progress || {} };
            go('hub', { profile: enriched });
          }}
          onParent={() => go('parent')}/>
      </AppFrame>
    );
  }

  switch (state.screen) {
    case 'profile':
      content = <ProfilePickerScreen {...commonProps} user={authUser}
        onPick={(p) => {
          const enriched = { ...p, progress: p.progress || {} };
          go('hub', { profile: enriched });
        }}
        onParent={() => go('parent')}
      />;
      break;
    case 'hub':
      content = <HomeHubScreen {...commonProps} profile={profile}
        onBack={() => go('profile')}
        onCategory={(c) => go('map', { category: c })}
        onShop={() => go('shop')}
        onAchievements={() => go('achievements')}
        onUpdateProfile={persistProfile}
      />;
      break;
    case 'shop':
      content = <ShopScreen {...commonProps} profile={profile}
        onBack={() => go('hub')}
        onUpdateProfile={persistProfile}
      />;
      break;
    case 'achievements':
      content = <AchievementsScreen {...commonProps} profile={profile}
        onBack={() => go('hub')}
      />;
      break;
    case 'map':
      content = <AdventureMapScreen {...commonProps} profile={profile}
        category={state.category || CATEGORIES_META[0]}
        subscription={subscription}
        onBack={() => go('hub')}
        onLevel={(l) => go('task', { level: l })}
      />;
      break;
    case 'task':
      content = <TaskPlayerScreen {...commonProps} profile={profile}
        level={state.level}
        category={state.category || CATEGORIES_META[0]}
        onBack={() => go('map')}
        onComplete={handleTaskComplete}
      />;
      break;
    case 'parent':
      content = <ParentDashboardScreen {...commonProps}
        user={authUser}
        subscription={subscription}
        onBack={() => go('profile')}
        onAdmin={isAdmin ? () => go('admin') : null}
        onPrivacy={() => go('privacy')}
        onLogout={() => signOutParent().then(() => location.reload())}
      />;
      break;
    case 'admin':
      if (!isAdmin) { go('parent'); content = null; break; }
      content = <AdminDashboardScreen {...commonProps}
        onBack={() => go('parent')}
      />;
      break;
    case 'privacy':
      content = <PrivacyPanelScreen palette={palette} playfulness={tweaks.playfulness}
        user={authUser} onBack={() => go('parent')}/>;
      break;
    default:
      content = null;
  }

  // Screen label
  const label = {
    profile: '01 Výběr profilu',
    hub: '02 Domů',
    map: '03 Dobrodružná mapa',
    task: '04 Úkol',
    parent: '05 Rodič',
    admin: '06 Administrace',
    privacy: '07 Soukromí',
    shop: '08 Obchůdek',
    achievements: '09 Síň slávy',
  }[state.screen];

  return (
    <div id="main" data-screen-label={label} style={{
      minHeight: '100vh', width: '100%',
      background: `radial-gradient(ellipse at top, ${palette.bgDeep}, ${palette.bg})`,
      fontFamily: '"Baloo 2", system-ui',
      position: 'relative', overflow: 'hidden auto',
    }}>
      <PaperBg palette={palette} metaphor={metaphor}/>
      <div style={{
        position: 'relative', zIndex: 1,
        maxWidth: 960, margin: '0 auto',
        minHeight: '100vh',
      }}>
        {content}
      </div>

      {/* Dev screen selector — pouze v tweaks/dev režimu */}
      {showTweaks && (
        <div style={{
          position: 'fixed', top: 12, left: '50%', transform: 'translateX(-50%)',
          zIndex: 50, display: 'flex', gap: 4, padding: 4,
          background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(10px)',
          borderRadius: 999, boxShadow: '0 6px 20px rgba(0,0,0,0.1)',
          flexWrap: 'wrap', maxWidth: 'calc(100vw - 40px)',
        }}>
          {[
            { k: 'profile',      l: 'Profil' },
            { k: 'hub',          l: 'Domů' },
            { k: 'map',          l: 'Mapa' },
            { k: 'task',         l: 'Úkol' },
            { k: 'shop',         l: 'Shop' },
            { k: 'achievements', l: 'Trofeje' },
            { k: 'parent',       l: 'Rodič' },
            ...(isAdmin ? [{ k: 'admin', l: 'Admin' }] : []),
          ].map(t => (
            <button key={t.k} onClick={() => go(t.k)} style={{
              padding: '6px 12px', borderRadius: 999, border: 'none',
              background: state.screen === t.k ? palette.primary : 'transparent',
              color: state.screen === t.k ? '#fff' : palette.ink,
              fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12, cursor: 'pointer',
            }}>{t.l}</button>
          ))}
        </div>
      )}

      {/* Achievement toast */}
      <AnimatePresence>
        {newAchievement && (
          <AchievementToast achievement={newAchievement} palette={palette}
            onClose={() => setNewAchievement(null)}/>
        )}
      </AnimatePresence>

      {/* Tweaks panel */}
      {showTweaks && (
        <div style={{
          position: 'fixed', bottom: 20, right: 20, zIndex: 100,
          width: 300, padding: 18, borderRadius: 22,
          background: '#fff', boxShadow: '0 20px 50px rgba(0,0,0,0.18)',
          fontFamily: '"Baloo 2", "Baloo 2", system-ui',
          border: '1.5px solid #00000010',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <div style={{ fontWeight: 700, fontSize: 16, color: '#3B2A2F' }}>Tweaks</div>
            <button onClick={() => setShowTweaks(false)} style={{
              width: 28, height: 28, borderRadius: '50%', border: 'none',
              background: '#00000010', cursor: 'pointer', fontSize: 16,
            }}>×</button>
          </div>

          <TweakGroup label="Metafora mapy">
            {[
              ['forest','🌲 Les'],
              ['ocean','🌊 Moře'],
              ['space','🚀 Vesmír'],
            ].map(([k,l]) => (
              <TweakPill key={k} active={metaphor === k} onClick={() => updateTweak('metaphor', k)}>{l}</TweakPill>
            ))}
          </TweakGroup>

          <TweakGroup label="Paleta">
            {[
              ['pastel','Pastel'],
              ['light','Světlá'],
              ['dark','Tmavá'],
            ].map(([k,l]) => (
              <TweakPill key={k} active={tweaks.palette === k} onClick={() => updateTweak('palette', k)}>{l}</TweakPill>
            ))}
          </TweakGroup>

          <TweakGroup label="Věk dítěte">
            {[
              ['little','🐣 Předškolák'],
              ['school','🎒 Školák'],
            ].map(([k,l]) => (
              <TweakPill key={k} active={tweaks.age === k} onClick={() => updateTweak('age', k)}>{l}</TweakPill>
            ))}
          </TweakGroup>

          <TweakGroup label={`Hravost · ${tweaks.playfulness}`}>
            {[0,1,2,3].map(n => (
              <TweakPill key={n} active={tweaks.playfulness === n} onClick={() => updateTweak('playfulness', n)}>{n}</TweakPill>
            ))}
          </TweakGroup>

          <TweakGroup label="Zařízení">
            {[
              ['phone','📱 Telefon'],
              ['tablet','📟 Tablet'],
              ['desktop','💻 Desktop'],
            ].map(([k,l]) => (
              <TweakPill key={k} active={frame === k} onClick={() => updateTweak('frame', k)}>{l}</TweakPill>
            ))}
          </TweakGroup>
        </div>
      )}
    </div>
  );
}

function TweakGroup({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: '#7A6670', marginBottom: 6,
      }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{children}</div>
    </div>
  );
}

function TweakPill({ children, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: '6px 12px', borderRadius: 999,
      border: active ? '1.5px solid #F49B63' : '1.5px solid #00000015',
      background: active ? '#F49B6320' : 'transparent',
      color: active ? '#E67C3F' : '#3B2A2F',
      fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12,
      cursor: 'pointer',
    }}>{children}</button>
  );
}

// ─── AppFrame — sdílená skořápka pro Auth/Consent gate ────────
function AppFrame({ palette, metaphor, label, children }) {
  return (
    <div id="main" data-screen-label={label} style={{
      minHeight: '100vh', width: '100%',
      background: `radial-gradient(ellipse at top, ${palette.bgDeep}, ${palette.bg})`,
      fontFamily: '"Baloo 2", system-ui',
      position: 'relative', overflow: 'hidden auto',
    }}>
      <PaperBg palette={palette} metaphor={metaphor}/>
      <div style={{
        position: 'relative', zIndex: 1,
        maxWidth: 720, margin: '0 auto',
        minHeight: '100vh',
      }}>
        {children}
      </div>
    </div>
  );
}

// ─── Error boundary ──────────────────────────────────────────
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error('Pandička error:', error, info);
    try { trackEvent('error', { message: String(error?.message || error).slice(0, 120) }); } catch {}
  }
  render() {
    if (this.state.hasError) {
      return (
        <div role="alert" style={{
          minHeight: '100vh', background: '#FFF4E2', fontFamily: '"Baloo 2", "Baloo 2", system-ui',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
        }}>
          <div style={{
            maxWidth: 420, textAlign: 'center', padding: 24, borderRadius: 28,
            background: '#fff', boxShadow: '0 20px 60px rgba(0,0,0,0.12)',
          }}>
            <div style={{ fontSize: 56 }}>🐼</div>
            <h1 style={{ fontSize: 22, margin: '10px 0 6px', color: '#3B2A2F' }}>Pandička trochu zaspala</h1>
            <p style={{ color: '#7A6670', marginBottom: 16 }}>Něco se pokazilo. Zkusíme to znovu?</p>
            <button onClick={() => location.reload()} style={{
              padding: '12px 22px', borderRadius: 999, border: 'none', cursor: 'pointer',
              background: '#F49B63', color: '#fff', fontFamily: 'inherit', fontWeight: 600, fontSize: 14,
              boxShadow: '0 3px 0 #E67C3F',
            }}>Zkusit znovu</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// ─── Service worker registration ─────────────────────────────
if ('serviceWorker' in navigator && location.protocol !== 'file:') {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./sw.js').catch(() => {});
  });
}

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