import { Layout } from "./Layout"

type ConnectingPageProps = {
  ssid: string
}

export const ConnectingPage = ({ ssid }: ConnectingPageProps) => (
  <Layout title="Connecting...">
    <div id="connecting-state">
      <h1>⏳ Connecting to WiFi...</h1>
      <p>
        <strong>SSID:</strong> {ssid}
      </p>
      <p id="status">
        Testing connection... <span id="countdown">10</span>s remaining
      </p>
      <p>
        <small>Waiting to see if connection succeeds...</small>
      </p>
    </div>

    <div id="success-state" style="display: none;">
      <h1>✓ Connection Successful!</h1>
      <p>
        <strong>Connected to:</strong> {ssid}
      </p>
      <p>The Pi has switched to the new network.</p>
      <hr />
      <h3>Next Steps:</h3>
      <ol>
        <li>
          Switch your device to the <strong>{ssid}</strong> network
        </li>
        <li>
          Visit <a href="http://phone.local">http://phone.local</a>
        </li>
      </ol>
      <p>
        <small>The AP will shut down automatically since the Pi is now connected to WiFi.</small>
      </p>
    </div>

    <div id="error-state" style="display: none;">
      <h1>❌ Connection Failed</h1>
      <p>
        Could not connect to <strong>{ssid}</strong>
      </p>
      <p>The password may be incorrect, or the network is out of range.</p>
      <p>The AP is still running - you can try again.</p>
      <a href="/" role="button">
        ← Try Again
      </a>
    </div>

    <script>{`
      let countdown = 10;
      const countdownEl = document.getElementById('countdown');
      const connectingState = document.getElementById('connecting-state');
      const successState = document.getElementById('success-state');
      const errorState = document.getElementById('error-state');

      const interval = setInterval(async () => {
        try {
          await fetch('/ping');
          // Still connected - decrement countdown
          countdown--;
          if (countdownEl) countdownEl.textContent = countdown;

          if (countdown <= 0) {
            // 10 seconds passed and still connected = connection failed
            clearInterval(interval);
            connectingState.style.display = 'none';
            errorState.style.display = 'block';
          }
        } catch (e) {
          // Connection died = network switch happened = success!
          clearInterval(interval);
          connectingState.style.display = 'none';
          successState.style.display = 'block';
        }
      }, 1000);
    `}</script>
  </Layout>
)
