/* App shell — routing, layouts, tweaks panel, orchestration */

// ============ ADMIN ALUNO DETAIL (falta essa) ============
function AdminAlunoDetalhe({ alunoId, onBack }) {
  const aluno = FC_ALUNOS.find(a => a.id === alunoId);
  if (!aluno) return null;

  const eventos = [
    { data: '2026-04-20 14:32', tipo: 'login', texto: 'Login (Chrome · São Paulo, BR)' },
    { data: '2026-04-20 14:35', tipo: 'progresso', texto: 'Concluiu aula "CPC 27 — Imobilizado"' },
    { data: '2026-04-18 09:14', tipo: 'duvida', texto: 'Publicou dúvida em "Depreciação e impairment"' },
    { data: '2026-04-15 19:02', tipo: 'progresso', texto: 'Iniciou Módulo 3' },
    { data: '2026-04-02 10:00', tipo: 'pagamento', texto: 'Renovação anual processada — R$ 2.964' },
    { data: '2026-01-15 11:22', tipo: 'cadastro', texto: 'Primeiro acesso à plataforma' },
  ];

  return (
    <div className="fc-stack fc-gap-6">
      <button className="fc-btn fc-btn-ghost fc-btn-sm" onClick={onBack} style={{ alignSelf: 'flex-start' }}>
        <I.chevronLeft size={16} /> Voltar para alunos
      </button>

      <Card style={{ padding: 28 }}>
        <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
          <div className="fc-avatar" style={{ width: 72, height: 72, fontSize: 28 }}>{aluno.nome.charAt(0)}</div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
              <StatusPill status={aluno.status} />
              <Badge tone={aluno.plano === 'anual' ? 'gold' : 'gray'}>{aluno.plano}</Badge>
            </div>
            <div className="fc-h2" style={{ marginBottom: 4 }}>{aluno.nome}</div>
            <div className="fc-small">{aluno.email} · {aluno.cidade || 'sem cidade'}</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.mail size={14} /> Enviar e-mail</button>
            <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.sparkle size={14} /> Conceder cortesia</button>
          </div>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Card style={{ padding: 16 }}>
          <div className="fc-caption">PROGRESSO</div>
          <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--fc-azul-profundo)', margin: '6px 0 8px' }}>{aluno.progresso}%</div>
          <Progress value={aluno.progresso} size="xs" />
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="fc-caption">CADASTRO</div>
          <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fc-azul-profundo)', marginTop: 6 }}>{new Date(aluno.cadastro).toLocaleDateString('pt-BR')}</div>
          <div className="fc-caption" style={{ marginTop: 4 }}>há ~{Math.round((Date.now() - new Date(aluno.cadastro)) / (86400000 * 30))} meses</div>
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="fc-caption">ÚLTIMO LOGIN</div>
          <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fc-azul-profundo)', marginTop: 6 }}>{new Date(aluno.ultLogin).toLocaleDateString('pt-BR')}</div>
        </Card>
        <Card style={{ padding: 16 }}>
          <div className="fc-caption">DÚVIDAS POSTADAS</div>
          <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--fc-azul-profundo)', marginTop: 6 }}>{FC_DUVIDAS.filter(d => d.autorId === aluno.id).length}</div>
        </Card>
      </div>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 16 }}>Linha do tempo</div>
        <div style={{ position: 'relative', paddingLeft: 24 }}>
          <div style={{ position: 'absolute', left: 5, top: 6, bottom: 6, width: 2, background: 'var(--fc-gray-200)' }} />
          {eventos.map((e, i) => (
            <div key={i} style={{ position: 'relative', paddingBottom: 18 }}>
              <div style={{
                position: 'absolute', left: -23, top: 5, width: 12, height: 12, borderRadius: '50%',
                background: e.tipo === 'pagamento' ? 'var(--fc-dourado)' : e.tipo === 'duvida' ? 'var(--fc-azul-medio)' : 'var(--fc-success)',
                border: '2px solid white', boxShadow: '0 0 0 2px var(--fc-gray-200)',
              }} />
              <div className="fc-caption" style={{ marginBottom: 2 }}>{e.data}</div>
              <div style={{ fontSize: 14, color: 'var(--fc-gray-800)' }}>{e.texto}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// ============ SIDEBARS ============
function AlunoSidebar({ active, onNavigate, onLogout, onToggleArea, user }) {
  const items = [
    { id: 'aluno-dashboard', icon: I.home, label: 'Início' },
    { id: 'aluno-aulas', icon: I.play, label: 'Aulas' },
    { id: 'aluno-duvidas', icon: I.chat, label: 'Dúvidas' },
    ...(user.plano === 'anual' ? [{ id: 'aluno-mentoria', icon: I.video, label: 'Mentoria', badge: 'Premium' }] : []),
    { id: 'aluno-certificado', icon: I.award, label: 'Certificado' },
    { id: 'aluno-perfil', icon: I.user, label: 'Perfil' },
  ];
  return (
    <aside className="fc-sidebar">
      <div className="fc-sidebar-brand">
        <BrandLockup dark size="md" />
      </div>
      <nav className="fc-nav">
        {items.map(it => {
          const IconEl = it.icon;
          return (
            <button key={it.id} className={'fc-nav-item' + (active === it.id ? ' active' : '')} onClick={() => onNavigate(it.id)}>
              <IconEl size={18} />
              <span style={{ flex: 1, textAlign: 'left' }}>{it.label}</span>
              {it.badge && <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: 'var(--fc-dourado)', color: 'var(--fc-azul-profundo)', letterSpacing: '0.08em' }}>{it.badge}</span>}
            </button>
          );
        })}
      </nav>
      <div className="fc-sidebar-ftr">
        <button className="fc-nav-item" onClick={onToggleArea} style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>
          <I.settings size={16} /> <span>Alternar pro Admin</span>
        </button>
        <button className="fc-nav-item" onClick={onLogout} style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>
          <I.logout size={16} /> <span>Sair</span>
        </button>
      </div>
    </aside>
  );
}

function AdminSidebar({ active, onNavigate, onToggleArea, onLogout }) {
  const items = [
    { id: 'admin-dashboard', icon: I.home, label: 'Dashboard' },
    { id: 'admin-aulas', icon: I.play, label: 'Aulas' },
    { id: 'admin-alunos', icon: I.users, label: 'Alunos' },
    { id: 'admin-duvidas', icon: I.chat, label: 'Dúvidas' },
    { id: 'admin-metricas', icon: I.barChart, label: 'Métricas' },
    { id: 'admin-config', icon: I.settings, label: 'Configurações' },
  ];
  return (
    <aside className="fc-sidebar" style={{ background: '#0A1528' }}>
      <div className="fc-sidebar-brand">
        <BrandLockup dark size="md" />
        <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fc-dourado)', marginTop: 8, fontWeight: 700 }}>
          Painel Admin
        </div>
      </div>
      <nav className="fc-nav">
        {items.map(it => {
          const IconEl = it.icon;
          return (
            <button key={it.id} className={'fc-nav-item' + (active.startsWith(it.id) ? ' active' : '')} onClick={() => onNavigate(it.id)}>
              <IconEl size={18} />
              <span style={{ flex: 1, textAlign: 'left' }}>{it.label}</span>
            </button>
          );
        })}
      </nav>
      <div className="fc-sidebar-ftr">
        <button className="fc-nav-item" onClick={onToggleArea} style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>
          <I.user size={16} /> <span>Ver como aluno</span>
        </button>
        <button className="fc-nav-item" onClick={onLogout} style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>
          <I.logout size={16} /> <span>Sair</span>
        </button>
      </div>
    </aside>
  );
}

