const { useState } = React;

const StudentQRCode = () => {
  const [enrollmentNo, setEnrollmentNo] = useState('');
  const [showQR, setShowQR] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (enrollmentNo.trim() !== '') {
      setShowQR(true);
    }
  };

  if (showQR) {
    // Generate QR code using qrserver API with lowest error correction (L) for minimum density
    const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=350x350&ecc=L&margin=2&data=${encodeURIComponent(enrollmentNo)}`;

    return (
      <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center p-4">
        <div className="bg-white p-8 rounded-3xl shadow-2xl flex flex-col items-center w-full max-w-sm border-4 border-blue-500">
          <h2 className="text-xl font-bold text-gray-800 mb-6 text-center">Your Attendance QR</h2>
          
          <div className="bg-white p-2 border-2 border-dashed border-gray-300 rounded-2xl mb-6 flex items-center justify-center">
             <img src={qrUrl} alt="QR Code" width="350" height="350" className="max-w-full" />
          </div>

          <p className="text-3xl font-mono font-bold tracking-widest text-gray-800 bg-gray-100 px-4 py-2 rounded-lg">
            {enrollmentNo}
          </p>

          <p className="text-sm text-gray-500 mt-6 text-center">
            Keep your screen brightness high and hold this towards the teacher.
          </p>
          
          <button 
             onClick={() => setShowQR(false)}
             className="mt-8 text-blue-600 font-semibold hover:underline"
          >
             Back
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4">
      <div className="bg-white p-8 rounded-2xl shadow-xl w-full max-w-sm">
        <h2 className="text-2xl font-bold text-gray-800 mb-2 text-center">Student Portal</h2>
        <p className="text-gray-500 mb-8 text-center text-sm">Generate your attendance QR code</p>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Enrollment Number
            </label>
            <input
              type="text"
              value={enrollmentNo}
              onChange={(e) => setEnrollmentNo(e.target.value.toUpperCase())}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 font-mono text-center text-xl outline-none uppercase"
              placeholder="E.g., 2001234"
              required
            />
          </div>

          <button
            type="submit"
            className="w-full bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 transition"
          >
            Show QR Code
          </button>
        </form>
      </div>
    </div>
  );
};

window.StudentQRCode = StudentQRCode;
