// ===========================================================
// DEAD SAILOR · PROJECT DOCK · APP / ROUTER
// ===========================================================

const { useState: useS, useEffect: useE, useCallback: useC } = React;

// Garante que API está disponível; exibe erro recuperável se ds-bridge.js falhar
function getAPI() {
  if (window.API) return window.API;
  throw new Error('Serviço indisponível. Verifique sua conexão e recarregue a página.');
}
var API = window.API || {};

function Login({ onEnter }){
  const [email, setEmail] = useS('');
  const [password, setPassword] = useS('');
  const [error, setError] = useS('');
  const [loading, setLoading] = useS(false);
  const [rememberMe, setRememberMe] = useS(true);
  const [hoverBack, setHoverBack] = useS(false);
  const [showForm, setShowForm] = useS(false);
  const [typedKeys, setTypedKeys] = useS('');

  useE(() => {
    if (showForm) return;
    function handleKeyDown(e) {
      if (e.key.length === 1) {
        setTypedKeys(prev => {
          const next = (prev + e.key.toLowerCase()).slice(-20);
          if (next.endsWith('dsadmin') || next.endsWith('deadsailor')) {
            setShowForm(true);
          }
          return next;
        });
      }
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [showForm]);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      if (!window.API) throw new Error('Serviço indisponível. Recarregue a página.');
      const res = await window.API.login(email, password, rememberMe);
      onEnter(res.user.role);
    } catch (err) {
      setError(err.message || 'Erro ao autenticar. Verifique suas credenciais.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="login" data-screen-label="00 Login">
      <div className="left">
        <div className="bg"></div>

        <div className="brand-strip">
          <span className="logo" aria-label="Dead Sailor"></span>
          <span className="sep"></span>
          <span className="tag">PROJECT DOCK <span className="sig">· v0.1</span></span>
          <a href="../" 
             className="back-btn" 
             onMouseEnter={() => setHoverBack(true)}
             onMouseLeave={() => setHoverBack(false)}
             style={{
               marginLeft: 'auto', 
               fontFamily: 'var(--mono)', 
               fontSize: 10, 
               letterSpacing: '.18em', 
               color: hoverBack ? 'var(--signal)' : 'var(--bone-dim)', 
               textTransform: 'uppercase', 
               textDecoration: 'none', 
               display: 'flex', 
               alignItems: 'center', 
               gap: 8, 
               transition: 'all 0.2s ease'
             }}>
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.2" style={{transform: 'rotate(180deg)', transition: 'transform 0.2s ease', transform: hoverBack ? 'rotate(180deg) translateX(3px)' : 'rotate(180deg)'}}><path d="M2 6h8M7 3l3 3-3 3"/></svg>
            <span>Voltar ao site</span>
          </a>
        </div>

        <div className="center-block">
          {!showForm ? (
            <div style={{ animation: 'fadeIn 1s ease', display: 'flex', flexDirection: 'column', gap: 24 }}>
              <span className="kicker">// DOCK CONNECTIVITY · OFFLINE</span>
              <h1 className="title" style={{ fontSize: '2.5rem', textTransform: 'uppercase', letterSpacing: '-0.02em', lineHeight: 1.1 }}>
                SISTEMA<br/><em style={{ color: 'var(--bone-dim)', fontStyle: 'italic' }}>RESTRITO.</em>
              </h1>
              <p className="lede" style={{ color: 'var(--bone-dim)', opacity: 0.6 }}>
                Esta estação de trabalho está fora da grade pública. Para restabelecer o link operacional, digite a chave de segurança física.
              </p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16 }}>
                <span className="auth-pulse-dot" style={{
                  width: 8,
                  height: 8,
                  background: 'var(--bone-dim)',
                  borderRadius: '50%',
                  opacity: 0.3,
                  animation: 'pulse 2s infinite ease-in-out'
                }}></span>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.2em', color: 'var(--bone-dim)', opacity: 0.5, textTransform: 'uppercase' }}>
                  Aguardando chave física...
                </span>
              </div>
            </div>
          ) : (
            <div style={{ animation: 'fadeIn 0.5s ease' }}>
              <span className="kicker">// PORTAL · ROUTE 014</span>
              <h1 className="title">Acesse seu<br/><em>Project Dock.</em></h1>
              <p className="lede">Seu espaço para acompanhar cada etapa da jornada criativa — briefings, aprovações, cronogramas e arquivos finais.</p>

              <form onSubmit={handleSubmit}>
                <div className="field">
                  <label>// E-mail</label>
                  <input type="email" placeholder="seu@email.com" value={email} onChange={e => setEmail(e.target.value)} required />
                </div>
                <div className="field">
                  <label>// Senha</label>
                  <input type="password" placeholder="••••••••••" value={password} onChange={e => setPassword(e.target.value)} required />
                </div>

                <div className="keep-logged-row" style={{display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, marginBottom: 12, userSelect: 'none'}}>
                  <div 
                    role="checkbox"
                    aria-checked={rememberMe}
                    tabIndex={0}
                    onClick={() => setRememberMe(!rememberMe)}
                    onKeyDown={(e) => {
                      if (e.key === ' ' || e.key === 'Enter') {
                        e.preventDefault();
                        setRememberMe(!rememberMe);
                      }
                    }}
                    style={{display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.12em', color: 'var(--bone-dim)', textTransform: 'uppercase', outline: 'none'}}
                  >
                    <div style={{
                      width: 14, 
                      height: 14, 
                      display: 'grid', 
                      placeItems: 'center',
                      border: '1px solid var(--steel-3)',
                      background: rememberMe ? 'var(--signal)' : 'transparent',
                      boxShadow: rememberMe ? '0 0 8px var(--signal)' : 'none',
                      borderRadius: 2,
                      transition: 'all 0.2s ease',
                      flexShrink: 0
                    }}>
                      {rememberMe && (
                        <svg width="8" height="8" viewBox="0 0 12 12" fill="none" stroke="var(--abyss)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M2.5 6.5L5 9l4.5-5.5"/>
                        </svg>
                      )}
                    </div>
                    <span style={{ transition: 'color 0.2s ease', color: rememberMe ? 'var(--bone)' : 'var(--bone-dim)' }}>Manter conectado</span>
                  </div>
                </div>

                {error && <div className="form-error" style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.16em', color:'#D97757', padding:'8px 0'}}>{error}</div>}

                <div className="row" style={{marginTop:20}}>
                  <Button type="submit" kind="primary" arrow disabled={loading}>{loading ? 'Entrando...' : 'Entrar'}</Button>
                  <a href="#" className="forgot" onClick={e=>e.preventDefault()}>Esqueci minha senha</a>
                </div>
              </form>
            </div>
          )}
        </div>

        <div className="footer-strip">
          <span>// DEAD SAILOR · CREATIVE LAB</span>
          <span>RIO DE JANEIRO · BR</span>
        </div>
      </div>

      <div className="right">
        <div className="coord-top"><span className="dot"></span><span>22°54′S · 43°10′W</span></div>
        <span className="corner-tl"></span><span className="corner-tr"></span>
        <span className="corner-bl"></span><span className="corner-br"></span>

        <svg className="chart" viewBox="0 0 600 800" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <pattern id="dots" x="0" y="0" width="24" height="24" patternUnits="userSpaceOnUse">
              <circle cx="12" cy="12" r="0.6" fill="rgba(232,226,216,.18)" />
            </pattern>
            <pattern id="grid" x="0" y="0" width="48" height="48" patternUnits="userSpaceOnUse">
              <path d="M48 0H0V48" fill="none" stroke="rgba(232,226,216,.05)" />
            </pattern>
          </defs>
          <rect width="600" height="800" fill="url(#grid)" />
          <rect width="600" height="800" fill="url(#dots)" />
          <path d="M40 720 C 180 600, 240 540, 320 420 S 480 240, 560 100"
                fill="none" stroke="rgba(0,255,102,.55)" strokeWidth="1" strokeDasharray="3 4" />
          <path d="M40 720 C 180 600, 240 540, 320 420 S 480 240, 560 100"
                fill="none" stroke="rgba(0,255,102,.18)" strokeWidth="6" filter="blur(2px)" />
          {[[40,720],[180,600],[320,420],[480,240],[560,100]].map(([cx,cy], i) => (
            <g key={i}>
              <circle cx={cx} cy={cy} r="3" fill={i===2?'#00FF66':'rgba(232,226,216,.35)'} />
              {i===2 && <circle cx={cx} cy={cy} r="9" fill="none" stroke="#00FF66" strokeOpacity="0.35" />}
            </g>
          ))}
          <text x="48" y="700" fontFamily="Geist Mono" fontSize="11" fill="rgba(232,226,216,.4)" letterSpacing="2">START</text>
          <text x="500" y="92" fontFamily="Geist Mono" fontSize="11" fill="rgba(0,255,102,.7)" letterSpacing="2">N°014</text>
        </svg>

        <div className="word-stack">
          <div className="map">Built<br/>beyond<br/><em>the map.</em></div>
          <div className="sub">// SYSTEM 001 · ROUTE 014 · LIVE</div>
        </div>

        <div className="coord-bot">
          <span>// DS / TERRITORY 014</span>
          <span>BRASIL · MMXXVI</span>
        </div>
      </div>
    </div>
  );
}


// ====================================================================
// APP shell with hash routing
// ====================================================================
function App(){
  const [route, setRoute] = useS(null);
  const [user, setUser] = useS(null);
  const [loading, setLoading] = useS(true);

  const [showChangePassword, setShowChangePassword] = useS(false);
  const [newPassword, setNewPassword] = useS('');
  const [confirmPassword, setConfirmPassword] = useS('');
  const [changingPass, setChangingPass] = useS(false);
  const [passToast, setPassToast] = window.useToast ? window.useToast() : useS(null);

  useE(() => {
    function handleShow() {
      setShowChangePassword(true);
    }
    window.addEventListener('ds-show-change-password', handleShow);
    return () => window.removeEventListener('ds-show-change-password', handleShow);
  }, []);

  async function handleChangePassword(e) {
    if (e) e.preventDefault();
    if (!newPassword.trim()) {
      setPassToast('A senha não pode estar em branco.');
      return;
    }
    if (newPassword !== confirmPassword) {
      setPassToast('As senhas não coincidem.');
      return;
    }
    setChangingPass(true);
    try {
      const email = user?.email || (JSON.parse(localStorage.getItem('ds_user') || '{}').email);
      if (!email) throw new Error('E-mail do usuário não encontrado.');
      await window.API.resetUserPassword(email, newPassword);
      setPassToast('Senha alterada com sucesso!');
      setShowChangePassword(false);
      setNewPassword('');
      setConfirmPassword('');
    } catch (err) {
      setPassToast('Erro ao alterar senha: ' + err.message);
    } finally {
      setChangingPass(false);
    }
  }

  useE(() => {
    async function init() {
      // Se não há API disponível, vai direto para o login
      if (!window.API) {
        setRoute({ profile: null, view: 'login' });
        setLoading(false);
        return;
      }
      const _api = window.API;
      const token = _api.token;

      // Sem token salvo: não há necessidade de mostrar loading, vai direto ao login
      if (!token) {
        const hashInfo = parseHash() || { profile: null, view: 'login' };
        if (hashInfo.profile) {
          // Tentou acessar rota protegida sem token
          _api.token = null;
          go('/login');
          setRoute({ profile: null, view: 'login' });
        } else {
          setRoute(hashInfo);
        }
        setLoading(false);
        return;
      }

      // Há token: valida sessão com o servidor
      try {
        const userData = await _api.me();
        setUser(userData);
        const hashInfo = parseHash();
        
        const isStaff = userData.role !== 'client';
        const expectedProfile = isStaff ? 'admin' : 'client';
        const defaultView = userData.role === 'collaborator' ? 'projects' : 'home';

        if (hashInfo && hashInfo.profile) {
          if (hashInfo.profile !== expectedProfile) {
            setRoute({ profile: expectedProfile, view: defaultView });
            go(`/${expectedProfile}/${defaultView}`);
          } else {
            // Se for colaborador acessando home/dashboard ou outra rota restrita
            if (userData.role === 'collaborator' && hashInfo.profile === 'admin' && hashInfo.view !== 'projects' && hashInfo.view !== 'project' && hashInfo.view !== 'planning') {
              setRoute({ profile: 'admin', view: 'projects' });
              go('/admin/projects');
            } else if (userData.role === 'leader' && hashInfo.profile === 'admin' && hashInfo.view === 'settings') {
              setRoute({ profile: 'admin', view: 'home' });
              go('/admin/home');
            } else {
              setRoute(hashInfo);
            }
          }
        } else {
          setRoute({ profile: expectedProfile, view: defaultView });
          go(`/${expectedProfile}/${defaultView}`);
        }
      } catch (err) {
        _api.token = null;
        setRoute({ profile: null, view: 'login' });
      } finally {
        setLoading(false);
      }
    }
    init();
  }, []);

  useE(() => {
    function onHash(){
      const h = parseHash();
      if (h) {
        if (h.profile && !window.API?.token) {
          go('/login');
          setRoute({ profile: null, view: 'login' });
          return;
        }

        // Valida permissões de rota se o usuário já estiver carregado
        if (user) {
          const isStaff = user.role !== 'client';
          const expectedProfile = isStaff ? 'admin' : 'client';

          if (h.profile !== expectedProfile) {
            const defaultView = user.role === 'collaborator' ? 'projects' : 'home';
            go(`/${expectedProfile}/${defaultView}`);
            return;
          }

          if (user.role === 'collaborator' && h.profile === 'admin' && h.view !== 'projects' && h.view !== 'project' && h.view !== 'planning') {
            go('/admin/projects');
            return;
          }

          if (user.role === 'leader' && h.profile === 'admin' && h.view === 'settings') {
            go('/admin/home');
            return;
          }
        }
        setRoute(h);
      }
    }
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [user]);

  function parseHash(){
    const h = (window.location.hash || '').replace(/^#/, '');
    if(!h || h === '/' || h === '/login') return { profile: null, view: 'login' };
    const parts = h.split('/').filter(Boolean);
    const profile = parts[0];
    if(profile !== 'client' && profile !== 'admin') return null;
    const view = parts[1] || 'home';
    const arg = parts.slice(2).join('/');
    return { profile, view, arg };
  }

  function go(path){
    window.location.hash = path;
  }

  function navigate(key){
    const profile = route?.profile;
    if(!profile) { go('/login'); return; }

    if(key === 'logout') {
      if (window.API) window.API.logout();
      setUser(null);
      go('/login');
      return;
    }
    if(key === 'home'){
      if (user?.role === 'collaborator') {
        go('/admin/projects');
      } else {
        go(`/${profile}`);
      }
      return;
    }

    if(profile === 'client'){
      if(key === 'projects') return go('/client/projects');
      if(key === 'company')   return go('/client/company');
      if(key === 'brief-form') return go('/client/brief/form');
      if(key === 'brief-confirmed') return go('/client/brief/confirmed');
      if(key.startsWith('project-')) return go('/client/project/'+key.slice(8));
      return go('/client/'+key);
    }

    if(profile === 'admin'){
      if(key === 'briefings')  return go('/admin/briefings');
      if(key === 'projects')   return go('/admin/projects');
      if(key === 'clients')    return go('/admin/clients');
      if(key === 'settings')   return go('/admin/settings');
      if(key === 'planning')   return go('/admin/planning');
      if(key.startsWith('briefing-analysis-')) return go('/admin/briefing/'+key.slice(18));
      if(key.startsWith('admin-project-')) return go('/admin/project/'+key.slice(14));
      return go('/admin/'+key);
    }
  }

  function handleLogin(role) {
    const profile = role === 'client' ? 'client' : 'admin';
    const defaultView = role === 'collaborator' ? 'projects' : 'home';
    go(`/${profile}/${defaultView}`);
  }

  if (loading) {
    return (
      <div style={{minHeight:'100vh', display:'grid', placeItems:'center', background:'#08090a', color:'#00FF66', fontFamily:'monospace', fontSize:11, letterSpacing:'.3em', textTransform:'uppercase'}}>
        <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:24}}>
          <span style={{fontSize:36}}>⚓</span>
          <span>Conectando ao Project Dock...</span>
        </div>
      </div>
    );
  }

  if(!route || route.view === 'login'){
    return <Login onEnter={handleLogin} />;
  }

  const profile = route.profile;
  const D = window.DS_DATA;

  let content = null;
  let crumb = ['Dead Sailor', profile === 'client' ? 'Project Dock · Cliente' : 'Operations Dock', 'Dashboard'];
  let current = 'home';

  if(profile === 'client'){
    if(route.view === 'home'){ content = <ClientDashboard navigate={navigate} />; current = 'home'; crumb = ['Dead Sailor', 'Project Dock · Cliente', 'Dashboard']; }
    else if(route.view === 'projects'){ content = <ClientProjectsList navigate={navigate} />; current = 'projects'; crumb = ['Dead Sailor', 'Project Dock', 'Meus projetos']; }
    else if(route.view === 'project'){ content = <ClientProject projectId={route.arg} navigate={navigate} />; current = 'projects'; crumb = ['Project Dock', 'Projetos', 'Detalhe']; }
    else if(route.view === 'approvals'){ content = <ClientApprovals navigate={navigate} />; current = 'approvals'; crumb = ['Project Dock', 'Aprovações']; }
    else if(route.view === 'files'){ content = <ClientFilesPage />; current = 'files'; crumb = ['Project Dock', 'Arquivos finais']; }
    else if(route.view === 'brief'){
      if(route.arg === 'form'){ content = <BriefingForm navigate={navigate} />; current = 'home'; crumb = ['Project Dock', 'Briefing', 'Em preenchimento']; }
      else if(route.arg === 'confirmed'){ content = <BriefingConfirmed navigate={navigate} />; current = 'home'; crumb = ['Project Dock', 'Briefing', 'Enviado']; }
      else { content = <FirstAccess navigate={navigate} />; current = 'home'; crumb = ['Project Dock', 'Briefing pendente']; }
    }
    else { content = <ComingSoon name={labelize(route.view)} />; current = route.view; crumb = ['Project Dock', labelize(route.view)]; }
  }
  else if(profile === 'admin'){
    if(route.view === 'home'){ content = <AdminDashboard navigate={navigate} />; current = 'home'; crumb = ['Dead Sailor', 'Operations Dock', 'Dashboard']; }
    else if(route.view === 'briefings'){ content = <AdminBriefings navigate={navigate} />; current = 'briefings'; crumb = ['Operations Dock', 'Briefings']; }
    else if(route.view === 'briefing'){ content = <BriefingAnalysis briefingId={route.arg} navigate={navigate} />; current = 'briefings'; crumb = ['Operations Dock', 'Briefings', 'Análise']; }
    else if(route.view === 'projects'){ content = <AdminProjects navigate={navigate} />; current = 'projects'; crumb = ['Operations Dock', 'Projetos']; }
    else if(route.view === 'project'){ content = <AdminProject projectId={route.arg} navigate={navigate} />; current = 'projects'; crumb = ['Operations Dock', 'Projetos', 'Detalhe']; }
    else if(route.view === 'planning'){ content = <AdminPlanning navigate={navigate} />; current = 'projects'; crumb = ['Operations Dock', 'Projetos', 'Planejamento']; }
    else if(route.view === 'settings'){ content = <AdminSettings navigate={navigate} />; current = 'settings'; crumb = ['Operations Dock', 'Configurações']; }
    else if(route.view === 'clients'){ content = <AdminClients navigate={navigate} />; current = 'clients'; crumb = ['Operations Dock', 'Clientes']; }
    else { content = <ComingSoon name={labelize(route.view)} />; current = route.view; crumb = ['Operations Dock', labelize(route.view)]; }
  }

  return (
    <div className="shell">
      <Sidebar profile={profile} current={current} navigate={navigate} />
      <main className="main">
        <Topbar crumb={crumb} profile={profile} />
        {content}
      </main>

      {showChangePassword && (
        <window.Modal title="ALTERAR SENHA DE ACESSO" onClose={() => setShowChangePassword(false)}>
          <form onSubmit={handleChangePassword} style={{display:'flex', flexDirection:'column', gap:18, padding:'8px 4px'}}>
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.24em', color:'var(--signal)', textTransform:'uppercase', marginBottom:6}}>// SEGURANÇA DA CONTA</div>
            <p style={{fontSize:13, lineHeight:1.6, color:'var(--bone-dim)', fontWeight:300, marginBottom:8}}>
              Escolha uma nova senha forte para acessar seu painel do Project Dock. Ela será atualizada imediatamente no banco de dados.
            </p>
            <window.Field label="Nova Senha" required>
              <input type="password" placeholder="Mínimo 6 caracteres" value={newPassword} onChange={e => setNewPassword(e.target.value)} required style={{fontFamily:'monospace'}} />
            </window.Field>
            <window.Field label="Confirmar Nova Senha" required>
              <input type="password" placeholder="Repita a nova senha" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} required style={{fontFamily:'monospace'}} />
            </window.Field>
            <div style={{marginTop: 8, display: 'flex', justifyContent: 'flex-end', gap: 10}}>
              <window.Button kind="ghost" onClick={() => setShowChangePassword(false)}>Cancelar</window.Button>
              <window.Button kind="primary" arrow onClick={handleChangePassword} disabled={changingPass}>
                {changingPass ? 'Alterando...' : 'Confirmar Alteração'}
              </window.Button>
            </div>
          </form>
        </window.Modal>
      )}

      {passToast && <window.Toast>{passToast}</window.Toast>}
    </div>
  );
}

function labelize(v){
  const map = {
    notifications: 'Notificações',
    company: 'Minha empresa',
    approvals: 'Aprovações',
    reviews: 'Revisões',
    deliveries: 'Entregas',
    clients: 'Clientes',
    files: 'Arquivos',
    settings: 'Configurações',
  };
  return map[v] || v;
}

function ComingSoon({ name }){
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="kicker">§ · EM CONSTRUÇÃO</div>
          <h1>{name}</h1>
          <p className="sub">Esta seção será publicada em uma próxima rota do sistema. Por enquanto, os fluxos críticos — briefings, projetos, aprovações, cronogramas e arquivos — estão funcionais nos demais módulos.</p>
        </div>
        <div className="right">
          <div className="stamp"><span className="dot"></span><span>PRÓXIMA ROTA</span></div>
        </div>
      </div>
      <div className="empty" style={{padding:'72px 24px', fontSize:11}}>
        // SECTION OUT OF SCOPE FOR PROTOTYPE v0.1
      </div>
    </div>
  );
}

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