// ============ TOPBAR ============
function Topbar({ user, onProfile }) {
  return (
    <div className="fc-topbar">
      <div style={{ flex: 1 }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <button className="fc-btn fc-btn-ghost fc-btn-sm" style={{ position: 'relative' }}>
          <I.bell size={18} />
          <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, borderRadius: '50%', background: 'var(--fc-dourado)' }} />
        </button>
        {user.streakDias > 0 && (
          <div className="fc-streak-pill">
            <I.flame size={14} />
            <span>{user.streakDias} dias</span>
          </div>
        )}
        <button onClick={onProfile} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div className="fc-avatar" style={{ width: 34, height: 34, fontSize: 13 }}>{user.primeiroNome.charAt(0)}</div>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fc-azul-profundo)' }}>{user.primeiroNome}</div>
            <div style={{ fontSize: 11, color: 'var(--fc-gray-500)' }}>{user.planoLabel}</div>
          </div>
        </button>
      </div>
    </div>
  );
}

// ============ TWEAKS PANEL ============
function TweaksPanel({ state, setState, onClose }) {
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 200,
      width: 320, background: 'var(--fc-white)',
      borderRadius: 'var(--fc-r-lg)',
      boxShadow: '0 18px 40px rgba(15,27,51,0.22), 0 0 0 1px rgba(15,27,51,0.06)',
      border: '1px solid var(--fc-gray-200)',
      overflow: 'hidden',
    }}>
      <div style={{ padding: '14px 18px', background: 'var(--fc-azul-profundo)', color: 'white', display: 'flex', alignItems: 'center', gap: 10 }}>
        <I.sliders size={16} style={{ color: 'var(--fc-dourado)' }} />
        <div style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>Tweaks</div>
        <button onClick={onClose} style={{ color: 'rgba(255,255,255,0.6)' }}><I.x size={16} /></button>
      </div>
      <div style={{ padding: 18 }}>
        <div style={{ marginBottom: 18 }}>
          <div className="fc-label" style={{ color: 'var(--fc-gray-700)' }}>Área ativa</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 4 }}>
            {[['aluno', 'Aluno'], ['admin', 'Admin']].map(([v, l]) => (
              <button key={v} onClick={() => setState({ ...state, area: v })}
                className="fc-btn fc-btn-sm" style={{
                  background: state.area === v ? 'var(--fc-azul-profundo)' : 'var(--fc-gray-100)',
                  color: state.area === v ? 'white' : 'var(--fc-gray-700)',
                }}>{l}</button>
            ))}
          </div>
        </div>

        <div style={{ marginBottom: 18 }}>
          <div className="fc-label" style={{ color: 'var(--fc-gray-700)' }}>Persona do aluno</div>
          <div style={{ display: 'grid', gap: 6, marginTop: 4 }}>
            {[
              ['anual-ativo', 'Anual ativo (40% progresso)'],
              ['mensal', 'Mensal ativo'],
              ['recem', 'Recém-cadastrado (M3/M4 bloqueados)'],
              ['expirado', 'Acesso expirado'],
            ].map(([v, l]) => (
              <button key={v} onClick={() => setState({ ...state, persona: v })}
                className="fc-btn fc-btn-sm" style={{
                  background: state.persona === v ? 'var(--fc-cream-deep)' : 'var(--fc-gray-50)',
                  color: 'var(--fc-gray-800)', justifyContent: 'flex-start',
                  border: state.persona === v ? '1px solid var(--fc-dourado)' : '1px solid var(--fc-gray-200)',
                  textAlign: 'left',
                }}>
                <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid ' + (state.persona === v ? 'var(--fc-dourado)' : 'var(--fc-gray-400)'), background: state.persona === v ? 'var(--fc-dourado)' : 'transparent', flexShrink: 0 }} />
                {l}
              </button>
            ))}
          </div>
        </div>

        <div style={{ marginBottom: 18 }}>
          <div className="fc-label" style={{ color: 'var(--fc-gray-700)' }}>Progresso override</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginTop: 4 }}>
            {[null, 0, 40, 100].map(v => (
              <button key={String(v)} onClick={() => setState({ ...state, progressoOverride: v })}
                className="fc-btn fc-btn-sm" style={{
                  background: state.progressoOverride === v ? 'var(--fc-azul-profundo)' : 'var(--fc-gray-100)',
                  color: state.progressoOverride === v ? 'white' : 'var(--fc-gray-700)',
                }}>{v === null ? 'auto' : v + '%'}</button>
            ))}
          </div>
        </div>

        <div>
          <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
            <div style={{
              width: 34, height: 20, borderRadius: 10, position: 'relative',
              background: state.proximoVencimento ? 'var(--fc-dourado)' : 'var(--fc-gray-300)',
              transition: 'all 180ms',
            }} onClick={() => setState({ ...state, proximoVencimento: !state.proximoVencimento })}>
              <div style={{ width: 16, height: 16, borderRadius: '50%', background: 'white', position: 'absolute', top: 2, left: state.proximoVencimento ? 16 : 2, transition: 'all 180ms', boxShadow: '0 1px 3px rgba(0,0,0,0.15)' }} />
            </div>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fc-gray-800)' }}>Simular "próximo do vencimento"</div>
          </label>
          <div className="fc-caption" style={{ marginTop: 4, marginLeft: 44 }}>Mostra o banner de renovação no dashboard</div>
        </div>
      </div>
    </div>
  );
}

