// Yeni Deneme Ekleme Sayfası
function NewExamPage({ settings, onSave }) {
  const { useState, useMemo } = React;
  const [denemeAdi, setDenemeAdi] = useState('');
  const [denemeTarihi, setDenemeTarihi] = useState(new Date().toISOString().split('T')[0]);

  const [tyt, setTyt] = useState({
    TURKCE: { correct: 0, wrong: 0 },
    SOSYAL: { correct: 0, wrong: 0 }, // Aggregated Social Sciences
    MAT: { correct: 0, wrong: 0 },
    FEN: { correct: 0, wrong: 0 }, // Aggregated Natural Sciences
    // Detailed Social Sciences subjects
    TARIH: { correct: 0, wrong: 0 },
    COGRAFYA: { correct: 0, wrong: 0 },
    FELSEFE: { correct: 0, wrong: 0 },
    DIN: { correct: 0, wrong: 0 },
    // Detailed Natural Sciences subjects
    FIZIK: { correct: 0, wrong: 0 },
    KIMYA: { correct: 0, wrong: 0 },
    BIYOLOJI: { correct: 0, wrong: 0 }
  });

  const [say, setSay] = useState({
    MAT2: { correct: 0, wrong: 0 },
    FIZ: { correct: 0, wrong: 0 },
    KIM: { correct: 0, wrong: 0 },
    BIO: { correct: 0, wrong: 0 },
  });

  // QUESTION_LIMITS objesi (utils.js dosyasından kopyalandı)
  const QUESTION_LIMITS = {
    TURKCE: 40, 
    SOSYAL: 20, 
    MAT: 40, 
    FEN: 20,
    MAT2: 40, 
    FIZ: 14, 
    KIM: 13, 
    BIO: 13,
    TARIH: 5,
    COGRAFYA: 5,
    FELSEFE: 5,
    DIN: 5,
    FIZIK: 7,
    KIMYA: 7,
    BIYOLOJI: 6
  };

  // Helper functions (utils.js dosyasından kopyalandı)
  function round2(n) {
    return Math.round(n * 100) / 100;
  }

  function safeNum(n) {
    const v = Number(n);
    return Number.isFinite(v) ? v : 0;
  }

  function net(correct, wrong) {
    return correct - wrong / 4;
  }

  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');

  // Kariyer.net modülünü kullanarak hesaplama
  const hesaplama = useMemo(() => {
    const tytNets = {
      TURKCE: KariyerNetYKS.net(tyt.TURKCE.correct, tyt.TURKCE.wrong),
      SOSYAL: KariyerNetYKS.net(tyt.SOSYAL.correct, tyt.SOSYAL.wrong),
      MAT: KariyerNetYKS.net(tyt.MAT.correct, tyt.MAT.wrong),
      FEN: KariyerNetYKS.net(tyt.FEN.correct, tyt.FEN.wrong)
    };
    
    const aytSayNets = {
      MAT2: KariyerNetYKS.net(say.MAT2.correct, say.MAT2.wrong),
      FIZ: KariyerNetYKS.net(say.FIZ.correct, say.FIZ.wrong),
      KIM: KariyerNetYKS.net(say.KIM.correct, say.KIM.wrong),
      BIO: KariyerNetYKS.net(say.BIO.correct, say.BIO.wrong)
    };
    
    const diploma = settings?.diploma_notu || 0;
    
    return KariyerNetYKS.calculate({ tytNets, aytSayNets, diploma });
  }, [tyt, say, settings]);

  const diplomaKatkisi = hesaplama.obpKatkisi;
  const tytHamPuan = hesaplama.tyt.hamPuan;
  const tytPuan = hesaplama.tyt.yerlestirmePuani;
  const aytHamPuan = hesaplama.say.hamPuan;
  const aytPuan = hesaplama.say.yerlestirmePuani;
  
  // Net hesaplamaları
  const tytToplamNet = useMemo(() => {
    return KariyerNetYKS.round2(
      KariyerNetYKS.net(tyt.TURKCE.correct, tyt.TURKCE.wrong) +
      KariyerNetYKS.net(tyt.SOSYAL.correct, tyt.SOSYAL.wrong) +
      KariyerNetYKS.net(tyt.MAT.correct, tyt.MAT.wrong) +
      KariyerNetYKS.net(tyt.FEN.correct, tyt.FEN.wrong)
    );
  }, [tyt]);
  
  const aytToplamNet = useMemo(() => {
    return KariyerNetYKS.round2(
      KariyerNetYKS.net(say.MAT2.correct, say.MAT2.wrong) +
      KariyerNetYKS.net(say.FIZ.correct, say.FIZ.wrong) +
      KariyerNetYKS.net(say.KIM.correct, say.KIM.wrong) +
      KariyerNetYKS.net(say.BIO.correct, say.BIO.wrong)
    );
  }, [say]);
  
  // Detailed TYT subject nets
  const tytDetailedNets = useMemo(() => {
    return {
      TARIH: KariyerNetYKS.net(tyt.TARIH.correct, tyt.TARIH.wrong),
      COGRAFYA: KariyerNetYKS.net(tyt.COGRAFYA.correct, tyt.COGRAFYA.wrong),
      FELSEFE: KariyerNetYKS.net(tyt.FELSEFE.correct, tyt.FELSEFE.wrong),
      DIN: KariyerNetYKS.net(tyt.DIN.correct, tyt.DIN.wrong),
      FIZIK: KariyerNetYKS.net(tyt.FIZIK.correct, tyt.FIZIK.wrong),
      KIMYA: KariyerNetYKS.net(tyt.KIMYA.correct, tyt.KIMYA.wrong),
      BIYOLOJI: KariyerNetYKS.net(tyt.BIYOLOJI.correct, tyt.BIYOLOJI.wrong)
    };
  }, [tyt]);
  
  // Calculate aggregated social sciences net
  const tytSosyalNet = useMemo(() => {
    // If user entered values for aggregated section, use those
    if (tyt.SOSYAL.correct > 0 || tyt.SOSYAL.wrong > 0) {
      return KariyerNetYKS.net(tyt.SOSYAL.correct, tyt.SOSYAL.wrong);
    }
    // Otherwise calculate from individual subjects
    return KariyerNetYKS.round2(
      tytDetailedNets.TARIH + tytDetailedNets.COGRAFYA + 
      tytDetailedNets.FELSEFE + tytDetailedNets.DIN
    );
  }, [tyt, tytDetailedNets]);
  
  // Calculate aggregated natural sciences net
  const tytFenNet = useMemo(() => {
    // If user entered values for aggregated section, use those
    if (tyt.FEN.correct > 0 || tyt.FEN.wrong > 0) {
      return KariyerNetYKS.net(tyt.FEN.correct, tyt.FEN.wrong);
    }
    // Otherwise calculate from individual subjects
    return KariyerNetYKS.round2(
      tytDetailedNets.FIZIK + tytDetailedNets.KIMYA + tytDetailedNets.BIYOLOJI
    );
  }, [tyt, tytDetailedNets]);
  
  // Sıralama bilgileri
  const tytHamSiralama = hesaplama.tyt.hamSiralama;
  const tytYerlestirmeSiralama = hesaplama.tyt.yerlestirmeSiralama;
  const aytHamSiralama = hesaplama.say.hamSiralama;
  const aytYerlestirmeSiralama = hesaplama.say.yerlestirmeSiralama;

  const handleTyt = (name, field, val) => {
    setTyt((s) => {
      const newState = { ...s, [name]: { ...s[name], [field]: val } };
      
      // Update SOSYAL when individual subjects are updated
      if (['TARIH', 'COGRAFYA', 'FELSEFE', 'DIN'].includes(name) && (field === 'correct' || field === 'wrong')) {
        // If any individual subject is being updated, update SOSYAL with sum of individual subjects
        const tarihCorrect = name === 'TARIH' && field === 'correct' ? val : s.TARIH.correct;
        const tarihWrong = name === 'TARIH' && field === 'wrong' ? val : s.TARIH.wrong;
        const cografyaCorrect = name === 'COGRAFYA' && field === 'correct' ? val : s.COGRAFYA.correct;
        const cografyaWrong = name === 'COGRAFYA' && field === 'wrong' ? val : s.COGRAFYA.wrong;
        const felsefeCorrect = name === 'FELSEFE' && field === 'correct' ? val : s.FELSEFE.correct;
        const felsefeWrong = name === 'FELSEFE' && field === 'wrong' ? val : s.FELSEFE.wrong;
        const dinCorrect = name === 'DIN' && field === 'correct' ? val : s.DIN.correct;
        const dinWrong = name === 'DIN' && field === 'wrong' ? val : s.DIN.wrong;
        
        newState.SOSYAL = { 
          correct: tarihCorrect + cografyaCorrect + felsefeCorrect + dinCorrect,
          wrong: tarihWrong + cografyaWrong + felsefeWrong + dinWrong
        };
      }
      
      // Update FEN when individual subjects are updated
      if (['FIZIK', 'KIMYA', 'BIYOLOJI'].includes(name) && (field === 'correct' || field === 'wrong')) {
        // If any individual subject is being updated, update FEN with sum of individual subjects
        const fizikCorrect = name === 'FIZIK' && field === 'correct' ? val : s.FIZIK.correct;
        const fizikWrong = name === 'FIZIK' && field === 'wrong' ? val : s.FIZIK.wrong;
        const kimyaCorrect = name === 'KIMYA' && field === 'correct' ? val : s.KIMYA.correct;
        const kimyaWrong = name === 'KIMYA' && field === 'wrong' ? val : s.KIMYA.wrong;
        const biyolojiCorrect = name === 'BIYOLOJI' && field === 'correct' ? val : s.BIYOLOJI.correct;
        const biyolojiWrong = name === 'BIYOLOJI' && field === 'wrong' ? val : s.BIYOLOJI.wrong;
        
        newState.FEN = { 
          correct: fizikCorrect + kimyaCorrect + biyolojiCorrect,
          wrong: fizikWrong + kimyaWrong + biyolojiWrong
        };
      }
      
      // Clear individual subjects when SOSYAL is updated
      if (name === 'SOSYAL' && (field === 'correct' || field === 'wrong')) {
        // If SOSYAL is being updated, clear individual subjects if they had values
        if (val > 0 && (s.TARIH.correct > 0 || s.TARIH.wrong > 0 || 
                        s.COGRAFYA.correct > 0 || s.COGRAFYA.wrong > 0 ||
                        s.FELSEFE.correct > 0 || s.FELSEFE.wrong > 0 ||
                        s.DIN.correct > 0 || s.DIN.wrong > 0)) {
          newState.TARIH = { correct: 0, wrong: 0 };
          newState.COGRAFYA = { correct: 0, wrong: 0 };
          newState.FELSEFE = { correct: 0, wrong: 0 };
          newState.DIN = { correct: 0, wrong: 0 };
        }
      }
      
      // Clear individual subjects when FEN is updated
      if (name === 'FEN' && (field === 'correct' || field === 'wrong')) {
        // If FEN is being updated, clear individual subjects if they had values
        if (val > 0 && (s.FIZIK.correct > 0 || s.FIZIK.wrong > 0 || 
                        s.KIMYA.correct > 0 || s.KIMYA.wrong > 0 ||
                        s.BIYOLOJI.correct > 0 || s.BIYOLOJI.wrong > 0)) {
          newState.FIZIK = { correct: 0, wrong: 0 };
          newState.KIMYA = { correct: 0, wrong: 0 };
          newState.BIYOLOJI = { correct: 0, wrong: 0 };
        }
      }
      
      return newState;
    });
  };

  const handleSay = (name, field, val) => {
    setSay((s) => ({ ...s, [name]: { ...s[name], [field]: val } }));
  };

  const handleSave = async () => {
    if (!denemeAdi.trim()) {
      setMessage('❌ Lütfen deneme adı girin');
      return;
    }

    setSaving(true);
    setMessage('');

    const hasAytData = Object.values(say).some(section => Number(section.correct) > 0 || Number(section.wrong) > 0);

    const examData = {
      deneme_adi: denemeAdi.trim() || 'İsimsiz Deneme',
      deneme_tarihi: denemeTarihi,
      
      // Turkish
      tyt_turkce_dogru: tyt.TURKCE.correct,
      tyt_turkce_yanlis: tyt.TURKCE.wrong,
      
      // Social Sciences - Individual Subjects
      tyt_tarih_dogru: tyt.TARIH.correct,
      tyt_tarih_yanlis: tyt.TARIH.wrong,
      tyt_cografya_dogru: tyt.COGRAFYA.correct,
      tyt_cografya_yanlis: tyt.COGRAFYA.wrong,
      tyt_felsefe_dogru: tyt.FELSEFE.correct,
      tyt_felsefe_yanlis: tyt.FELSEFE.wrong,
      tyt_din_dogru: tyt.DIN.correct,
      tyt_din_yanlis: tyt.DIN.wrong,
      
      // Social Sciences - Aggregated
      tyt_sosyal_dogru: tyt.SOSYAL.correct > 0 || tyt.SOSYAL.wrong > 0 
        ? tyt.SOSYAL.correct 
        : tyt.TARIH.correct + tyt.COGRAFYA.correct + tyt.FELSEFE.correct + tyt.DIN.correct,
      tyt_sosyal_yanlis: tyt.SOSYAL.correct > 0 || tyt.SOSYAL.wrong > 0 
        ? tyt.SOSYAL.wrong 
        : tyt.TARIH.wrong + tyt.COGRAFYA.wrong + tyt.FELSEFE.wrong + tyt.DIN.wrong,
      
      // Mathematics
      tyt_mat_dogru: tyt.MAT.correct,
      tyt_mat_yanlis: tyt.MAT.wrong,
      
      // Natural Sciences - Individual Subjects
      tyt_fizik_dogru: tyt.FIZIK.correct,
      tyt_fizik_yanlis: tyt.FIZIK.wrong,
      tyt_kimya_dogru: tyt.KIMYA.correct,
      tyt_kimya_yanlis: tyt.KIMYA.wrong,
      tyt_biyoloji_dogru: tyt.BIYOLOJI.correct,
      tyt_biyoloji_yanlis: tyt.BIYOLOJI.wrong,
      
      // Natural Sciences - Aggregated
      tyt_fen_dogru: tyt.FEN.correct > 0 || tyt.FEN.wrong > 0 
        ? tyt.FEN.correct 
        : tyt.FIZIK.correct + tyt.KIMYA.correct + tyt.BIYOLOJI.correct,
      tyt_fen_yanlis: tyt.FEN.correct > 0 || tyt.FEN.wrong > 0 
        ? tyt.FEN.wrong 
        : tyt.FIZIK.wrong + tyt.KIMYA.wrong + tyt.BIYOLOJI.wrong,
      
      // AYT Subjects
      ayt_mat_dogru: say.MAT2.correct,
      ayt_mat_yanlis: say.MAT2.wrong,
      ayt_fizik_dogru: say.FIZ.correct,
      ayt_fizik_yanlis: say.FIZ.wrong,
      ayt_kimya_dogru: say.KIM.correct,
      ayt_kimya_yanlis: say.KIM.wrong,
      ayt_biyoloji_dogru: say.BIO.correct,
      ayt_biyoloji_yanlis: say.BIO.wrong,
      
      tyt_ham_puan: tytHamPuan,
      tyt_puan: tytPuan,
      ayt_ham_puan: hasAytData ? aytHamPuan : 0,
      ayt_puan: hasAytData ? aytPuan : 0,
      
      hesaplama_modu: hasAytData ? 'kariyernet_ayt' : 'kariyernet_tyt',
      tahmini_siralama: hasAytData ? aytYerlestirmeSiralama : tytYerlestirmeSiralama,
    };

    const result = await apiCall('/exam.php', {
      method: 'POST',
      body: JSON.stringify(examData),
    });

    if (result.success) {
      setMessage('✅ Deneme başarıyla kaydedildi!');
      setTimeout(() => {
        onSave();
      }, 1500);
    } else {
      setMessage('❌ Hata: ' + result.message);
    }
    setSaving(false);
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h2 className="text-2xl font-bold mb-4 gradient-text">✏️ Yeni Deneme Ekle</h2>

        {/* Genel Bilgiler */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
          <div>
            <label className="block text-base font-semibold text-gray-700 mb-2">
              Deneme Adı
            </label>
            <input
              type="text"
              value={denemeAdi}
              onChange={(e) => setDenemeAdi(e.target.value)}
              placeholder="örn: ÖZDEBİR"
              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-semibold text-gray-700 mb-2">
              Deneme Tarihi
            </label>
            <input
              type="date"
              value={denemeTarihi}
              onChange={(e) => setDenemeTarihi(e.target.value)}
              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>

      {/* TYT Netleri */}
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h3 className="text-xl font-bold mb-4 text-blue-800">📘 TYT Netleri</h3>
        
        {/* Main TYT Subjects */}
        <div className="space-y-3 mb-6">
          <SectionRow label="Türkçe" name="TURKCE" value={tyt.TURKCE} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
          <SectionRow label="Matematik" name="MAT" value={tyt.MAT} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
        </div>
        
        {/* Social Sciences Section */}
        <div className="border-t border-gray-300 pt-4 mb-6">
          <h4 className="text-lg font-semibold mb-3 text-amber-700">🌍 Sosyal Bilimler</h4>
          
          {/* Aggregated Social Sciences Input */}
          <div className="mb-4">
            <SectionRow 
              label="Sosyal Bilimler Toplam" 
              name="SOSYAL" 
              value={tyt.SOSYAL} 
              onChange={handleTyt} 
              questionLimits={QUESTION_LIMITS}
            />
          </div>
          
          {/* Detailed Social Sciences Subjects */}
          <div className="space-y-3 mb-4">
            <SectionRow label="Tarih" name="TARIH" value={tyt.TARIH} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
            <SectionRow label="Coğrafya" name="COGRAFYA" value={tyt.COGRAFYA} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
            <SectionRow label="Felsefe" name="FELSEFE" value={tyt.FELSEFE} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
            <SectionRow label="Din Kültürü" name="DIN" value={tyt.DIN} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
          </div>
          
          {/* Aggregated Social Sciences Display */}
          {/* 
          <div className="p-3 bg-gradient-to-r from-amber-100 to-amber-200 rounded-lg border border-amber-300">
            <div className="flex justify-between items-center">
              <span className="font-semibold text-amber-800">Sosyal Bilimler Toplam (Kullanılan)</span>
              <span className="font-bold text-amber-900">{tytSosyalNet} net</span>
            </div>
            <div className="text-xs text-amber-700 mt-1">
              {tyt.SOSYAL.correct > 0 || tyt.SOSYAL.wrong > 0 
                ? "Toplam değeri doğrudan girildi" 
                : "Detaylı derslerden hesaplandı"}
            </div>
          </div>
          */}
        </div>
        
        {/* Natural Sciences Section */}
        <div className="border-t border-gray-300 pt-4">
          <h4 className="text-lg font-semibold mb-3 text-emerald-700">🔬 Fen Bilimleri</h4>
          
          {/* Aggregated Natural Sciences Input */}
          <div className="mb-4">
            <SectionRow 
              label="Fen Bilimleri Toplam" 
              name="FEN" 
              value={tyt.FEN} 
              onChange={handleTyt} 
              questionLimits={QUESTION_LIMITS}
            />
          </div>
          
          {/* Detailed Natural Sciences Subjects */}
          <div className="space-y-3 mb-4">
            <SectionRow label="Fizik" name="FIZIK" value={tyt.FIZIK} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
            <SectionRow label="Kimya" name="KIMYA" value={tyt.KIMYA} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
            <SectionRow label="Biyoloji" name="BIYOLOJI" value={tyt.BIYOLOJI} onChange={handleTyt} questionLimits={QUESTION_LIMITS} />
          </div>
          
          {/* Aggregated Natural Sciences Display */}
          {/* 
          <div className="p-3 bg-gradient-to-r from-emerald-100 to-emerald-200 rounded-lg border border-emerald-300">
            <div className="flex justify-between items-center">
              <span className="font-semibold text-emerald-800">Fen Bilimleri Toplam (Kullanılan)</span>
              <span className="font-bold text-emerald-900">{tytFenNet} net</span>
            </div>
            <div className="text-xs text-emerald-700 mt-1">
              {tyt.FEN.correct > 0 || tyt.FEN.wrong > 0 
                ? "Toplam değeri doğrudan girildi" 
                : "Detaylı derslerden hesaplandı"}
            </div>
          </div>
          */}
        </div>
        <div className="mt-6 p-4 bg-gradient-to-r from-blue-200 to-gray-300 rounded-xl border-2 border-blue-400 shadow-sm">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="text-center p-3 bg-white rounded-lg shadow-sm">
              <div className="text-xs text-gray-600 font-medium">TYT Toplam Net</div>
              <div className="text-xl font-bold text-blue-800 mt-1">
                {tytToplamNet}
              </div>
            </div>
            <div className="text-center p-3 bg-white rounded-lg shadow-sm">
              <div className="text-xs text-gray-600 font-medium">TYT Ham Puan</div>
              <div className="text-lg font-bold text-gray-800 mt-1">{KariyerNetYKS.round3(tytHamPuan)}</div>
              <div className="text-xs text-gray-500 mt-1">Sıralama: {tytHamSiralama?.toLocaleString('tr-TR')}</div>
            </div>
            <div className="text-center p-3 bg-white rounded-lg shadow-sm">
              <div className="text-xs text-gray-600 font-medium">TYT Yerleştirme Puanı</div>
              <div className="text-lg font-bold text-gray-800 mt-1">{KariyerNetYKS.round3(tytPuan)}</div>
              <div className="text-xs text-gray-500 mt-1">(Ham + OBP)</div>
            </div>
            <div className="text-center p-3 bg-gradient-to-r from-orange-300 to-amber-300 rounded-lg shadow-sm border-2 border-orange-500">
              <div className="text-xs text-gray-600 font-medium">🎯 TYT Sıralaması</div>
              <div className="text-lg font-bold text-orange-800 mt-1">{tytYerlestirmeSiralama?.toLocaleString('tr-TR')}</div>
              <div className="text-xs text-gray-500 mt-1">(2024 verileri)</div>
            </div>
          </div>
        </div>
      </div>

      {/* AYT-SAY Netleri */}
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h3 className="text-xl font-bold mb-4 text-green-800">📗 AYT-SAY Netleri</h3>
        <div className="space-y-3">
          <SectionRow label="Matematik" name="MAT2" value={say.MAT2} onChange={handleSay} questionLimits={QUESTION_LIMITS} />
          <SectionRow label="Fizik" name="FIZ" value={say.FIZ} onChange={handleSay} questionLimits={QUESTION_LIMITS} />
          <SectionRow label="Kimya" name="KIM" value={say.KIM} onChange={handleSay} questionLimits={QUESTION_LIMITS} />
          <SectionRow label="Biyoloji" name="BIO" value={say.BIO} onChange={handleSay} questionLimits={QUESTION_LIMITS} />
        </div>

        <div className="mt-6 space-y-4">
          {/* Ana Sonuçlar */}
          <div className="p-4 bg-gradient-to-r from-green-200 to-gray-300 rounded-xl border-2 border-green-400 shadow-lg">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="text-center p-3 bg-white rounded-lg shadow-sm">
                <div className="text-xs text-gray-600 font-medium">AYT Toplam Net</div>
                <div className="text-xl font-bold text-green-800 mt-1">
                  {aytToplamNet}
                </div>
              </div>
              <div className="text-center p-3 bg-white rounded-lg shadow-sm">
                <div className="text-xs text-gray-600 font-medium">Ham Puan</div>
                <div className="text-lg font-bold text-blue-800 mt-1">{KariyerNetYKS.round3(aytHamPuan)}</div>
                <div className="text-xs text-gray-500 mt-1">Sıralama: {aytHamSiralama?.toLocaleString('tr-TR')}</div>
              </div>
              <div className="text-center p-3 bg-white rounded-lg shadow-sm">
                <div className="text-xs text-gray-600 font-medium">Yerleştirme Puanı</div>
                <div className="text-lg font-bold text-gray-800 mt-1">{KariyerNetYKS.round3(aytPuan)}</div>
                <div className="text-xs text-gray-500 mt-1">(Ham + OBP)</div>
              </div>
              <div className="text-center p-3 bg-gradient-to-r from-orange-300 to-amber-300 rounded-lg shadow-sm border-2 border-orange-500">
                <div className="text-xs text-gray-600 font-medium mb-1">🎯 Sıralama (SAY)</div>
                <div className="text-xl font-bold text-orange-800 mt-1">
                  {aytYerlestirmeSiralama?.toLocaleString('tr-TR')}
                </div>
                <div className="text-xs text-gray-500 mt-1">
                  2024 Gerçek Veriler
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Kaydet */}
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        {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...' : '💾 Denemeyi Kaydet'}
        </button>
      </div>
    </div>
  );
}

function SectionRow({ label, name, value, onChange, disabled = false, questionLimits }) {
  // Check if limit exists for this name
  const limit = questionLimits ? questionLimits[name] || 0 : 0;
  // Don't use safeNum for displaying in inputs to avoid showing "0" by default
  const c = value.correct || '';
  const w = value.wrong || '';
  // Only use safeNum for calculations
  const correctNum = safeNum(value.correct);
  const wrongNum = safeNum(value.wrong);
  // Calculate blank questions with safety check
  const b = limit > 0 ? Math.max(0, limit - correctNum - wrongNum) : 0;
  const n = round2(net(correctNum, wrongNum));
  // More robust overflow check
  const overflow = limit > 0 && (correctNum + wrongNum) > limit;

  return (
    <div className={`grid grid-cols-1 sm:grid-cols-6 gap-3 items-center p-3 rounded-xl transition-all duration-300 ${
      overflow ? 'bg-gradient-to-r from-red-200 to-red-300 border-2 border-red-500' : 'bg-gradient-to-r from-gray-200 to-gray-300'
    } ${disabled ? 'opacity-50' : ''}`}>
      <div className="sm:col-span-2 font-semibold text-gray-800">
        {label} 
        <span className="text-xs text-gray-500 ml-1">(max {limit})</span>
      </div>
      <div className="sm:col-span-1">
        <label className="text-xs text-gray-600 block mb-1 font-medium">Doğru</label>
        <input
          type="number"
          className="w-full border-2 rounded-lg px-2 py-1 focus:ring-2 focus:ring-gray-700 input-field"
          value={c}
          min={0}
          max={limit > 0 ? limit : undefined}
          placeholder="0"
          onChange={(e) => onChange(name, "correct", e.target.value === '' ? '' : Number(e.target.value))}
          disabled={disabled}
        />
      </div>
      <div className="sm:col-span-1">
        <label className="text-xs text-gray-600 block mb-1 font-medium">Yanlış</label>
        <input
          type="number"
          className="w-full border-2 rounded-lg px-2 py-1 focus:ring-2 focus:ring-gray-700 input-field"
          value={w}
          min={0}
          max={limit > 0 ? limit : undefined}
          placeholder="0"
          onChange={(e) => onChange(name, "wrong", e.target.value === '' ? '' : Number(e.target.value))}
          disabled={disabled}
        />
      </div>
      <div className="sm:col-span-1 text-center">
        <div className="text-xs text-gray-600 font-medium">Boş</div>
        <div className="font-semibold text-gray-700">{b}</div>
      </div>
      <div className="sm:col-span-1 text-center">
        <div className="text-xs text-gray-600 font-medium">Net</div>
        <div className="font-bold text-gray-800">{n}</div>
      </div>
    </div>
  );
}

// İstatistikler Sayfası
function StatisticsPage() {
  const { useState, useEffect, useRef } = React;
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const tytChartRef = useRef(null);
  const tytChartInstance = useRef(null);

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

  useEffect(() => {
    if (stats && stats.trend && stats.trend.length > 0) {
      renderChart();
    } else if (chartInstance.current) {
      chartInstance.current.destroy();
      chartInstance.current = null;
    }

    if (stats && stats.tyt_trend && stats.tyt_trend.length > 0) {
      renderTytChart();
    } else if (tytChartInstance.current) {
      tytChartInstance.current.destroy();
      tytChartInstance.current = null;
    }

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
        chartInstance.current = null;
      }
      if (tytChartInstance.current) {
        tytChartInstance.current.destroy();
        tytChartInstance.current = null;
      }
    };
  }, [stats]);

  const loadStatistics = async () => {
    setLoading(true);
    const result = await apiCall('/statistics.php');
    if (result.success) {
      setStats(result.data);
    }
    setLoading(false);
  };

  const renderChart = () => {
    if (!chartRef.current || !stats.trend || stats.trend.length === 0) return;

    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    const ctx = chartRef.current.getContext('2d');
    
    chartInstance.current = new Chart(ctx, {
      type: 'line',
      data: {
        labels: stats.trend.map(t => t.deneme_tarihi),
        datasets: [
          {
            label: 'TYT Puan',
            data: stats.trend.map(t => t.tyt_puan),
            borderColor: 'rgb(45, 55, 72)',
            backgroundColor: 'rgba(45, 55, 72, 0.1)',
            tension: 0.4,
            fill: true,
            pointRadius: 5,
            pointBackgroundColor: 'rgb(45, 55, 72)',
            pointBorderColor: '#fff',
            pointBorderWidth: 2
          },
          {
            label: 'AYT Puan',
            data: stats.trend.map(t => t.ayt_puan),
            borderColor: 'rgb(34, 197, 94)',
            backgroundColor: 'rgba(34, 197, 94, 0.1)',
            tension: 0.4,
            fill: true,
            pointRadius: 5,
            pointBackgroundColor: 'rgb(34, 197, 94)',
            pointBorderColor: '#fff',
            pointBorderWidth: 2
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: {
              font: {
                size: 12,
                family: "'Inter', sans-serif"
              }
            }
          },
          title: {
            display: true,
            text: 'Puan Gelişim',
            font: {
              size: 16,
              family: "'Inter', sans-serif",
              weight: 'bold'
            }
          },
        },
        scales: {
          y: {
            beginAtZero: false,
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            ticks: {
              font: {
                family: "'Inter', sans-serif"
              }
            }
          },
          x: {
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            ticks: {
              font: {
                family: "'Inter', sans-serif"
              }
            }
          }
        },
        interaction: {
          mode: 'index',
          intersect: false
        },
        plugins: {
          tooltip: {
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            titleColor: '#333',
            bodyColor: '#666',
            borderColor: 'rgba(0, 0, 0, 0.1)',
            borderWidth: 1,
            padding: 10,
            usePointStyle: true,
            callbacks: {
              label: function(context) {
                return `${context.dataset.label}: ${context.parsed.y.toFixed(2)}`;
              }
            }
          }
        }
      },
    });
  };

  const renderTytChart = () => {
    if (!tytChartRef.current || !stats.tyt_trend || stats.tyt_trend.length === 0) return;

    if (tytChartInstance.current) {
      tytChartInstance.current.destroy();
    }

    const ctx = tytChartRef.current.getContext('2d');

    tytChartInstance.current = new Chart(ctx, {
      type: 'line',
      data: {
        labels: stats.tyt_trend.map(t => t.deneme_tarihi),
        datasets: [
          {
            label: 'TYT Puan',
            data: stats.tyt_trend.map(t => t.tyt_puan),
            borderColor: 'rgb(37, 99, 235)',
            backgroundColor: 'rgba(37, 99, 235, 0.15)',
            tension: 0.4,
            fill: true,
            pointRadius: 5,
            pointBackgroundColor: 'rgb(37, 99, 235)',
            pointBorderColor: '#fff',
            pointBorderWidth: 2
          }
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: {
              font: {
                size: 12,
                family: "'Inter', sans-serif"
              }
            }
          },
          title: {
            display: true,
            text: 'TYT Puan Gelişimi',
            font: {
              size: 16,
              family: "'Inter', sans-serif",
              weight: 'bold'
            }
          },
          tooltip: {
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            titleColor: '#333',
            bodyColor: '#666',
            borderColor: 'rgba(0, 0, 0, 0.1)',
            borderWidth: 1,
            padding: 10,
            usePointStyle: true,
            callbacks: {
              label: function(context) {
                return `${context.dataset.label}: ${context.parsed.y.toFixed(2)}`;
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: false,
            grid: {
              color: 'rgba(59, 130, 246, 0.08)'
            },
            ticks: {
              font: {
                family: "'Inter', sans-serif"
              }
            }
          },
          x: {
            grid: {
              color: 'rgba(59, 130, 246, 0.08)'
            },
            ticks: {
              font: {
                family: "'Inter', sans-serif"
              }
            }
          }
        },
        interaction: {
          mode: 'index',
          intersect: false
        }
      },
    });
  };

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

  if (!stats || !stats.genel || stats.genel.toplam_deneme === 0) {
    return (
      <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 istatistik yok</h3>
        <p className="text-gray-600 mb-4 text-sm">Deneme ekleyerek istatistiklerinizi görüntüleyin!</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>
    );
  }

  return (
    <div className="space-y-6">
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h2 className="text-2xl font-bold mb-1 gradient-text">📈 İstatistikler ve İlerleme</h2>
        <p className="text-gray-600 text-sm">Deneme performansınızı detaylı şekilde inceleyin</p>
      </div>

      {/* Genel İstatistikler */}
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h3 className="text-xl font-bold mb-4 text-gray-800">🎯 Genel Performans</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard
            title="Toplam Deneme"
            value={stats.genel.toplam_deneme}
            icon="📝"
            color="from-indigo-700 to-indigo-800"
          />
          <StatCard
            title="Ort. TYT Net"
            value={round2(stats.genel.ortalama_tyt_net)}
            icon="📘"
            color="from-blue-700 to-blue-800"
          />
          <StatCard
            title="Ort. AYT Net"
            value={round2(stats.genel.ortalama_ayt_net)}
            icon="📗"
            color="from-green-700 to-green-800"
          />
          <StatCard
            title="En Yüksek AYT"
            value={round2(stats.genel.max_ayt_puan)}
            icon="🏆"
            color="from-yellow-700 to-yellow-800"
          />
        </div>
      </div>

      {/* İlerleme */}
      {stats.ilerleme && stats.ilerleme.ilk_deneme && (
        <div className="glass-effect rounded-2xl p-6 shadow-lg">
          <h3 className="text-xl font-bold mb-4 text-gray-800">📊 İlerlemeniz</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="p-4 bg-gradient-to-r from-gray-700 to-gray-800 rounded-xl text-white shadow-lg">
              <div className="text-sm font-medium opacity-90">TYT Net Artışı</div>
              <div className="text-2xl font-bold mt-2">
                {stats.ilerleme.tyt_net_artis > 0 ? '+' : ''}{round2(stats.ilerleme.tyt_net_artis)}
              </div>
              <div className="text-sm font-medium opacity-75 mt-2">
                {round2(stats.ilerleme.ilk_deneme.tyt_toplam_net)} → {round2(stats.ilerleme.son_deneme.tyt_toplam_net)}
              </div>
            </div>
            <div className="p-4 bg-gradient-to-r from-green-700 to-green-800 rounded-xl text-white shadow-lg">
              <div className="text-sm font-medium opacity-90">AYT Net Artışı</div>
              <div className="text-2xl font-bold mt-2">
                {stats.ilerleme.ayt_net_artis > 0 ? '+' : ''}{round2(stats.ilerleme.ayt_net_artis)}
              </div>
              <div className="text-sm font-medium opacity-75 mt-2">
                {round2(stats.ilerleme.ilk_deneme.ayt_toplam_net)} → {round2(stats.ilerleme.son_deneme.ayt_toplam_net)}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Ders Bazında Ortalamalar */}
      <div className="glass-effect rounded-2xl p-6 shadow-lg">
        <h3 className="text-xl font-bold mb-4 text-gray-800">📚 Ders Bazında Ortalamalar</h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-2">
          <DersNetCard label="Türkçe" avg={stats.ders_bazinda.ort_turkce} max={stats.ders_bazinda.max_turkce} color="from-blue-300 to-blue-400" textColor="text-blue-900" />
          <DersNetCard label="Sosyal" avg={stats.ders_bazinda.ort_sosyal} max={stats.ders_bazinda.max_sosyal} color="from-indigo-300 to-indigo-400" textColor="text-indigo-900" />
          <DersNetCard label="TYT Mat" avg={stats.ders_bazinda.ort_mat} max={stats.ders_bazinda.max_mat} color="from-purple-300 to-purple-400" textColor="text-purple-900" />
          <DersNetCard label="Fen" avg={stats.ders_bazinda.ort_fen} max={stats.ders_bazinda.max_fen} color="from-pink-300 to-pink-400" textColor="text-pink-900" />
          <DersNetCard label="AYT Mat" avg={stats.ders_bazinda.ort_ayt_mat} max={stats.ders_bazinda.max_ayt_mat} color="from-green-300 to-green-400" textColor="text-green-900" />
          <DersNetCard label="Fizik" avg={stats.ders_bazinda.ort_fizik} max={stats.ders_bazinda.max_fizik} color="from-teal-300 to-teal-400" textColor="text-teal-900" />
          <DersNetCard label="Kimya" avg={stats.ders_bazinda.ort_kimya} max={stats.ders_bazinda.max_kimya} color="from-amber-300 to-amber-400" textColor="text-amber-900" />
          <DersNetCard label="Biyoloji" avg={stats.ders_bazinda.ort_biyoloji} max={stats.ders_bazinda.max_biyoloji} color="from-emerald-300 to-emerald-400" textColor="text-emerald-900" />
        </div>
      </div>

      {/* Genel Puan Grafiği */}
      {stats.trend && stats.trend.length > 0 && (
        <div className="glass-effect rounded-2xl p-6 shadow-lg">
          <h3 className="text-xl font-bold mb-4 text-gray-800">📈 Genel Puan Gelişimi</h3>
          <div className="chart-container">
            <canvas ref={chartRef}></canvas>
          </div>
        </div>
      )}

      {/* TYT Puan Grafiği ve Listesi */}
      {stats.tyt_trend && stats.tyt_trend.length > 0 && (
        <div className="glass-effect rounded-2xl p-6 shadow-lg">
          <div className="flex flex-col lg:flex-row lg:items-start lg:gap-6">
            <div className="flex-1 min-w-0">
              <h3 className="text-xl font-bold mb-4 text-gray-800">📘 TYT Puan Gelişim Grafiği</h3>
              <div className="chart-container">
                <canvas ref={tytChartRef}></canvas>
              </div>
            </div>

            <div className="w-full lg:w-72 mt-6 lg:mt-0">
              <h4 className="text-lg font-semibold text-gray-800 mb-3">📋 TYT Denemeleri</h4>
              <div className="space-y-3 max-h-72 overflow-y-auto pr-1">
                {stats.tyt_trend.slice().reverse().map((exam, index) => (
                  <div key={`${exam.deneme_tarihi}-${exam.deneme_adi}-${index}`} className="p-3 rounded-xl border border-blue-100 bg-blue-50/60">
                    <div className="flex justify-between items-center">
                      <div>
                        <div className="text-sm font-semibold text-gray-900">{exam.deneme_adi || `TYT Denemesi ${index + 1}`}</div>
                        <div className="text-xs text-gray-500">{exam.deneme_tarihi}</div>
                      </div>
                      <div className="text-xs font-semibold text-blue-700 px-2 py-1 bg-white rounded-full shadow-sm">
                        {round2(exam.tyt_puan)} puan
                      </div>
                    </div>
                    <div className="mt-2 flex justify-between text-xs text-gray-700">
                      <span>Toplam Net: <strong>{round2(exam.tyt_toplam_net)}</strong></span>
                      <span>Puan: <strong>{round2(exam.tyt_puan)}</strong></span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function DersNetCard({ label, avg, max, color, textColor }) {
  return (
    <div className={`p-2 bg-gradient-to-br ${color} rounded-lg shadow-sm border border-gray-400`}>
      <div className="text-xs font-semibold text-gray-700 mb-1">{label}</div>
      <div className={`text-lg font-bold ${textColor}`}>{round2(avg || 0)}</div>
      <div className="text-xs text-gray-500 mt-1">En yüksek: {round2(max || 0)}</div>
    </div>
  );
}

function StatCard({ title, value, suffix = '', icon, color }) {
  return (
    <div className="stat-card glass-effect rounded-xl p-4 shadow-md hover:shadow-lg">
      <div className="flex items-center justify-between mb-1">
        <span className="text-2xl">{icon}</span>
        <span className={`text-2xl font-bold bg-gradient-to-r ${color} bg-clip-text text-transparent`}>
          {value}{suffix}
        </span>
      </div>
      <p className="text-gray-600 font-semibold text-sm">{title}</p>
    </div>
  );
}

// Export the StatisticsPage component so it can be imported in app.jsx
window.StatisticsPage = StatisticsPage;
