import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";

export const Route = createFileRoute("/")({
  component: Home,
});

// Public URL of the backend, injected at build time via Vite.
// Falls back to localhost for `vite dev`.
const API_URL = import.meta.env.VITE_API_URL ?? "http://localhost:3000";

type Hello = { message: string; timestamp: string };

function Home() {
  const [data, setData] = useState<Hello | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(`${API_URL}/api/hello`)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json() as Promise<Hello>;
      })
      .then(setData)
      .catch((e) => setError(String(e)));
  }, []);

  return (
    <main style={{ fontFamily: "system-ui, sans-serif", padding: "2rem", maxWidth: 640, margin: "0 auto" }}>
      <h1>test-app-stack</h1>
      <p>TanStack Start frontend talking to an ElysiaJS (Bun) backend.</p>

      <section style={{ marginTop: "1.5rem", padding: "1rem", border: "1px solid #ddd", borderRadius: 8 }}>
        <h2 style={{ marginTop: 0 }}>Backend connection</h2>
        <p><strong>API URL:</strong> <code>{API_URL}</code></p>
        {error && <p style={{ color: "crimson" }}>❌ {error}</p>}
        {!error && !data && <p>Connecting…</p>}
        {data && (
          <>
            <p>✅ <strong>{data.message}</strong></p>
            <p style={{ color: "#666", fontSize: "0.85rem" }}>at {data.timestamp}</p>
          </>
        )}
      </section>
    </main>
  );
}
