<!DOCTYPE html>
<html>
<head>
    <title>Firebase Phone Auth</title>
</head>
<body>

<h2>Phone Authentication</h2>

<input type="text" id="phoneNumber" placeholder="+911234567890">
<div id="recaptcha-container"></div>
<button id="sendOtpBtn">Send OTP</button>

<br><br>

<input type="text" id="otp" placeholder="Enter OTP">
<button id="verifyOtpBtn">Verify OTP</button>

<p id="message"></p>

<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/12.11.0/firebase-app.js";
import { 
    getAuth, 
    RecaptchaVerifier, 
    signInWithPhoneNumber 
} from "https://www.gstatic.com/firebasejs/12.11.0/firebase-auth.js";

// 🔧 Firebase config
const firebaseConfig = {
    apiKey: "AIzaSyDzFDrIDPTxEdVbrkTMik8G8k5d3-3xNow",
    authDomain: "cusella-ebbad.firebaseapp.com",
    projectId: "cusella-ebbad",
    storageBucket: "cusella-ebbad.firebasestorage.app",
    messagingSenderId: "749098079888",
    appId: "1:749098079888:web:ce59d2b5c590ccb2ae2a15"
};

// 🚀 Init
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// ✅ FIX: Render reCAPTCHA properly
let recaptchaVerifier;

window.onload = () => {
    recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {
        size: 'normal',
        callback: () => {
            console.log("reCAPTCHA solved");
        }
    });

    recaptchaVerifier.render(); // IMPORTANT
};

// 📤 Send OTP
document.getElementById("sendOtpBtn").addEventListener("click", async () => {
    const phoneNumber = document.getElementById("phoneNumber").value;

    try {
        const confirmationResult = await signInWithPhoneNumber(
            auth,
            phoneNumber,
            recaptchaVerifier
        );

        window.confirmationResult = confirmationResult;
        document.getElementById("message").innerText = "OTP sent!";
    } catch (error) {
        console.error(error);
        document.getElementById("message").innerText = error.message;
    }
});

// ✅ Verify OTP
document.getElementById("verifyOtpBtn").addEventListener("click", async () => {
    const code = document.getElementById("otp").value;

    try {
        const result = await window.confirmationResult.confirm(code);
        document.getElementById("message").innerText = "Phone verified!";
        console.log(result.user);
    } catch (error) {
        console.error(error);
        document.getElementById("message").innerText = "Invalid OTP";
    }
});
</script>

</body>
</html>