// Ayarlar Sayfası
function SettingsPage({ settings, onUpdate }) {
  const { useState, useEffect, useMemo } = React;
  const [diplomaNotu, setDiplomaNotu] = useState(settings?.diploma_notu || 0);
  const [hedefPuan, setHedefPuan] = useState(settings?.hedef_puan || 0);
  const [hedefSiralama, setHedefSiralama] = useState(settings?.hedef_siralama || 0);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (settings) {
      setDiplomaNotu(settings.diploma_notu || 0);
      setHedefPuan(settings.hedef_puan || 0);
      setHedefSiralama(settings.hedef_siralama || 0);
    }
  }, [settings]);

  const obp = useMemo(() => {
    const calc = obpFromDiploma(diplomaNotu);
    return calc;
  }, [diplomaNotu]);

  const handleSave = async () => {
    setSaving(true);
    setMessage('');

    const result = await apiCall('/settings.php', {
      method: 'POST',
      body: JSON.stringify({
        diploma_notu: diplomaNotu,
        hedef_puan: hedefPuan,
        hedef_siralama: hedefSiralama,
        alan: 'SAY'
      }),
    });

    if (result.success) {
      setMessage('✅ Ayarlar başarıyla kaydedildi!');
      onUpdate();
    } else {
      setMessage('❌ Hata: ' + result.message);
    }
    setSaving(false);
  };

  return (
    <div className="max-w-4xl mx-auto">
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h2 className="text-2xl font-bold mb-4 gradient-text">⚙️ Ayarlar</h2>

        <div className="space-y-6">
          {/* Diploma Notu */}
          <div className="border-b pb-6">
            <h3 className="text-xl font-semibold mb-4 text-gray-800">Diploma Bilgileri</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-base font-medium text-gray-700 mb-2">
                  Diploma Notunuz (0-100)
                </label>
                <input
                  type="number"
                  value={diplomaNotu}
                  onChange={(e) => setDiplomaNotu(Number(e.target.value))}
                  min="0"
                  max="100"
                  step="0.01"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-700 input-field"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gradient-to-r from-gray-200 to-gray-300 rounded-xl border border-gray-400 shadow-sm">
                <div className="text-center p-3 bg-white rounded-lg shadow-sm">
                  <div className="text-xs text-gray-600 font-medium">OBS Puanınız (500'lük)</div>
                  <div className="text-xl font-bold text-gray-800 mt-1">{round2(obp.obp)}</div>
                </div>
                <div className="text-center p-3 bg-white rounded-lg shadow-sm">
                  <div className="text-xs text-gray-600 font-medium">YKS'ye Katkısı</div>
                  <div className="text-xl font-bold text-green-800 mt-1">+{round2(obp.add)}</div>
                </div>
              </div>

              <div className="p-3 bg-gray-300 rounded-lg border border-gray-400">
                <div className="text-xs text-gray-700 font-medium">
                  💡 OBS Puanı = Diploma Notu × 5<br/>
                  💡 YKS Katkısı = OBS Puanı × 0.12 = Diploma Notu × 0.6
                </div>
              </div>
            </div>
          </div>

          {/* Hedefler */}
          <div className="border-b pb-6">
            <h3 className="text-xl font-semibold mb-4 text-gray-800">Hedefleriniz</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-base font-medium text-gray-700 mb-2">
                  Hedef AYT Puanı
                </label>
                <input
                  type="number"
                  value={hedefPuan}
                  onChange={(e) => setHedefPuan(Number(e.target.value))}
                  min="0"
                  max="600"
                  step="0.01"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-700 input-field"
                />
              </div>

              <div>
                <label className="block text-base font-medium text-gray-700 mb-2">
                  Hedef Sıralama
                </label>
                <input
                  type="number"
                  value={hedefSiralama}
                  onChange={(e) => setHedefSiralama(Number(e.target.value))}
                  min="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-700 input-field"
                />
              </div>
            </div>
          </div>

          {/* Kaydet Butonu */}
          <div>
            {message && (
              <div className={`p-3 rounded-lg mb-4 text-center font-semibold ${
                message.includes('✅') ? 'success-message border border-green-400' : 'error-message border border-red-400'
              }`}>
                {message}
              </div>
            )}

            <button
              onClick={handleSave}
              disabled={saving}
              className="w-full btn-primary py-3 rounded-lg font-bold text-lg disabled:opacity-50 shadow-lg hover:shadow-xl"
            >
              {saving ? 'Kaydediliyor...' : '💾 Ayarları Kaydet'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Denemeler Listesi Sayfası
function ExamsPage({ settings }) {
  const { useState, useEffect } = React;
  const [exams, setExams] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedExam, setSelectedExam] = useState(null);
  const [editingExam, setEditingExam] = useState(null);
  const [isSavingEdit, setIsSavingEdit] = useState(false);
  const [editError, setEditError] = useState('');

  useEffect(() => {
    loadExams();
  }, []);

  const loadExams = async () => {
    setLoading(true);
    try {
      const result = await apiCall('/exam.php');
      if (result.success && result.data && Array.isArray(result.data.exams)) {
        const fixedExams = result.data.exams.map((exam, index) => {
          const realId = Number(exam.id);
          const hasRealId = Number.isInteger(realId) && realId > 0;
          const fallbackId = `tmp-${exam.olusturma_tarihi || exam.deneme_tarihi || 'exam'}-${index}`;

          return {
            ...exam,
            id: hasRealId ? realId : fallbackId,
            realId: hasRealId ? realId : null,
          };
        });
        setExams(fixedExams);
      } else {
        setExams([]);
      }
    } catch (error) {
      console.error('Denemeler yüklenirken hata:', error);
      setExams([]);
    } finally {
      setLoading(false);
    }
  };

  const hasAytData = (exam) => {
    if (!exam) return false;
    const aytFields = [
      'ayt_toplam_net',
      'ayt_puan',
      'ayt_mat_dogru',
      'ayt_mat_yanlis',
      'ayt_fizik_dogru',
      'ayt_fizik_yanlis',
      'ayt_kimya_dogru',
      'ayt_kimya_yanlis',
      'ayt_biyoloji_dogru',
      'ayt_biyoloji_yanlis'
    ];

    return aytFields.some(field => Number(exam[field]) > 0);
  };

  const startEdit = (exam) => {
    if (!exam) return;
    setEditingExam({
      id: exam.id,
      realId: exam.realId,
      deneme_adi: exam.deneme_adi,
      deneme_tarihi: exam.deneme_tarihi,
    });
    setEditError('');
  };

  const cancelEdit = () => {
    setEditingExam(null);
    setIsSavingEdit(false);
    setEditError('');
  };

  const saveEdit = async () => {
    if (!editingExam) return;
    const name = editingExam.deneme_adi?.trim();
    if (!name) {
      setEditError('Deneme adı boş olamaz');
      return;
    }

    const realId = editingExam.realId || editingExam.id;
    if (!realId) {
      setEditError('Bu denemenin ID bilgisi bulunamadı.');
      return;
    }

    setIsSavingEdit(true);
    setEditError('');

    const payload = {
      deneme_adi: name,
      deneme_tarihi: editingExam.deneme_tarihi,
    };

    const result = await apiCall(`/exam.php?id=${realId}`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });

    if (result.success) {
      setExams(prevExams => prevExams.map(exam => {
        if (exam.id === editingExam.id) {
          return {
            ...exam,
            deneme_adi: name,
            deneme_tarihi: editingExam.deneme_tarihi,
          };
        }
        return exam;
      }));
      cancelEdit();
    } else {
      setEditError(result.message || 'Güncelleme başarısız oldu');
      setIsSavingEdit(false);
    }
  };

  const handleDelete = async (examKey) => {
    if (!confirm('Bu denemeyi silmek istediğinizden emin misiniz?')) return;

    const examToDelete = exams.find(exam => exam.id === examKey);
    if (!examToDelete) return;

    const params = new URLSearchParams();
    if (examToDelete.realId) {
      params.append('id', examToDelete.realId);
    } else if (examToDelete.olusturma_tarihi) {
      params.append('created_at', examToDelete.olusturma_tarihi);
    } else {
      alert('Bu deneme için benzersiz bir kimlik bulunamadı.');
      return;
    }

    const result = await apiCall(`/exam.php?${params.toString()}`, { method: 'DELETE' });
    if (result.success) {
      setExams(prevExams => prevExams.filter(exam => exam.id !== examKey));
    } else {
      alert('Silme işlemi başarısız: ' + (result.message || 'Bilinmeyen hata'));
    }
  };

  if (loading) {
    return <div className="text-center py-8 text-lg">Yükleniyor...</div>;
  }

  return (
    <div className="space-y-6">
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3">
          <div>
            <h2 className="text-2xl font-bold gradient-text">📝 Denemelerim</h2>
            <p className="text-gray-600 mt-1 text-sm">Tüm deneme sonuçlarınızı burada görüntüleyebilirsiniz</p>
          </div>
          <div className="bg-gradient-to-r from-gray-700 to-gray-800 text-white px-4 py-2 rounded-lg font-bold shadow-lg text-sm">
            Toplam: <span className="text-base">{exams ? exams.length : 0}</span> deneme
          </div>
        </div>
      </div>

      {!exams || exams.length === 0 ? (
        <div className="glass-effect rounded-2xl p-8 text-center shadow-lg">
          <div className="text-4xl mb-3">📚</div>
          <h3 className="text-xl font-bold mb-1">Henüz deneme yok</h3>
          <p className="text-gray-600 mb-4 text-sm">İlk denemenizi ekleyerek başlayın!</p>
          <a href="#/new-exam" className="btn-primary px-6 py-3 rounded-lg font-bold text-base shadow-lg hover:shadow-xl inline-block">
            ➕ Yeni Deneme Ekle
          </a>
        </div>
      ) : (
        <div className="grid gap-4">
          {exams.map((exam, index) => {
            const aytExists = hasAytData(exam);
            return (
              <div key={exam.id ?? index} className="glass-effect rounded-xl p-5 hover:shadow-xl transition-all duration-300 exam-card">
                <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-4">
                  <div className="flex-1">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:gap-4 mb-3">
                      <h3 className="text-lg font-bold text-gray-800">
                        {exam.deneme_adi}
                        {!aytExists && (
                          <span className="ml-2 text-xs font-semibold text-blue-600 bg-blue-100 px-2 py-1 rounded-full">TYT DENEMESİ</span>
                        )}
                      </h3>
                      <span className="text-sm text-gray-500 bg-gray-200 px-2 py-1 rounded-full mt-1 sm:mt-0">
                        {exam.deneme_tarihi}
                      </span>
                    </div>

                    <div className="grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4">
                      <div className="bg-gradient-to-br from-blue-200 to-blue-300 rounded-lg p-3 text-center border border-blue-400">
                        <div className="text-xs text-gray-600 font-medium">TYT Net</div>
                        <div className="font-bold text-blue-800 text-sm">{round2(exam.tyt_toplam_net)}</div>
                      </div>
                      {aytExists && (
                        <div className="bg-gradient-to-br from-green-200 to-green-300 rounded-lg p-3 text-center border border-green-400">
                          <div className="text-xs text-gray-600 font-medium">AYT Net</div>
                          <div className="font-bold text-green-800 text-sm">{round2(exam.ayt_toplam_net)}</div>
                        </div>
                      )}
                      <div className="bg-gradient-to-br from-purple-200 to-purple-300 rounded-lg p-3 text-center border border-purple-400">
                        <div className="text-xs text-gray-600 font-medium">TYT Puan</div>
                        <div className="font-bold text-purple-800 text-sm">{round2(exam.tyt_puan)}</div>
                      </div>
                      {aytExists && (
                        <div className="bg-gradient-to-br from-pink-200 to-pink-300 rounded-lg p-3 text-center border border-pink-400">
                          <div className="text-xs text-gray-600 font-medium">AYT Puan</div>
                          <div className="font-bold text-pink-800 text-sm">{round2(exam.ayt_puan)}</div>
                        </div>
                      )}
                      <div className="bg-gradient-to-br from-orange-200 to-amber-300 rounded-lg p-3 text-center border-2 border-orange-500">
                        <div className="text-xs text-gray-600 font-medium">🎯 Tahmini Sıralama ({aytExists ? 'AYT' : 'TYT'})</div>
                        <div className="font-bold text-orange-800 text-sm">{Number(exam.tahmini_siralama || 0).toLocaleString()}</div>
                      </div>
                    </div>

                    {/* Detaylı Netler */}
                    <details className="mt-4">
                      <summary className="cursor-pointer text-sm text-gray-800 font-semibold hover:text-gray-900 transition">
                        📊 Detaylı Netleri Göster
                      </summary>
                      <div className="mt-3 grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
                        <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                          <div className="text-xs text-gray-500 font-medium">Türkçe</div>
                          <div className="font-bold text-gray-800">{round2(exam.tyt_turkce_net)} net</div>
                          <div className="text-xs text-gray-400">{exam.tyt_turkce_dogru}D {exam.tyt_turkce_yanlis}Y</div>
                        </div>
                        <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                          <div className="text-xs text-gray-500 font-medium">Sosyal</div>
                          <div className="font-bold text-gray-800">{round2(exam.tyt_sosyal_net)} net</div>
                          <div className="text-xs text-gray-400">{exam.tyt_sosyal_dogru}D {exam.tyt_sosyal_yanlis}Y</div>
                        </div>
                        <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                          <div className="text-xs text-gray-500 font-medium">TYT Mat</div>
                          <div className="font-bold text-gray-800">{round2(exam.tyt_mat_net)} net</div>
                          <div className="text-xs text-gray-400">{exam.tyt_mat_dogru}D {exam.tyt_mat_yanlis}Y</div>
                        </div>
                        <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                          <div className="text-xs text-gray-500 font-medium">Fen</div>
                          <div className="font-bold text-gray-800">{round2(exam.tyt_fen_net)} net</div>
                          <div className="text-xs text-gray-400">{exam.tyt_fen_dogru}D {exam.tyt_fen_yanlis}Y</div>
                        </div>
                        {aytExists && (
                          <>
                            <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                              <div className="text-xs text-gray-500 font-medium">AYT Mat</div>
                              <div className="font-bold text-gray-800">{round2(exam.ayt_mat_net)} net</div>
                              <div className="text-xs text-gray-400">{exam.ayt_mat_dogru}D {exam.ayt_mat_yanlis}Y</div>
                            </div>
                            <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                              <div className="text-xs text-gray-500 font-medium">Fizik</div>
                              <div className="font-bold text-gray-800">{round2(exam.ayt_fizik_net)} net</div>
                              <div className="text-xs text-gray-400">{exam.ayt_fizik_dogru}D {exam.ayt_fizik_yanlis}Y</div>
                            </div>
                            <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                              <div className="text-xs text-gray-500 font-medium">Kimya</div>
                              <div className="font-bold text-gray-800">{round2(exam.ayt_kimya_net)} net</div>
                              <div className="text-xs text-gray-400">{exam.ayt_kimya_dogru}D {exam.ayt_kimya_yanlis}Y</div>
                            </div>
                            <div className="p-2 bg-gradient-to-br from-gray-200 to-gray-300 rounded-md border border-gray-400">
                              <div className="text-xs text-gray-500 font-medium">Biyoloji</div>
                              <div className="font-bold text-gray-800">{round2(exam.ayt_biyoloji_net)} net</div>
                              <div className="text-xs text-gray-400">{exam.ayt_biyoloji_dogru}D {exam.ayt_biyoloji_yanlis}Y</div>
                            </div>
                          </>
                        )}
                      </div>
                    </details>
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={() => startEdit(exam)}
                      className="px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all duration-300 font-semibold shadow-md hover:shadow-lg flex items-center gap-1 text-sm"
                    >
                      ✏️ Düzenle
                    </button>
                    <button
                      onClick={() => handleDelete(exam.id)}
                      className="px-4 py-2 bg-gradient-to-r from-red-700 to-red-800 text-white rounded-lg hover:from-red-800 hover:to-red-900 transition-all duration-300 font-semibold shadow-md hover:shadow-lg flex items-center gap-1 text-sm"
                    >
                      🗑️ Sil
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {editingExam && (
        <div className="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 space-y-4">
            <h3 className="text-xl font-bold text-gray-800">Deneme Adını Düzenle</h3>

            <div className="space-y-3">
              <label className="block text-sm font-medium text-gray-700">Deneme Adı</label>
              <input
                type="text"
                value={editingExam.deneme_adi}
                onChange={(e) => setEditingExam(prev => ({ ...prev, deneme_adi: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                placeholder="Yeni deneme adını girin"
              />
            </div>

            <div className="space-y-3">
              <label className="block text-sm font-medium text-gray-700">Deneme Tarihi</label>
              <input
                type="date"
                value={editingExam.deneme_tarihi}
                onChange={(e) => setEditingExam(prev => ({ ...prev, deneme_tarihi: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {editError && (
              <div className="text-sm text-red-600 bg-red-50 border border-red-200 px-3 py-2 rounded-lg">
                {editError}
              </div>
            )}

            <div className="flex justify-end gap-3 pt-2">
              <button
                onClick={cancelEdit}
                className="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 transition text-sm font-semibold"
                disabled={isSavingEdit}
              >
                Vazgeç
              </button>
              <button
                onClick={saveEdit}
                className="px-5 py-2 rounded-lg bg-gradient-to-r from-green-600 to-green-700 text-white font-semibold shadow-lg hover:from-green-700 hover:to-green-800 transition text-sm"
                disabled={isSavingEdit}
              >
                {isSavingEdit ? 'Kaydediliyor...' : 'Kaydet'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
// New Exam Page içeriği pages2.jsx'te devam edecek