// ============ ROOT APP ============
function App() {
  const initialState = React.useMemo(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('fc-app-state') || 'null');
      if (saved) return saved;
    } catch (e) {}
    return {
      view: 'login',
      area: 'aluno',
      persona: 'anual-ativo',
      progressoOverride: null,
      proximoVencimento: false,
      aulaAtualId: null,
      alunoDetalheId: null,
    };
  }, []);

  const [state, setStateRaw] = React.useState(initialState);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [toastQueue, setToastQueue] = React.useState([]);

  const setState = (next) => {
    setStateRaw(next);
    try { localStorage.setItem('fc-app-state', JSON.stringify(next)); } catch (e) {}
  };

  // Keyboard shortcut: press 'T' to open tweaks
  React.useEffect(() => {
    const handler = (e) => {
      if (e.key === 't' && !['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) {
        setTweaksOpen(v => !v);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  // Tweak-able knobs — host integration
  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  // Derive user from persona
  const user = React.useMemo(() => {
    const persona = FC_PERSONAS[state.persona] || FC_PERSONAS['anual-ativo'];
    return { ...persona, progresso: state.progressoOverride ?? persona.progresso };
  }, [state.persona, state.progressoOverride]);

  // Toast mechanism
  const toast = (msg, opts = {}) => {
    const id = Math.random().toString(36).slice(2);
    setToastQueue(q => [...q, { id, msg, ...opts }]);
    setTimeout(() => setToastQueue(q => q.filter(t => t.id !== id)), 3200);
  };
  window.__fcToast = toast;

  const login = () => setState({ ...state, view: state.area === 'admin' ? 'admin-dashboard' : 'aluno-dashboard' });
  const logout = () => setState({ ...state, view: 'login' });
  const navigate = (id) => setState({ ...state, view: id });
  const openAula = (aulaId) => setState({ ...state, view: 'aluno-aula', aulaAtualId: aulaId });
  const editarAula = (aulaId) => setState({ ...state, view: 'admin-aula-edit', aulaAtualId: aulaId });
  const verAluno = (alunoId) => setState({ ...state, view: 'admin-aluno-detalhe', alunoDetalheId: alunoId });
  const toggleArea = () => {
    const newArea = state.area === 'aluno' ? 'admin' : 'aluno';
    const newView = newArea === 'admin' ? 'admin-dashboard' : 'aluno-dashboard';
    setState({ ...state, area: newArea, view: newView });
  };

  // ----- LOGIN (no shell) -----
  if (state.view === 'login') {
    return (
      <>
        <LoginScreen onLogin={login} />
        <TweaksFab onClick={() => setTweaksOpen(true)} />
        {tweaksOpen && <TweaksPanel state={state} setState={setState} onClose={() => setTweaksOpen(false)} />}
        <ToastStack items={toastQueue} />
      </>
    );
  }

  // ----- ADMIN SHELL -----
  if (state.view.startsWith('admin')) {
    let screen;
    if (state.view === 'admin-dashboard') screen = <AdminDashboard onNavigate={navigate} />;
    else if (state.view === 'admin-aulas') screen = <AdminAulas onEditar={editarAula} />;
    else if (state.view === 'admin-aula-edit') screen = <AdminAulaEdit aulaId={state.aulaAtualId} onBack={() => navigate('admin-aulas')} />;
    else if (state.view === 'admin-alunos') screen = <AdminAlunos onVerAluno={verAluno} />;
    else if (state.view === 'admin-aluno-detalhe') screen = <AdminAlunoDetalhe alunoId={state.alunoDetalheId} onBack={() => navigate('admin-alunos')} />;
    else if (state.view === 'admin-duvidas') screen = <AdminDuvidas />;
    else if (state.view === 'admin-metricas') screen = <AdminMetricas />;
    else if (state.view === 'admin-config') screen = <AdminConfig />;
    else screen = <AdminDashboard onNavigate={navigate} />;

    return (
      <>
        <div className="fc-app">
          <AdminSidebar active={state.view} onNavigate={navigate} onToggleArea={toggleArea} onLogout={logout} />
          <div className="fc-main">
            <div className="fc-topbar">
              <div style={{ flex: 1, fontSize: 13, color: 'var(--fc-gray-600)' }}>
                Painel administrativo · Prof. Vinícius Ferraz
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <button className="fc-btn fc-btn-ghost fc-btn-sm"><I.bell size={18} /></button>
                <div className="fc-avatar" style={{ width: 32, height: 32, overflow: 'hidden' }}>
                  <img src={FC_ASSETS.foto} alt="Prof. Vinícius Ferraz" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
              </div>
            </div>
            <div className="fc-content">{screen}</div>
          </div>
        </div>
        <TweaksFab onClick={() => setTweaksOpen(true)} />
        {tweaksOpen && <TweaksPanel state={state} setState={setState} onClose={() => setTweaksOpen(false)} />}
        <ToastStack items={toastQueue} />
      </>
    );
  }

  // ----- ALUNO SHELL -----
  let screen;
  if (state.view === 'aluno-dashboard') screen = <AlunoDashboard user={user} state={state} onNavigate={navigate} onOpenAula={openAula} />;
  else if (state.view === 'aluno-aulas') screen = <AulasList user={user} onOpenAula={openAula} />;
  else if (state.view === 'aluno-aula') screen = <AulaPage aulaId={state.aulaAtualId} user={user} onOpenAula={openAula} onBack={() => navigate('aluno-aulas')} />;
  else if (state.view === 'aluno-duvidas') screen = <DuvidasFeed user={user} onOpenAula={openAula} />;
  else if (state.view === 'aluno-mentoria') screen = <Mentoria user={user} />;
  else if (state.view === 'aluno-certificado') screen = <Certificado user={user} />;
  else if (state.view === 'aluno-perfil') screen = <Perfil user={user} />;
  else screen = <AlunoDashboard user={user} state={state} onNavigate={navigate} onOpenAula={openAula} />;

  return (
    <>
      <div className="fc-app">
        <AlunoSidebar active={state.view} onNavigate={navigate} onLogout={logout} onToggleArea={toggleArea} user={user} />
        <div className="fc-main">
          <Topbar user={user} onProfile={() => navigate('aluno-perfil')} />
          <div className="fc-content">{screen}</div>
        </div>
      </div>
      <TweaksFab onClick={() => setTweaksOpen(true)} />
      {tweaksOpen && <TweaksPanel state={state} setState={setState} onClose={() => setTweaksOpen(false)} />}
      <ToastStack items={toastQueue} />
    </>
  );
}

function TweaksFab({ onClick }) {
  return (
    <button onClick={onClick} style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 90,
      width: 48, height: 48, borderRadius: '50%',
      background: 'var(--fc-azul-profundo)', color: 'var(--fc-dourado)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 8px 20px rgba(15,27,51,0.3)',
      border: '1px solid rgba(200,168,75,0.3)',
    }} title="Tweaks (atalho: T)">
      <I.sliders size={20} />
    </button>
  );
}

function ToastStack({ items }) {
  return (
    <div style={{ position: 'fixed', bottom: 20, left: 20, zIndex: 300, display: 'flex', flexDirection: 'column', gap: 8 }}>
      {items.map(t => {
        const IconEl = t.icon || I.info;
        return (
          <div key={t.id} style={{
            background: t.gold ? 'var(--fc-azul-profundo)' : 'var(--fc-gray-800)',
            color: 'white', padding: '12px 16px', borderRadius: 8,
            display: 'flex', alignItems: 'center', gap: 10, minWidth: 260,
            boxShadow: '0 8px 20px rgba(15,27,51,0.2)',
            borderLeft: t.gold ? '3px solid var(--fc-dourado)' : 'none',
            animation: 'fcSlideUp 220ms ease-out',
          }}>
            <IconEl size={18} style={{ color: t.gold ? 'var(--fc-dourado)' : 'white', flexShrink: 0 }} />
            <div style={{ fontSize: 13, fontWeight: 500 }}>{t.msg}</div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { App, AdminAlunoDetalhe });
