import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Layout from "../components/Layout";

async function getAuthState() {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return null;
  
  try {
    const res = await fetch(`${baseUrl}/api/auth/me`, {
      headers: {
        Cookie: `${sessionCookie.name}=${sessionCookie.value}`
      },
      cache: "no-store"
    });
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

async function getChats() {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return [];
  
  try {
    const res = await fetch(`${baseUrl}/api/chats`, {
      headers: {
        Cookie: `${sessionCookie.name}=${sessionCookie.value}`
      },
      cache: "no-store"
    });
    if (!res.ok) return [];
    return await res.json();
  } catch {
    return [];
  }
}

export default async function Home() {
  const auth = await getAuthState();
  if (!auth) {
    redirect("/login");
  }
  
  const chats = await getChats();

  return (
    <Layout chats={chats} user={auth}>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', color: 'var(--text-muted)' }}>
        <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.3, marginBottom: 16 }}>
          <path d="M12 2C6.477 2 2 6.477 2 12C2 17.523 6.477 22 12 22C17.523 22 22 17.523 22 12C22 6.477 17.523 2 12 2ZM12 4C16.418 4 20 7.582 20 12C20 16.418 16.418 20 12 20C7.582 20 4 16.418 4 12C4 7.582 7.582 4 12 4Z" fill="currentColor"/>
          <path d="M15 13H9C8.448 13 8 12.552 8 12C8 11.448 8.448 11 9 11H15C15.552 11 16 11.448 16 12C16 12.552 15.552 13 15 13Z" fill="currentColor"/>
        </svg>
        <div style={{ fontSize: 18, fontWeight: 500, color: 'var(--text-main)', marginBottom: 8 }}>Чем я могу помочь?</div>
        <div style={{ fontSize: 14 }}>Выберите чат в меню слева или создайте новый.</div>
      </div>
    </Layout>
  );
}
