// Main App: top bar, view router, drawer mounting.
const APPIcons = window.Icons;
const SESSION_KEY = 'akis_pm_session_v1';
const API_BASE = './api';

async function apiRequest(path, options = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...(options.headers || {}),
    },
    ...options,
  });
  const text = await res.text();
  const data = text ? JSON.parse(text) : {};
  if (!res.ok || data.ok === false) {
    const err = new Error(data.error || `API error ${res.status}`);
    err.status = res.status;
    throw err;
  }
  return data;
}

function App() {
  const store = window.PMStore.useStore();
  const { state } = store;
  const [session, setSession] = React.useState(() => {
    try {
      const raw = localStorage.getItem(SESSION_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch (e) {
      return null;
    }
  });
  const [query, setQuery] = React.useState('');
  const [selectedTaskId, setSelectedTaskId] = React.useState(null);
  const [syncStatus, setSyncStatus] = React.useState('local');
  const [remoteReady, setRemoteReady] = React.useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(() => {
    try {
      return localStorage.getItem('akis_sidebar_collapsed') === '1';
    } catch (e) {
      return false;
    }
  });

  const loadRemoteState = async () => {
    const data = await apiRequest('/state.php');
    if (data.state) {
      store.replaceState(data.state);
      setRemoteReady(true);
      setSyncStatus('online');
    }
  };

  const login = async (user) => {
    const cleanEmail = user.email;
    const publicUser = {
      email: cleanEmail,
      name: user.name,
      remember: user.remember,
      signedInAt: user.signedInAt,
    };
    let nextUser = publicUser;
    try {
      const data = await apiRequest('/auth.php?action=login', {
        method: 'POST',
        body: JSON.stringify({ email: cleanEmail, password: user.password }),
      });
      nextUser = data.user || user;
      localStorage.setItem(SESSION_KEY, JSON.stringify(nextUser));
      setSession(nextUser);
      await loadRemoteState();
    } catch (e) {
      if (e.status === 401 || e.status === 422) {
        localStorage.removeItem(SESSION_KEY);
        throw e;
      }
      nextUser = { ...publicUser, offline: true };
      localStorage.setItem(SESSION_KEY, JSON.stringify(nextUser));
      setSession(nextUser);
      setRemoteReady(false);
      setSyncStatus('local');
    }
  };
  const logout = async () => {
    try { await apiRequest('/auth.php?action=logout', { method: 'POST', body: '{}' }); } catch (e) {}
    localStorage.removeItem(SESSION_KEY);
    setSelectedTaskId(null);
    setRemoteReady(false);
    setSyncStatus('local');
    setSession(null);
  };
  const clearLocalSession = () => {
    localStorage.removeItem(SESSION_KEY);
    setRemoteReady(false);
    setSyncStatus('local');
    setSession(null);
  };
  const refreshCloudSession = async () => {
    try {
      const me = await apiRequest('/auth.php?action=me');
      if (me.user) {
        localStorage.setItem(SESSION_KEY, JSON.stringify(me.user));
        setSession(me.user);
      }
      await loadRemoteState();
    } catch (e) {
      setRemoteReady(false);
      setSyncStatus('local');
      if (e.status === 401) clearLocalSession();
    }
  };
  const toggleSidebar = () => {
    setSidebarCollapsed(v => {
      const next = !v;
      try { localStorage.setItem('akis_sidebar_collapsed', next ? '1' : '0'); } catch (e) {}
      return next;
    });
  };

  const selectedTask = selectedTaskId ? state.tasks.find(t => t.id === selectedTaskId) : null;

  const openTask = (id) => setSelectedTaskId(id);
  const closeTask = () => setSelectedTaskId(null);

  const quickAddTask = (data = {}) => {
    store.addTask({
      title: 'Yeni görev',
      status: data.status || 'todo',
      priority: 'medium',
      projectId: data.projectId || state.activeProjectId,
      ...data,
    });
  };

  // Open newest task after add
  const prevTaskCount = React.useRef(state.tasks.length);
  React.useEffect(() => {
    if (state.tasks.length > prevTaskCount.current) {
      const newest = [...state.tasks]
        .filter(t => t.createdAt)
        .sort((a,b) => new Date(b.createdAt) - new Date(a.createdAt))[0];
      if (newest) setSelectedTaskId(newest.id);
    }
    prevTaskCount.current = state.tasks.length;
  }, [state.tasks.length]);

  React.useEffect(() => {
    if (!session) return;
    refreshCloudSession();
  }, [session?.email]);

  React.useEffect(() => {
    if (!session || !remoteReady) return;
    const timer = setTimeout(() => {
      apiRequest('/state.php', {
        method: 'PUT',
        body: JSON.stringify({ state }),
      })
        .then(() => setSyncStatus('online'))
        .catch(() => setSyncStatus('offline'));
    }, 700);
    return () => clearTimeout(timer);
  }, [state, session?.email, remoteReady]);

  if (!session) {
    return <LoginScreen onLogin={login} />;
  }

  const activeProject = state.projects.find(p => p.id === state.activeProjectId);

  const isProjectView = state.activeView === 'kanban' || state.activeView === 'list';

  const viewTitle = (() => {
    if (state.activeView === 'dashboard') return 'Panel';
    if (state.activeView === 'all-tasks') return 'Tüm Görevler';
    if (state.activeView === 'calendar') return 'Takvim';
    if (state.activeView === 'kanban') return activeProject?.name || 'Kanban';
    if (state.activeView === 'list') return activeProject?.name || 'Liste';
    return '';
  })();

  const viewSubtitle = (() => {
    if (state.activeView === 'dashboard') return 'Genel bakış';
    if (state.activeView === 'all-tasks') return 'Tüm projeler · gruplama ve filtreleme';
    if (state.activeView === 'calendar') return 'Aylık görünüm';
    if (isProjectView && activeProject) {
      const count = state.tasks.filter(t => t.projectId === activeProject.id).length;
      return `${count} görev`;
    }
    return '';
  })();

  return (
    <div className={`app ${sidebarCollapsed ? 'sidebar-collapsed' : ''}`}>
      <window.Sidebar
        state={state}
        user={session}
        setActiveView={store.setActiveView}
        setActiveProject={store.setActiveProject}
        addProject={store.addProject}
        updateProject={store.updateProject}
        deleteProject={store.deleteProject}
        openNewTask={() => quickAddTask({ projectId: state.activeProjectId })}
        onLogout={logout}
      />

      <div className="main">
        <div className="topbar">
          <button
            className="icon-btn sidebar-toggle"
            onClick={toggleSidebar}
            title={sidebarCollapsed ? 'Sidebar genişlet' : 'Sidebar daralt'}
          >
            <APPIcons.PanelLeft size={17} />
          </button>

          <div className="topbar-title">
            {isProjectView && activeProject && (
              <div className="project-tile" style={{ background: activeProject.color, width: 32, height: 32, fontSize: 12 }}>
                {window.projectAbbr(activeProject.name)}
              </div>
            )}
            <div style={{ minWidth: 0 }}>
              <h1>{viewTitle}</h1>
              {viewSubtitle && <div className="crumb" style={{ marginTop: 1 }}>{viewSubtitle}</div>}
            </div>
          </div>

          {isProjectView && (
            <div className="view-tabs" style={{ marginLeft: 12 }}>
              <button
                className={`view-tab ${state.activeView === 'kanban' ? 'active' : ''}`}
                onClick={() => store.setActiveView('kanban')}
                aria-label="Kanban görünümü"
              ><APPIcons.Kanban size={14} /> <span className="vt-label">Kanban</span></button>
              <button
                className={`view-tab ${state.activeView === 'list' ? 'active' : ''}`}
                onClick={() => store.setActiveView('list')}
                aria-label="Liste görünümü"
              ><APPIcons.List size={14} /> <span className="vt-label">Liste</span></button>
            </div>
          )}

          <div className="topbar-spacer" />

          <div className="search-input">
            <APPIcons.Search size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
            <input
              placeholder="Görev ara..."
              value={query}
              onChange={e => setQuery(e.target.value)}
            />
          </div>

          <button
            className="icon-btn"
            onClick={() => store.setTheme(state.theme === 'dark' ? 'light' : 'dark')}
            title="Tema değiştir"
          >
            {state.theme === 'dark' ? <APPIcons.Sun size={17} /> : <APPIcons.Moon size={17} />}
          </button>
          <button className="icon-btn" title="Bildirimler" data-narrow-hide>
            <APPIcons.Bell size={17} />
          </button>
          <div className={`sync-pill sync-${syncStatus}`} title="Senkronizasyon durumu">
            {syncStatus === 'online' ? 'Bulut' : syncStatus === 'offline' ? 'Çevrimdışı' : 'Yerel'}
          </div>
          <button
            className="btn btn-primary"
            onClick={() => quickAddTask({ projectId: state.activeProjectId, status: 'todo' })}
          >
            <APPIcons.Plus size={15} strokeWidth={2.5} />
            <span className="btn-label">Yeni Görev</span>
          </button>
        </div>

        {state.activeView === 'dashboard' && (
          <window.Dashboard
            state={state}
            user={session}
            onSelectTask={openTask}
            setActiveView={store.setActiveView}
            setActiveProject={store.setActiveProject}
          />
        )}
        {state.activeView === 'all-tasks' && (
          <window.ListView
            state={state}
            query={query}
            scope="all"
            onSelectTask={openTask}
            onToggleDone={store.toggleTaskDone}
            onDeleteTask={store.deleteTask}
          />
        )}
        {state.activeView === 'kanban' && (
          <window.Kanban
            state={state}
            query={query}
            onSelectTask={openTask}
            onUpdateTask={store.updateTask}
            onDeleteTask={store.deleteTask}
            onAddTask={(data) => quickAddTask(data)}
          />
        )}
        {state.activeView === 'list' && (
          <window.ListView
            state={state}
            query={query}
            scope="project"
            onSelectTask={openTask}
            onToggleDone={store.toggleTaskDone}
            onDeleteTask={store.deleteTask}
          />
        )}
        {state.activeView === 'calendar' && (
          <window.CalendarView
            state={state}
            query={query}
            onSelectTask={openTask}
          />
        )}
      </div>

      {selectedTask && (
        <window.TaskDrawer
          task={selectedTask}
          state={state}
          onClose={closeTask}
          onUpdate={store.updateTask}
          onDelete={(id) => { store.deleteTask(id); closeTask(); }}
          onAddSubtask={store.addSubtask}
          onUpdateSubtask={store.updateSubtask}
          onRemoveSubtask={store.removeSubtask}
        />
      )}

      <TabletBottomNav
        state={state}
        setActiveView={store.setActiveView}
        setActiveProject={store.setActiveProject}
      />
    </div>
  );
}

function TabletBottomNav({ state, setActiveView, setActiveProject }) {
  const activeProject = state.projects.find(p => p.id === state.activeProjectId);
  const goProject = () => {
    if (!state.activeProjectId && state.projects[0]) setActiveProject(state.projects[0].id);
    setActiveView('kanban');
  };

  return (
    <nav className="tablet-bottom-nav" aria-label="iPad gezinme">
      <button className={state.activeView === 'dashboard' ? 'active' : ''} onClick={() => setActiveView('dashboard')}>
        <APPIcons.Dashboard size={18} />
        <span>Panel</span>
      </button>
      <button className={state.activeView === 'all-tasks' ? 'active' : ''} onClick={() => setActiveView('all-tasks')}>
        <APPIcons.CheckSquare size={18} />
        <span>Görevler</span>
      </button>
      <button className={state.activeView === 'calendar' ? 'active' : ''} onClick={() => setActiveView('calendar')}>
        <APPIcons.Calendar size={18} />
        <span>Takvim</span>
      </button>
      <button className={(state.activeView === 'kanban' || state.activeView === 'list') ? 'active' : ''} onClick={goProject}>
        <APPIcons.Folder size={18} />
        <span>{activeProject ? window.projectAbbr(activeProject.name) : 'Proje'}</span>
      </button>
    </nav>
  );
}

function LoginScreen({ onLogin }) {
  const [email, setEmail] = React.useState('admin@aktasweb.io');
  const [password, setPassword] = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    const cleanEmail = email.trim() || 'admin@aktasweb.io';
    if (!password.trim()) {
      setError('Şifre gerekli.');
      return;
    }
    const name = cleanEmail.split('@')[0]
      .split(/[._-]/)
      .filter(Boolean)
      .map(part => part.charAt(0).toLocaleUpperCase('tr-TR') + part.slice(1))
      .join(' ') || 'Hasan Aktaş';
    setLoading(true);
    try {
      await onLogin({ email: cleanEmail, password, name, remember, signedInAt: new Date().toISOString() });
    } catch (e) {
      setError(e.message || 'Giriş yapılamadı.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-shell">
      <div className="login-panel">
        <div className="login-brand">
          <div className="brand-mark">A</div>
          <div>
            <div className="brand-name">Akış</div>
            <div className="brand-sub">Proje Yönetimi</div>
          </div>
        </div>
        <div>
          <h1 className="login-title">Çalışma alanına giriş</h1>
          <p className="login-subtitle">Projeler, görevler ve takvim tek düzenli akışta.</p>
        </div>
        <form className="login-form" onSubmit={submit}>
          <label className="login-field">
            <span>E-posta</span>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="ad@firma.com"
              autoComplete="email"
            />
          </label>
          <label className="login-field">
            <span>Şifre</span>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="current-password"
            />
          </label>
          {error && <div className="login-error">{error}</div>}
          <div className="login-options">
            <label className="login-check">
              <input
                type="checkbox"
                checked={remember}
                onChange={e => setRemember(e.target.checked)}
              />
              <span>Beni hatırla</span>
            </label>
            <span>Demo alanı</span>
          </div>
          <button className="btn btn-primary login-submit" type="submit" disabled={loading}>
            <APPIcons.Check size={15} strokeWidth={2.5} />
            {loading ? 'Giriş Yapılıyor' : 'Giriş Yap'}
          </button>
        </form>
      </div>

      <div className="login-preview" aria-hidden="true">
        <div className="preview-top">
          <span></span><span></span><span></span>
        </div>
        <div className="preview-grid">
          <div className="preview-stat">
            <strong>23</strong>
            <span>Görev</span>
          </div>
          <div className="preview-stat warm">
            <strong>2</strong>
            <span>Bugün</span>
          </div>
        </div>
        <div className="preview-lanes">
          <div>
            <span>Yapılacak</span>
            <i></i><i></i><i></i>
          </div>
          <div>
            <span>Devam Eden</span>
            <i></i><i></i>
          </div>
          <div>
            <span>İncelemede</span>
            <i></i><i></i>
          </div>
        </div>
      </div>
    </div>
  );
}

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