import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_URL = 'http://localhost:5000/api';

function App() {
  // --- 1. AUTH & NAVIGATION STATES ---
  // Twakuyeho kwihutira gufata mu kigega cya kera ngo bitavanga, ubu agomba kubanza kwinjira
  const [user, setUser] = useState(''); 
  const [isRegisterMode, setIsRegisterMode] = useState(false); 
  const [authForm, setAuthForm] = useState({ username: '', password: '' });
  const [activeTab, setActiveTab] = useState('dashboard'); 
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');

  // --- 2. DATA STATES ---
  const [students, setStudents] = useState([]);
  const [fees, setFees] = useState([]);
  const [payments, setPayments] = useState([]);
  const [records, setRecords] = useState([]);
  const [report, setReport] = useState([]);
  const [dashboardSummary, setDashboardSummary] = useState({ totalStudents: 0, totalExpected: 0, totalCollected: 0, totalArrears: 0 });
  const [selectedInvoice, setSelectedInvoice] = useState(null);

  // --- 3. FORM INPUT STATES ---
  const [studentInput, setStudentInput] = useState({ Name: '', Class: '' });
  const [feeInput, setFeeInput] = useState({ Amount: '', Description: '' });
  const [paymentInput, setPaymentInput] = useState({ StudentID: '', Amount: '' });
  const [recordInput, setRecordInput] = useState({ Term: 'Term 1', StudentID: '', FeeID: '' });

  // --- 4. DATA FETCHING FUNCTION ---
  const loadData = async () => {
    if (!user) return;
    try {
      const sRes = await axios.get(`${API_URL}/students`); setStudents(sRes.data);
      const fRes = await axios.get(`${API_URL}/fees`); setFees(fRes.data);
      const pRes = await axios.get(`${API_URL}/payments`); setPayments(pRes.data);
      const rRes = await axios.get(`${API_URL}/records`); setRecords(rRes.data);
      const repRes = await axios.get(`${API_URL}/reports/balances`); setReport(repRes.data);
      
      const dashRes = await axios.get(`${API_URL}/reports/dashboard-summary`); 
      setDashboardSummary(dashRes.data);
    } catch (err) {
      setError("Gufata amakuru byanze, subira ugaruke cyangwa ufungure server!");
    }
  };

  useEffect(() => {
    loadData();
  }, [user, activeTab]);

  // --- 5. AUTH HANDLERS (LOGIN & REGISTER) ---
  const handleLogin = async (e) => {
    e.preventDefault();
    setError(''); setMessage('');
    try {
      const res = await axios.post(`${API_URL}/auth/login`, authForm);
      setUser(res.data.username);
      setAuthForm({ username: '', password: '' });
      setActiveTab('dashboard');
    } catch (err) {
      setError(err.response?.data?.error || "Username cyangwa Password ntabwo ari yo!");
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setError(''); setMessage('');
    try {
      const res = await axios.post(`${API_URL}/auth/register`, authForm);
      setMessage(res.data.message);
      setIsRegisterMode(false); 
      setAuthForm({ username: '', password: '' });
    } catch (err) {
      setError(err.response?.data?.error || "Kwandika konti nshya byanze!");
    }
  };

  const handleLogout = () => {
    setUser('');
    setSelectedInvoice(null);
    setMessage('Wamaze gusohoka muri sisitemu neza.');
    setError('');
  };

  // --- INDIVIDUAL INVOICE FETCH ---
  const viewStudentInvoice = async (studentId) => {
    try {
      setError('');
      const res = await axios.get(`${API_URL}/students/${studentId}/invoice`);
      setSelectedInvoice(res.data);
      setActiveTab('student-invoice'); 
    } catch (err) {
      setError("Byanze gukurura invoice y'uyu munyeshuri.");
    }
  };

  // --- BUSINESS LOGIC SUBMITS ---
  const submitStudent = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API_URL}/students`, studentInput);
      setMessage("Umunyeshuri yanditswe neza!");
      setStudentInput({ Name: '', Class: '' });
      loadData();
    } catch (err) { setError("Byanze kwandika umunyeshuri!"); }
  };

  const submitFee = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API_URL}/fees`, feeInput);
      setMessage("Ifishi nshya y'ishuri yakozwe!");
      setFeeInput({ Amount: '', Description: '' });
      loadData();
    } catch (err) { setError("Kwandika fee byanze!"); }
  };

  const submitPayment = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API_URL}/payments`, paymentInput);
      setMessage("Ubwishyu bw'umunyeshuri bwanditswe neza!");
      setPaymentInput({ StudentID: '', Amount: '' });
      loadData();
    } catch (err) { setError("Kwandika ubwishyu byanze!"); }
  };

  const submitRecord = async (e) => {
    e.preventDefault();
    try {
      await axios.post(`${API_URL}/records`, recordInput);
      setMessage("Record y'igihe cy'ishuri yashyizweho!");
      setRecordInput({ Term: 'Term 1', StudentID: '', FeeID: '' });
      loadData();
    } catch (err) { setError("Gukora record byanze!"); }
  };

  // --- 6. IF NTA MUNTU URI MURI SYSTEM (SHOW LOGIN / REGISTER VIEW) ---
  if (!user) {
    return (
      <div className="min-h-screen bg-slate-900 flex flex-col justify-center items-center p-6">
        <div className="bg-white p-8 rounded-2xl shadow-xl w-full max-w-sm border border-slate-200">
          <h2 className="text-xl font-black text-center text-slate-800 mb-1">🔑 TSS EXAMINATION</h2>
          <p className="text-xs text-center text-slate-400 font-bold uppercase mb-6 tracking-wide">
            {isRegisterMode ? "Fungura Konti Nshya (Register)" : "Kwinjira mu Sisitemu (Login)"}
          </p>
          
          {error && <div className="p-3 mb-4 text-xs text-red-800 bg-red-100 rounded-lg font-medium">{error}</div>}
          {message && <div className="p-3 mb-4 text-xs text-green-800 bg-green-100 rounded-lg font-medium">{message}</div>}
          
          <form onSubmit={isRegisterMode ? handleRegister : handleLogin} className="space-y-4">
            <div>
              <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Username</label>
              <input type="text" required value={authForm.username} onChange={(e) => setAuthForm({ ...authForm, username: e.target.value })} className="w-full p-2.5 border rounded-lg text-sm focus:outline-blue-500" placeholder="Andika username" />
            </div>
            <div>
              <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Password</label>
              <input type="password" required value={authForm.password} onChange={(e) => setAuthForm({ ...authForm, password: e.target.value })} className="w-full p-2.5 border rounded-lg text-sm focus:outline-blue-500" placeholder="••••••••" />
            </div>
            <button type="submit" className="w-full py-2.5 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 text-sm cursor-pointer shadow-md transition-all">
              {isRegisterMode ? "Kora Konti Nshya" : "Injira mu Sisitemu"}
            </button>
          </form>

          <div className="mt-6 text-center border-t pt-4">
            <button onClick={() => { setIsRegisterMode(!isRegisterMode); setError(''); setMessage(''); }} className="text-xs text-blue-600 hover:underline font-bold cursor-pointer">
              {isRegisterMode ? "Ufite konti? Injira hano" : "Nta konti ufite? Fungura hano (Register)"}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // --- 7. RECENT SYSTEM DASHBOARD AND MAIN APP VIEW ---
  return (
    <div className="min-h-screen bg-slate-50 flex flex-col md:flex-row font-sans text-slate-800">
      {/* SIDEBAR NAVIGATION */}
      <aside className="w-full md:w-64 bg-slate-800 text-slate-100 flex flex-col shrink-0 print:hidden">
        <div className="p-5 border-b border-slate-700">
          <h2 className="text-lg font-black text-white tracking-tight">💰 SFMS MANAGER</h2>
          <p className="text-xs text-emerald-400 mt-1 font-bold">🟢 Active: {user}</p>
        </div>
        <nav className="flex-1 p-4 space-y-1.5">
          {['dashboard', 'students', 'fees', 'records', 'payments', 'report'].map((tab) => (
            <button key={tab} onClick={() => { setActiveTab(tab); setMessage(''); setError(''); }} className={`w-full text-left px-4 py-2.5 rounded-xl font-bold text-xs uppercase cursor-pointer transition-all ${activeTab === tab ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'hover:bg-slate-700 text-slate-300'}`}>
              {tab === 'dashboard' ? '🏠 Dashboard Overview' : tab === 'students' ? '👥 Students List' : tab === 'fees' ? '💵 Fee Structure' : tab === 'records' ? '📂 Term Records' : tab === 'payments' ? '💰 Payments' : '📊 Reports & Bills'}
            </button>
          ))}
        </nav>
        <div className="p-4 border-t border-slate-700">
          <button onClick={handleLogout} className="w-full py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold rounded-xl text-xs uppercase cursor-pointer shadow-md transition-all">Sohokamo</button>
        </div>
      </aside>

      {/* MAIN CONTENT AREA */}
      <main className="flex-1 p-6 overflow-y-auto">
        {message && <div className="p-3 mb-4 text-sm text-green-800 bg-green-100 rounded-xl font-medium border border-green-200 print:hidden">{message}</div>}
        {error && <div className="p-3 mb-4 text-sm text-red-800 bg-red-100 rounded-xl font-medium border border-red-200 print:hidden">{error}</div>}

        {/* ================= SECTION 1: DASHBOARD OVERVIEW ================= */}
        {activeTab === 'dashboard' && (
          <div className="space-y-6">
            <div>
              <h2 className="text-xl font-black text-slate-800">Urukurikirane rw'Amakuru (Dashboard)</h2>
              <p className="text-xs text-slate-500">Ibihe byose n'imibare y'ishuri muri rusange.</p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <p className="text-xs font-bold text-slate-400 uppercase">Abanyeshuri Bose</p>
                <p className="text-3xl font-black text-slate-800 mt-1">{dashboardSummary.totalStudents}</p>
                <span className="text-[10px] text-slate-400 font-medium">Biyandikishije muri Sisitemu</span>
              </div>
              <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <p className="text-xs font-bold text-slate-400 uppercase">Ayo Kwandika (Expected)</p>
                <p className="text-3xl font-black text-blue-600 mt-1">{dashboardSummary.totalExpected} <span className="text-xs font-bold text-slate-500">FRW</span></p>
                <span className="text-[10px] text-blue-500 font-medium">Ay'ifishi zashyizweho</span>
              </div>
              <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <p className="text-xs font-bold text-slate-400 uppercase">Ayamaze Kwakwa (Collected)</p>
                <p className="text-3xl font-black text-emerald-600 mt-1">{dashboardSummary.totalCollected} <span className="text-xs font-bold text-slate-500">FRW</span></p>
                <span className="text-[10px] text-emerald-500 font-medium">Amaze kwinjira kuri konti</span>
              </div>
              <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <p className="text-xs font-bold text-slate-400 uppercase">Ibirarane byose (Arrears)</p>
                <p className="text-3xl font-black text-rose-600 mt-1">{dashboardSummary.totalArrears} <span className="text-xs font-bold text-slate-500">FRW</span></p>
                <span className="text-[10px] text-rose-500 font-bold font-mono">Asigaye hanze</span>
              </div>
            </div>

            <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4 tracking-wider">⏱️ Ubwishyu bwiza bwa vuba (Recent Payments Log)</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead>
                    <tr className="bg-slate-50 text-slate-500 uppercase font-bold border-b">
                      <th className="p-2.5">ID</th>
                      <th className="p-2.5">Umunyeshuri</th>
                      <th className="p-2.5">Ayatanzwe</th>
                      <th className="p-2.5">Itariki n'isaha</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y text-slate-700">
                    {payments.slice(0, 5).map(p => (
                      <tr key={p.PaymentID} className="hover:bg-slate-50">
                        <td className="p-2.5 text-slate-400">#{p.PaymentID}</td>
                        <td className="p-2.5 font-bold text-slate-800">{p.Name}</td>
                        <td className="p-2.5 text-emerald-600 font-black">{p.Amount} FRW</td>
                        <td className="p-2.5 text-slate-500">{new Date(p.Date).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================= SECTION 2: STUDENTS ================= */}
        {activeTab === 'students' && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs h-fit">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">👥 Injiza Umunyeshuri</h3>
              <form onSubmit={submitStudent} className="space-y-3">
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Izina Ryose</label><input type="text" value={studentInput.Name} onChange={e => setStudentInput({ ...studentInput, Name: e.target.value })} required className="w-full p-2 border rounded-xl text-sm focus:outline-blue-500" placeholder="Urugero: Kalisa Rwigema" /></div>
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Ishuri (Class)</label><input type="text" value={studentInput.Class} onChange={e => setStudentInput({ ...studentInput, Class: e.target.value })} required className="w-full p-2 border rounded-xl text-sm focus:outline-blue-500" placeholder="Urugero: L5 SOD" /></div>
                <button type="submit" className="w-full py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl uppercase cursor-pointer">Emeza Umunyeshuri</button>
              </form>
            </div>
            <div className="lg:col-span-2 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">📋 Urutonde rw'Abanyeshuri ({students.length})</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead><tr className="bg-slate-50 uppercase font-bold text-slate-500 border-b"><th className="p-2.5">StudentID</th><th className="p-2.5">Izina Ryose</th><th className="p-2.5">Class / Level</th></tr></thead>
                  <tbody className="divide-y text-slate-700">{students.map(s => (<tr key={s.StudentID} className="hover:bg-slate-50"><td className="p-2.5 text-slate-400">#{s.StudentID}</td><td className="p-2.5 font-bold text-slate-800">{s.Name}</td><td className="p-2.5">{s.Class}</td></tr>))}</tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================= SECTION 3: FEES STRUCTURE ================= */}
        {activeTab === 'fees' && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs h-fit">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">💵 Shiraho Igiciro cy'Ishuri</h3>
              <form onSubmit={submitFee} className="space-y-3">
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Amafaranga (FRW)</label><input type="number" value={feeInput.Amount} onChange={e => setFeeInput({ ...feeInput, Amount: e.target.value })} required className="w-full p-2 border rounded-xl text-sm focus:outline-blue-500" placeholder="80000" /></div>
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Ibisobanuro</label><input type="text" value={feeInput.Description} onChange={e => setFeeInput({ ...feeInput, Description: e.target.value })} required placeholder="Tuition Fee T1" className="w-full p-2 border rounded-xl text-sm focus:outline-blue-500" /></div>
                <button type="submit" className="w-full py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl uppercase cursor-pointer">Emeza Ifishi</button>
              </form>
            </div>
            <div className="lg:col-span-2 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">📋 Ifishi z'Amafaranga Ashyiraho</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead><tr className="bg-slate-50 uppercase font-bold text-slate-500 border-b"><th className="p-2.5">Fee ID</th><th className="p-2.5">Amafaranga Asabwa</th><th className="p-2.5">Ibisobanuro</th></tr></thead>
                  <tbody className="divide-y text-slate-700">{fees.map(f => (<tr key={f.FeeID} className="hover:bg-slate-50"><td className="p-2.5 text-slate-400">#{f.FeeID}</td><td className="p-2.5 font-bold text-blue-600">{f.Amount} FRW</td><td className="p-2.5">{f.Description}</td></tr>))}</tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================= SECTION 4: TERM RECORDS ================= */}
        {activeTab === 'records' && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs h-fit">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">📂 Liha Umunyeshuri Ifishi</h3>
              <form onSubmit={submitRecord} className="space-y-3">
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Term</label><select value={recordInput.Term} onChange={e => setRecordInput({ ...recordInput, Term: e.target.value })} className="w-full p-2 border rounded-xl text-sm bg-white focus:outline-blue-500"><option value="Term 1">Term 1</option><option value="Term 2">Term 2</option><option value="Term 3">Term 3</option></select></div>
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Hitamo Umunyeshuri</label><select required onChange={e => setRecordInput({ ...recordInput, StudentID: e.target.value })} className="w-full p-2 border rounded-xl text-sm bg-white focus:outline-blue-500"><option value="">-- Hitamo uwo guha --</option>{students.map(s => <option key={s.StudentID} value={s.StudentID}>{s.Name}</option>)}</select></div>
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Hitamo Ifishi</label><select required onChange={e => setRecordInput({ ...recordInput, FeeID: e.target.value })} className="w-full p-2 border rounded-xl text-sm bg-white focus:outline-blue-500"><option value="">-- Hitamo ifishi --</option>{fees.map(f => <option key={f.FeeID} value={f.FeeID}>{f.Description} ({f.Amount} FRW)</option>)}</select></div>
                <button type="submit" className="w-full py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl uppercase cursor-pointer">Emeza Ifishi</button>
              </form>
            </div>
            <div className="lg:col-span-2 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">📋 Ibirarane Bikurikirwa (Debited Students)</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead><tr className="bg-slate-50 uppercase font-bold text-slate-500 border-b"><th className="p-2.5">Record ID</th><th className="p-2.5">Umunyeshuri</th><th className="p-2.5">Term</th><th className="p-2.5">Ayagomba Kwishyura</th></tr></thead>
                  <tbody className="divide-y text-slate-700">{records.map(r => (<tr key={r.RecordID} className="hover:bg-slate-50"><td className="p-2.5 text-slate-400">#{r.RecordID}</td><td className="p-2.5 font-bold text-slate-800">{r.StudentName}</td><td className="p-2.5">{r.Term}</td><td className="p-2.5 text-rose-600 font-bold">{r.RequiredAmount} FRW</td></tr>))}</tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================= SECTION 5: PAYMENTS LOG ================= */}
        {activeTab === 'payments' && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-xs h-fit">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">💰 Fata Ubwishyu bushya</h3>
              <form onSubmit={submitPayment} className="space-y-3">
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Hitamo Umunyeshuri</label><select required onChange={e => setPaymentInput({ ...paymentInput, StudentID: e.target.value })} className="w-full p-2 border rounded-xl text-sm bg-white focus:outline-blue-500"><option value="">-- Hitamo wishyuye --</option>{students.map(s => <option key={s.StudentID} value={s.StudentID}>{s.Name}</option>)}</select></div>
                <div><label className="text-[11px] font-bold text-slate-500 block mb-0.5">Amafaranga (FRW)</label><input type="number" value={paymentInput.Amount} onChange={e => setPaymentInput({ ...paymentInput, Amount: e.target.value })} required className="w-full p-2 border rounded-xl text-sm focus:outline-blue-500" placeholder="50000" /></div>
                <button type="submit" className="w-full py-2 bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs rounded-xl uppercase cursor-pointer">Emeza Ubwishyu</button>
              </form>
            </div>
            <div className="lg:col-span-2 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
              <h3 className="text-xs font-black text-slate-700 uppercase mb-4">📋 Amateka y'inyemezabwishyu zose</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead><tr className="bg-slate-50 uppercase font-bold text-slate-500 border-b"><th className="p-2.5">PaymentID</th><th className="p-2.5">Izina ry'Umunyeshuri</th><th className="p-2.5">Ayatanzwe</th><th className="p-2.5">Itariki</th></tr></thead>
                  <tbody className="divide-y text-slate-700">{payments.map(p => (<tr key={p.PaymentID} className="hover:bg-slate-50"><td className="p-2.5 text-slate-400">#{p.PaymentID}</td><td className="p-2.5 font-bold text-slate-800">{p.Name}</td><td className="p-2.5 text-emerald-600 font-bold">{p.Amount} FRW</td><td className="p-2.5 text-slate-500">{new Date(p.Date).toLocaleDateString()}</td></tr>))}</tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================= SECTION 6: REPORTS & GENERAL BILLS ================= */}
        {activeTab === 'report' && (
          <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-xs space-y-6">
            <div>
              <h3 className="text-sm font-black text-slate-700 uppercase">📊 Ifishi Ngari y'Ibirarane n'Ubwishyu</h3>
              <p className="text-xs text-slate-500 mt-0.5">Kanda kuri "Fungura Invoice" y'umunyeshuri ubonge inyemezabwishyu ye bwite.</p>
            </div>
            
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs border-collapse">
                <thead>
                  <tr className="bg-slate-50 uppercase font-bold text-slate-500 border-b">
                    <th className="p-3">Umunyeshuri</th>
                    <th className="p-3">Ishuri</th>
                    <th className="p-3">Ayo Asabwa</th>
                    <th className="p-3">Ayishyuwe</th>
                    <th className="p-3">Umwenda (Balance)</th>
                    <th className="p-3 text-center">Igikorwa</th>
                  </tr>
                </thead>
                <tbody className="divide-y text-slate-700">
                  {report.map(row => (
                    <tr key={row.StudentID} className="hover:bg-slate-50">
                      <td className="p-3 font-bold text-slate-800">{row.Name}</td>
                      <td className="p-3 text-slate-600">{row.Class}</td>
                      <td className="p-3">{row.TotalRequired} FRW</td>
                      <td className="p-3 text-emerald-600 font-medium">{row.TotalPaid} FRW</td>
                      <td className={`p-3 font-black ${row.Balance > 0 ? 'text-rose-600' : 'text-slate-700'}`}>{row.Balance} FRW</td>
                      <td className="p-3 text-center">
                        <button onClick={() => viewStudentInvoice(row.StudentID)} className="px-3 py-1 bg-blue-50 text-blue-600 font-bold text-[11px] rounded-lg hover:bg-blue-600 hover:text-white transition-all cursor-pointer">
                          📄 Fungura Invoice
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ================= SECTION 7: STUDENT INVOICE VIEW ================= */}
        {activeTab === 'student-invoice' && selectedInvoice && (
          <div className="space-y-6 max-w-3xl mx-auto">
            <button onClick={() => setActiveTab('report')} className="px-4 py-1.5 bg-slate-200 text-slate-700 font-bold rounded-xl text-xs uppercase cursor-pointer hover:bg-slate-300 print:hidden">
              ← Subira kuri Raporo
            </button>

            <div className="bg-white p-8 rounded-2xl border-2 border-slate-200 shadow-md space-y-6 print:border-0 print:shadow-none">
              <div className="flex justify-between items-start border-b pb-6">
                <div>
                  <h2 className="text-xl font-black text-slate-900 tracking-tight">INVOICE & STATEMENT</h2>
                  <p className="text-xs text-slate-400 mt-1">School Fee Management System</p>
                </div>
                <div className="text-right">
                  <span className={`px-3 py-1 text-xs font-black rounded-full uppercase tracking-wider ${selectedInvoice.balance <= 0 ? 'bg-green-100 text-green-800' : 'bg-rose-100 text-rose-800'}`}>
                    {selectedInvoice.balance <= 0 ? 'Yararangije (PAID)' : 'Afite Ibirarane (OWING)'}
                  </span>
                  <p className="text-[11px] text-slate-400 mt-2">Itariki: {new Date().toLocaleDateString()}</p>
                </div>
              </div>

              <div className="bg-slate-50 p-4 rounded-xl grid grid-cols-2 gap-4 text-xs">
                <div>
                  <p className="text-slate-400 font-bold uppercase text-[10px]">Ukoresha ifishi:</p>
                  <p className="text-sm font-black text-slate-800 mt-0.5">{selectedInvoice.studentInfo.Name}</p>
                  <p className="text-slate-600 mt-0.5">ID: #{selectedInvoice.studentInfo.StudentID}</p>
                </div>
                <div className="text-right">
                  <p className="text-slate-400 font-bold uppercase text-[10px]">Ishuri / Umwaka:</p>
                  <p className="text-sm font-black text-slate-800 mt-0.5">{selectedInvoice.studentInfo.Class}</p>
                </div>
              </div>

              <div>
                <h4 className="text-xs font-black text-slate-700 uppercase mb-2 tracking-wide">1. Ifishi zashyizwe kuri uyu munyeshuri (Debited Fees)</h4>
                <table className="w-full text-xs text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-100 font-bold text-slate-600 border-b">
                      <th className="p-2">Igihe (Term)</th>
                      <th className="p-2">Ibisobanuro</th>
                      <th className="p-2 text-right">Igiciro (FRW)</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {selectedInvoice.statement.map(item => (
                      <tr key={item.RecordID}>
                        <td className="p-2 font-medium">{item.Term}</td>
                        <td className="p-2 text-slate-600">{item.Description}</td>
                        <td className="p-2 text-right font-bold">{item.Amount} FRW</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div>
                <h4 className="text-xs font-black text-slate-700 uppercase mb-2 tracking-wide">2. Amateka y'Ubwishyu bwakiriwe (Payments Record)</h4>
                <table className="w-full text-xs text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-100 font-bold text-slate-600 border-b">
                      <th className="p-2">Inyemezabwishyu (ID)</th>
                      <th className="p-2">Itariki</th>
                      <th className="p-2 text-right">Ayatanzwe (FRW)</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {selectedInvoice.paymentHistory.map(pay => (
                      <tr key={pay.PaymentID}>
                        <td className="p-2 text-slate-400">#PAY-{pay.PaymentID}</td>
                        <td className="p-2 text-slate-500">{new Date(pay.Date).toLocaleDateString()}</td>
                        <td className="p-2 text-right font-black text-emerald-600">+{pay.Amount} FRW</td>
                      </tr>
                    ))}
                    {selectedInvoice.paymentHistory.length === 0 && (
                      <tr><td colSpan="3" className="p-2 text-center text-slate-400 italic">Nta bwishyu na bumwe burakirwa.</td></tr>
                    )}
                  </tbody>
                </table>
              </div>

              <div className="border-t pt-4 flex flex-col items-end text-xs space-y-1">
                <p className="text-slate-500">Igiteranyo cy'ibyo asabwa: <span className="font-bold text-slate-800">{selectedInvoice.studentInfo.TotalRequired} FRW</span></p>
                <p className="text-emerald-600">Igiteranyo cy'ibyo yishyuye: <span className="font-bold">-{selectedInvoice.studentInfo.TotalPaid} FRW</span></p>
                <div className="border-t w-48 mt-2 pt-2 text-right">
                  <p className="text-sm font-black text-slate-900">Salde (Balance): <span className={selectedInvoice.balance > 0 ? 'text-rose-600' : 'text-emerald-600'}>{selectedInvoice.balance} FRW</span></p>
                </div>
              </div>

              <div className="pt-4 text-center print:hidden">
                <button onClick={() => window.print()} className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl text-xs uppercase tracking-wide cursor-pointer transition-all shadow-md">
                  🖨️ Printa Invoice Y'uyu Munyeshuri
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

export default App;