import { Hono } from 'hono';
import { serve } from 'bun';
import { serveStatic } from 'hono/bun';

const app = new Hono();

app.get("/table", (c) => {
  return c.html(`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Power Apps Table</title>
  <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/11.1.0/css/fabric.min.css" />
  <style>
    body, html, #root { margin:0; padding:0; height:100%; font-family:'Segoe UI',sans-serif; }
    #root { padding:2rem; overflow:auto; }
  </style>
</head>
<body>
  <div id="root"></div>

  <!-- LOAD REACT GLOBALLY -->
  <script type="module">
    // Load React from CDN into window
    window.React = (await import("https://esm.sh/react@18")).default;
    window.ReactDOM = (await import("https://esm.sh/react-dom@18")).default;

    console.log("React loaded:", window.React);

    // Now load your component
    import("./table.js").then(module => {
      const TablePage = module.default;
      console.log("TablePage:", TablePage);
      ReactDOM.createRoot(document.getElementById("root"))
        .render(React.createElement(TablePage));
    }).catch(err => {
      console.error("Failed to load table.js:", err);
    });
  </script>
</body>
</html>
  `);
});




// === CONFIG: Load from environment variables ===
const API_URL = process.env.API_URL!;
const API_KEY = process.env.API_KEY!;
const port = Number(process.env.PORT || 3000);

// Serve static assets from /public
//app.use('*', serveStatic({ root: './public' }));


// Default route serves index.html (handled by static middleware); fallback text if not found
// {made this text to text react table} app.get('/', (c) => c.redirect('/index.html'));

//serve({
 // port,
 // fetch: app.fetch,
//});

//console.log(`Server running on http://localhost:${port}`);

// 2. SERVE ONLY STATIC FILES (NOT ROUTES)
app.use("/table.js", serveStatic({ path: "./public/table.js" }));  // serve JS
app.use("/favicon.ico", serveStatic({ path: "./public/favicon.ico" })); // optional

// 3. FALLBACK: serve index.html for home (optional)
app.get("/", (c) => {
  return c.html(`
<!DOCTYPE html>
<html><head><title>Home</title></head>
<body style="font-family:Segoe UI;text-align:center;padding:4rem;">
  <h1>Power Apps Table</h1>
  <p><a href="/table">Open Table</a></p>
</body></html>
  `);
});

export default {
  port: 3000,
  fetch: app.fetch,
};