import { Layout } from "./Layout";

type LogsPageProps = {
  logs: string;
};

export const LogsPage = ({ logs }: LogsPageProps) => (
  <Layout title="Service Logs">
    <h1>📋 Service Logs</h1>
    <p>
      <small>
        <label>
          <input type="checkbox" id="auto-refresh" checked /> Auto-refresh
        </label>
        {" | "}
        <a href="/">← Back</a>
      </small>
    </p>
    <pre>
      <code id="logs-content">{logs.trim()}</code>
    </pre>

    <script>{`
      let interval = null;
      const checkbox = document.getElementById('auto-refresh');
      const logsContent = document.getElementById('logs-content');

      async function refreshLogs() {
        try {
          const res = await fetch('/api/logs');
          const data = await res.json();
          logsContent.textContent = data.logs;
        } catch (error) {
          console.error('Failed to refresh logs:', error);
        }
      }

      function startRefresh() {
        if (interval) clearInterval(interval);
        interval = setInterval(refreshLogs, 5000);
      }

      function stopRefresh() {
        if (interval) {
          clearInterval(interval);
          interval = null;
        }
      }

      checkbox.addEventListener('change', (e) => {
        if (e.target.checked) {
          startRefresh();
        } else {
          stopRefresh();
        }
      });

      // Start auto-refresh by default
      startRefresh();
    `}</script>
  </Layout>
);
