﻿// DentSide — main app shell

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "tr",
  "sidebarTheme": "dark",
  "palette": "blue"
}/*EDITMODE-END*/;

const PALETTES = {
  blue:   { accent: "#2B47E8", accent2: "#5B82FF", mint: "#1F9F73", coral: "#E27A52", violet: "#7B5BE0" },
  teal:   { accent: "#0F7A8C", accent2: "#3FB6C4", mint: "#1F9F73", coral: "#E27A52", violet: "#7B5BE0" },
  indigo: { accent: "#4338CA", accent2: "#7C75E8", mint: "#1F9F73", coral: "#E27A52", violet: "#A78BFA" },
  forest: { accent: "#1F7A4D", accent2: "#3FB893", mint: "#16A34A", coral: "#E27A52", violet: "#7B5BE0" },
};

const DEMO_EVENTS = [
  { id:"e1",  date:"2026-05-13", startHour:9,    duration:1.5, patientId:"p6", clinicId:"c4", procedure:"İmplant cerrahisi", notes:"" },
  { id:"e2",  date:"2026-05-13", startHour:11.5, duration:0.5, patientId:"p7", clinicId:"c3", procedure:"Aktivasyon", notes:"" },
  { id:"e3",  date:"2026-05-13", startHour:14,   duration:1,   patientId:"p5", clinicId:"c1", procedure:"Office beyazlatma", notes:"" },
  { id:"e4",  date:"2026-05-13", startHour:16,   duration:0.75,patientId:"p1", clinicId:"c1", procedure:"Ölçü alımı", notes:"" },
  { id:"e5",  date:"2026-05-14", startHour:10,   duration:0.5, patientId:"p7", clinicId:"c3", procedure:"Kontrol", notes:"" },
  { id:"e6",  date:"2026-05-14", startHour:14,   duration:1,   patientId:"p2", clinicId:"c2", procedure:"Kanal kontrol", notes:"" },
  { id:"e7",  date:"2026-05-15", startHour:9,    duration:1,   patientId:"p3", clinicId:"c3", procedure:"Plak değişimi", notes:"" },
  { id:"e8",  date:"2026-05-15", startHour:11,   duration:1.5, patientId:"p8", clinicId:"c2", procedure:"Çekim kontrolü", notes:"" },
  { id:"e9",  date:"2026-05-15", startHour:15,   duration:1,   patientId:"p4", clinicId:"c2", procedure:"Kontrol", notes:"" },
  { id:"e10", date:"2026-05-16", startHour:10,   duration:2,   patientId:"p1", clinicId:"c1", procedure:"Zirkonyum prova", notes:"" },
  { id:"e11", date:"2026-05-12", startHour:14,   duration:1,   patientId:"p5", clinicId:"c1", procedure:"Dolgu", notes:"" },
  { id:"e12", date:"2026-05-11", startHour:11,   duration:1,   patientId:"p2", clinicId:"c2", procedure:"Kanal seans", notes:"" },
];

const TREATMENT_CATEGORIES = [
  "Teşhis ve Tedavi Planlaması", "Tedavi ve Endodonti", "Pedodonti",
  "Protez", "Ağız-Diş ve Çene Cerrahisi", "Periodontoloji", "Ortodonti", "Diğer",
];

function NewPatientModal({ clinics, onSave, onClose }) {
  const [form, setForm] = React.useState({
    name: "", age: "", gender: "K", phone: "", clinicId: clinics[0]?.id || "", notes: "",
  });
  const [selectedTreatments, setSelectedTreatments] = React.useState([]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const toggleTreatment = (cat) => {
    setSelectedTreatments(prev =>
      prev.includes(cat) ? prev.filter(t => t !== cat) : [...prev, cat]
    );
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.clinicId) return;
    onSave({
      ...form,
      treatment: selectedTreatments.join(", "),
      age: parseInt(form.age) || 0,
      status: "Devam ediyor",
      plan: [],
      totalFee: 0,
      paid: 0,
      balance: 0,
    });
  };

  return (
    <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal__head">
          <span className="modal__title">Yeni Hasta</span>
          <button className="icon-btn" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal__body">
            <div className="form-row">
              <div className="form-field" style={{gridColumn:"1/-1"}}>
                <label>Ad Soyad *</label>
                <input value={form.name} onChange={e => set("name", e.target.value)} placeholder="Hasta adı" required autoFocus/>
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Yaş</label>
                <input type="number" min="1" max="120" value={form.age} onChange={e => set("age", e.target.value)} placeholder="35"/>
              </div>
              <div className="form-field">
                <label>Cinsiyet</label>
                <div className="radio-group">
                  <button type="button" className={`radio-opt ${form.gender==="K"?"is-on":""}`} onClick={() => set("gender","K")}>Kadın</button>
                  <button type="button" className={`radio-opt ${form.gender==="E"?"is-on":""}`} onClick={() => set("gender","E")}>Erkek</button>
                </div>
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Telefon</label>
                <input value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="+90 5xx xxx xx xx"/>
              </div>
              <div className="form-field">
                <label>Klinik *</label>
                <select value={form.clinicId} onChange={e => set("clinicId", e.target.value)} required>
                  {clinics.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
            </div>
            <div className="form-field">
              <label>Tedavi Kategorisi <span style={{color:"var(--text-mute)",fontWeight:400}}>(çoklu seçim)</span></label>
              <div className="treat-chips">
                {TREATMENT_CATEGORIES.map(cat => (
                  <button key={cat} type="button"
                    className={`treat-chip ${selectedTreatments.includes(cat) ? "is-on" : ""}`}
                    onClick={() => toggleTreatment(cat)}>
                    {selectedTreatments.includes(cat) && <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="2,6 5,9 10,3"/></svg>}
                    {cat}
                  </button>
                ))}
              </div>
            </div>
            <div className="form-field">
              <label>Notlar</label>
              <textarea value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Genel not..." style={{minHeight:60}}/>
            </div>
          </div>
          <div className="modal__foot">
            <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
            <button type="submit" className="btn btn--accent">Hasta Ekle</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [active, setActive] = React.useState(() => localStorage.getItem("ds_active_page") || "dashboard");
  const [selectedPatient, setSelectedPatient] = React.useState(null);
  const [query, setQuery] = React.useState("");
  const [showNewPatient, setShowNewPatient] = React.useState(false);
  const [showExport, setShowExport] = React.useState(false);

  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);
  const [readNotifIds, setReadNotifIds] = React.useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem("df_notif_read") || "[]")); } catch { return new Set(); }
  });
  const [notifPrefs, setNotifPrefs] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("DentSide_notifs") || "{}"); } catch { return {}; }
  });
  React.useEffect(() => {
    const handler = () => { try { setNotifPrefs(JSON.parse(localStorage.getItem("DentSide_notifs") || "{}")); } catch {} };
    window.addEventListener("df_notifs_updated", handler);
    return () => window.removeEventListener("df_notifs_updated", handler);
  }, []);
  const markNotifsRead = React.useCallback((ids) => {
    setReadNotifIds(prev => {
      const next = new Set([...prev, ...ids]);
      localStorage.setItem("df_notif_read", JSON.stringify([...next]));
      return next;
    });
  }, []);
  const [patients, setPatients] = React.useState([]);
  const [clinics, setClinics] = React.useState([]);
  const [catalog, setCatalog] = React.useState([...window.DentSideData.TREATMENTS_CATALOG]);
  const [events, setEvents] = React.useState([]);
  const [transfers, setTransfers] = React.useState([]);
  const [dataLoaded, setDataLoaded] = React.useState(false);
  const userId = window._dentUser?.id;
  const saveTimer = React.useRef(null);
  const latestState = React.useRef({});
  const saveEnabled = React.useRef(false);

  const t = window.DentI18nStrings[tweaks.lang] || window.DentI18nStrings.tr;
  const TODAY = new Date().toISOString().slice(0, 10);
  const MONTHS = ["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"];

  const computedEarningsByClinic = React.useMemo(() => clinics.map(clinic => {
    const cp = patients.filter(p => p.clinicId === clinic.id);
    const earned = cp.reduce((sum, p) =>
      sum + (p.plan || []).filter(s => s.status === "Tamamlandı").reduce((a, s) => a + (s.share || 0), 0), 0);
    const paid = cp.reduce((sum, p) => sum + (p.paid || 0), 0);
    const pending = cp.reduce((sum, p) => sum + Math.max(0, p.balance || 0), 0);
    return { clinicId: clinic.id, earned, paid, pending };
  }), [patients, clinics]);

  const computedIncomeTrend = React.useMemo(() => {
    const byMonth = {};
    const fallback = new Date().toISOString().slice(0, 10);
    patients.forEach(p => {
      (p.plan || []).filter(s => s.status === "Tamamlandı").forEach(s => {
        const d = new Date((s.date || fallback) + "T00:00:00");
        const key = `${d.getFullYear()}-${d.getMonth()}`;
        if (!byMonth[key]) byMonth[key] = { month: MONTHS[d.getMonth()], year: d.getFullYear(), income: 0, sortKey: d.getFullYear() * 100 + d.getMonth() };
        byMonth[key].income += s.share || 0;
      });
    });
    return Object.values(byMonth).sort((a, b) => a.sortKey - b.sortKey);
  }, [patients]);

  const patientIds = React.useMemo(() => new Set(patients.map(p => p.id)), [patients]);
  const validEvent = (e) => !e.patientId || patientIds.has(e.patientId);

  const computedTodayAppts = React.useMemo(() =>
    events.filter(e => e.date === TODAY && validEvent(e)).map(e => ({
      patientId: e.patientId,
      clinicId: e.clinicId,
      procedure: e.procedure,
      time: e.startHour != null
        ? `${Math.floor(e.startHour)}:${String(Math.round((e.startHour % 1) * 60)).padStart(2, "0")}`
        : "—",
      duration: e.duration ? Math.round(e.duration * 60) : 60,
    })), [events, patients, TODAY]);

  const computedUpcoming = React.useMemo(() =>
    events
      .filter(e => e.date > TODAY && validEvent(e))
      .map(e => ({ patientId: e.patientId, clinicId: e.clinicId, date: e.date, reason: e.procedure }))
      .sort((a, b) => a.date.localeCompare(b.date)), [events, patients, TODAY]);

  const PROC_CATS = [
    { name:"İmplant",    keywords:["implant","cerrahi"] },
    { name:"Ortodonti",  keywords:["ortodonti","braket","plak","aktivasyon","şeffaf","sabit"] },
    { name:"Kanal",      keywords:["kanal"] },
    { name:"Dolgu",      keywords:["dolgu","kompozit"] },
    { name:"Zirkonyum",  keywords:["zirkonyum","kron","köprü","seramik","simant"] },
    { name:"Beyazlatma", keywords:["beyazlat"] },
    { name:"Çekim",      keywords:["çekim"] },
    { name:"Diğer",      keywords:[] },
  ];
  const computedProcedureDist = React.useMemo(() => {
    const counts = Object.fromEntries(PROC_CATS.map(c => [c.name, 0]));
    patients.forEach(p => (p.plan || []).forEach(s => {
      const proc = (s.procedure || "").toLowerCase();
      const cat = PROC_CATS.find(c => c.keywords.some(k => proc.includes(k)));
      counts[(cat || PROC_CATS[PROC_CATS.length - 1]).name]++;
    }));
    const total = Object.values(counts).reduce((a, b) => a + b, 0) || 1;
    return PROC_CATS
      .map(c => ({ name: c.name, count: counts[c.name], share: Math.round(counts[c.name] / total * 100) }))
      .filter(c => c.count > 0);
  }, [patients]);

  const data = {
    ...window.DentSideData,
    PATIENTS: patients,
    CLINICS: clinics,
    TREATMENTS_CATALOG: catalog,
    EARNINGS_BY_CLINIC: computedEarningsByClinic,
    INCOME_TREND: computedIncomeTrend,
    TODAY_APPOINTMENTS: computedTodayAppts,
    UPCOMING_CONTROLS: computedUpcoming,
    TRANSFERS: transfers,
    PROCEDURE_DISTRIBUTION: computedProcedureDist,
  };

  // Apply palette
  React.useEffect(() => {
    const p = PALETTES[tweaks.palette] || PALETTES.blue;
    const root = document.documentElement;
    Object.entries(p).forEach(([k, v]) => root.style.setProperty(`--${k.replace(/([A-Z])/g, "-$1").toLowerCase()}`, v));
    root.setAttribute("data-sidebar", tweaks.sidebarTheme);
  }, [tweaks]);

  const handleNav = (id) => {
    setActive(id);
    localStorage.setItem("ds_active_page", id);
    if (id !== "patients") setSelectedPatient(null);
  };

  React.useEffect(() => {
    document.querySelector(".content")?.scrollTo({ top: 0, behavior: "instant" });
  }, [active]);

  const handleSearch = (val) => {
    setQuery(val);
    if (val && active !== "patients") setActive("patients");
  };

  const handleAddPatient = (newPatient) => {
    const id = "p" + (patients.length + 1 + Date.now());
    const added = { ...newPatient, id, payments: [] };
    setPatients(prev => [...prev, added]);
    setShowNewPatient(false);
    setActive("patients");
    setSelectedPatient(added.id);
  };

  const handleUpdatePatient = (id, updates) => {
    if (updates._delete) {
      setPatients(prev => prev.filter(p => p.id !== id));
      setSelectedPatient(null);
    } else {
      setPatients(prev => prev.map(p => p.id === id ? { ...p, ...updates } : p));
    }
  };

  const handleImportPatients = ({ patients: imported, newClinics }) => {
    if (newClinics?.length) {
      setClinics(prev => [...prev, ...newClinics]);
    }
    setPatients(prev => [...prev, ...imported]);
  };

  const { Sidebar, Topbar } = window.DentUI;
  const { Clinics, Finance, Schedule, Treatments, Reports, Settings, Help, Stock, Placeholder } = window.DentViews;

  const badges = React.useMemo(() => {
    const today = new Date(); today.setHours(0,0,0,0);
    const in7 = new Date(today); in7.setDate(in7.getDate() + 7);
    const scheduleBadge = events.filter(a => {
      const d = new Date(a.date + "T00:00:00");
      return d >= today && d <= in7 && validEvent(a);
    }).length;
    const financeBadge = data.CLINICS.reduce((sum, c) => {
      const earned = (computedEarningsByClinic.find(e => e.clinicId === c.id) || {}).earned || 0;
      const transferred = transfers.filter(t => t.clinicId === c.id).reduce((a, t) => a + t.amount, 0);
      return sum + (earned > transferred ? 1 : 0);
    }, 0);
    return { schedule: scheduleBadge, finance: financeBadge };
  }, [patients, events, transfers, computedEarningsByClinic]);

  const notifications = React.useMemo(() => {
    const result = [];
    const fmtTL = (n) => new Intl.NumberFormat("tr-TR",{style:"currency",currency:"TRY",maximumFractionDigits:0}).format(n);

    // Randevu hatırlatıcısı (varsayılan: açık)
    if (notifPrefs.apptReminder !== false) {
      const tomorrow = new Date(Date.now() + 86400000).toISOString().slice(0, 10);
      const fmtH = (h) => `${String(Math.floor(h)).padStart(2,"0")}:${String(Math.round((h%1)*60)).padStart(2,"0")}`;
      events.filter(e => e.date === tomorrow && validEvent(e)).forEach(e => {
        const patient = e.patientId ? patients.find(p => p.id === e.patientId) : (e.patientName ? { name: e.patientName } : null);
        const clinic = clinics.find(c => c.id === e.clinicId);
        result.push({ id: `appt_${e.id}`, type: "appointment", title: "Yarınki randevu",
          body: `${patient?.name || "Hasta"} — ${e.procedure}${clinic ? ", " + clinic.name : ""}`,
          time: fmtH(e.startHour), nav: "schedule" });
      });
    }

    // Bekleyen alacak uyarısı
    if (notifPrefs.pendingAlert) {
      computedEarningsByClinic.forEach(e => {
        if (e.pending > 0) {
          const clinic = clinics.find(c => c.id === e.clinicId);
          if (clinic) result.push({ id: `pending_${e.clinicId}`, type: "alert", title: "Bekleyen alacak",
            body: `${clinic.name}: ${fmtTL(e.pending)} tahsil edilmedi`, time: "Bugün", nav: "finance" });
        }
      });
    }

    // Ödeme bildirimi — son 7 günde kaydedilen transferler
    if (notifPrefs.paymentAlert) {
      const cutoff = new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10);
      transfers.filter(t => t.date >= cutoff && t.amount > 0).slice(0, 5).forEach(t => {
        const clinic = clinics.find(c => c.id === t.clinicId);
        result.push({ id: `pay_${t.id || t.date + t.clinicId}`, type: "payment", title: "Ödeme alındı",
          body: `${clinic?.name || "Klinik"}: ${fmtTL(t.amount)}`, time: t.date, nav: "finance" });
      });
    }

    return result;
  }, [events, patients, clinics, notifPrefs, computedEarningsByClinic, transfers]);

  // Re-select when navigating to patients (desktop only)
  React.useEffect(() => {
    if (active === "patients" && !selectedPatient && data.PATIENTS.length > 0 && window.innerWidth >= 768) {
      setSelectedPatient(data.PATIENTS[0].id);
    }
  }, [active]);

  // Supabase: kullanıcı verisini yükle
  React.useEffect(() => {
    if (!userId) { window.location.href = 'giris.html'; return; }
    (async () => {
      try {
        const { data: rows, error: loadErr } = await window._sb
          .from('ds_user_data')
          .select('*')
          .eq('user_id', userId)
          .limit(1);
        const row = rows?.[0];
        if (loadErr) {
          // Yükleme hatası: veri yazılmıyor, demo state olduğu gibi kalıyor
          // saveEnabled false kalıyor — save effect çalışmaz
        } else if (row) {
          // Mevcut kullanıcı verisi — doktorun kayıtlarını yükle
          let patientsLoaded = false;
          if (row.patients?.length === 1 && row.patients[0]?.__enc) {
            try {
              const dec = await window.DentCrypto.decrypt(userId, row.patients[0].__enc);
              setPatients(dec);
              patientsLoaded = true;
            } catch(e) {
              console.error('[DS] Hasta şifresi çözülemedi, kaydetme devre dışı', e);
            }
          } else if (Array.isArray(row.patients)) {
            setPatients(row.patients);
            patientsLoaded = true;
          }
          if (row.clinics != null) setClinics(row.clinics);
          if (row.events != null) setEvents(row.events);
          if (row.transfers != null) setTransfers(row.transfers);
          if (row.catalog != null) setCatalog(row.catalog);
          if (patientsLoaded) saveEnabled.current = true;
        } else {
          // Gerçek ilk giriş: boş kayıt oluştur
          const encPat = await window.DentCrypto.encrypt(userId, []);
          await window._sb.from('ds_user_data').upsert({
            user_id: userId,
            patients: [{ __enc: encPat }],
            clinics: [],
            events: [],
            transfers: [],
            catalog: window.DentSideData.TREATMENTS_CATALOG,
          }, { onConflict: 'user_id' });
          saveEnabled.current = true;
        }
      } catch(e) {}
      setDataLoaded(true);
    })();
  }, []);

  // her değişiklikte latestState ref'ini güncelle (beforeunload için)
  React.useEffect(() => {
    latestState.current = { patients, clinics, events, transfers, catalog, dataLoaded };
  }, [patients, clinics, events, transfers, catalog, dataLoaded]);

  // Supabase: her veri değişikliğinde otomatik kaydet (200ms debounce, hasta verisi şifreli)
  React.useEffect(() => {
    if (!dataLoaded || !saveEnabled.current) return;
    if (saveTimer.current) clearTimeout(saveTimer.current);
    saveTimer.current = setTimeout(async () => {
      try {
        const encPat = await window.DentCrypto.encrypt(userId, patients);
        const { error } = await window._sb.from('ds_user_data').upsert({
          user_id: userId,
          patients: [{ __enc: encPat }],
          clinics, events, transfers, catalog,
        }, { onConflict: 'user_id' });
        if (error) console.error('[DS Save Error]', error);
      } catch(e) { console.error('[DS Save Exception]', e); }
    }, 200);
  }, [patients, clinics, events, transfers, catalog, dataLoaded]);

  // Sayfa kapanmadan/yenilenmeden önce bekleyen veriyi hemen kaydet
  React.useEffect(() => {
    const flushSave = () => {
      const s = latestState.current;
      if (!s.dataLoaded || !userId) return;
      if (saveTimer.current) clearTimeout(saveTimer.current);
      window.DentCrypto.encrypt(userId, s.patients).then(encPat => {
        window._sb.from('ds_user_data').upsert({
          user_id: userId,
          patients: [{ __enc: encPat }],
          clinics: s.clinics, events: s.events, transfers: s.transfers, catalog: s.catalog,
        }, { onConflict: 'user_id' }).catch(() => {});
      }).catch(() => {});
    };
    window.addEventListener('beforeunload', flushSave);
    return () => window.removeEventListener('beforeunload', flushSave);
  }, []);

  if (!dataLoaded) return (
    <div style={{position:"fixed",inset:0,background:"#f5f7ff",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:16,fontFamily:"Inter,sans-serif"}}>
      <div style={{width:44,height:44,borderRadius:11,background:"linear-gradient(135deg,#2B47E8,#5B82FF)",display:"grid",placeItems:"center"}}>
        <svg width="26" height="26" viewBox="0 0 479.82 440.39" fill="white"><path d="M239.91,229.04c18.22,0,33.05-14.83,33.05-33.05,0-15.16-10.27-27.97-24.22-31.84V20.12h-17.66s0,144.03,0,144.03c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05ZM239.91,180.61c8.48,0,15.38,6.9,15.38,15.38s-6.9,15.39-15.38,15.39-15.38-6.9-15.38-15.38,6.9-15.39,15.38-15.39Z"/><path d="M19.81,197.47C9.51,128.08,37.01,66.89,93.39,33.78c18.21-10.69,38.17-16.12,59.33-16.12,11.33,0,22.98,1.58,34.87,4.69v90.98l-40.7,23.5v107.35c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05s33.05-14.83,33.05-33.05c0-15.16-10.27-27.97-24.22-31.84v-97.15l40.7-23.5V9.26C187.36,3.12,169.77,0,152.72,0c-24.35,0-47.32,6.24-68.28,18.55C21.63,55.44-9.06,123.3,2.34,200.07c9.03,60.8,24.33,120.64,43.08,168.5,9.35,23.85,19.21,43.88,29.31,59.52l14.84-9.58c-9.46-14.65-18.78-33.62-27.7-56.38-18.28-46.66-33.22-105.13-42.06-164.65ZM171.11,276.02c0,8.48-6.9,15.38-15.38,15.38s-15.38-6.9-15.38-15.38,6.9-15.38,15.38-15.38,15.38,6.9,15.38,15.38Z"/><path d="M395.38,18.55C374.42,6.24,351.45,0,327.1,0c-17.05,0-34.64,3.12-52.54,9.26v114.27l40.7,23.5v97.15c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05s33.05-14.83,33.05-33.05c0-15.16-10.27-27.97-24.22-31.84v-107.35l-40.7-23.5V22.35c11.9-3.11,23.55-4.69,34.87-4.69,21.16,0,41.12,5.42,59.33,16.12,56.38,33.11,83.88,94.3,73.57,163.69-8.84,59.52-23.78,118-42.06,164.65-8.91,22.76-18.23,41.72-27.7,56.38l14.84,9.58c10.1-15.65,19.96-35.67,29.3-59.52,18.75-47.86,34.05-107.69,43.08-168.5,11.4-76.77-19.29-144.63-82.1-181.52ZM339.49,276.02c0,8.48-6.9,15.38-15.38,15.38s-15.38-6.9-15.38-15.38,6.9-15.38,15.38-15.38,15.38,6.9,15.38,15.38Z"/><path d="M442.54,194.88c9.21-62.01-15.11-116.54-65.05-145.87-18.23-10.71-38.11-15.16-59.44-13.37v17.82c18.33-1.78,35.21,1.81,50.49,10.78,44.15,25.93,64.76,72.6,56.52,128.04-8.46,56.96-22.67,112.71-40.01,156.95-18.36,46.86-35.02,67.52-44.49,71.22-7.94,3.1-15.07,3.07-21.83-.09-10.85-5.09-20.51-18.3-26.5-36.27-2.01-6.04-3.84-14.03-5.78-22.48-7.1-31.04-15.94-69.68-46.55-69.68s-39.45,38.63-46.55,69.68c-1.93,8.45-3.76,16.44-5.78,22.48-5.99,17.96-15.65,31.18-26.5,36.27-6.75,3.16-13.89,3.2-21.83.09-9.47-3.7-26.13-24.36-44.49-71.22-17.34-44.25-31.54-99.99-40.01-156.95-8.24-55.44,12.36-102.11,56.52-128.04,15.28-8.97,32.16-12.56,50.49-10.78v-17.82c-21.33-1.78-41.2,2.66-59.44,13.37-49.94,29.33-74.26,83.86-65.05,145.87,8.65,58.24,23.23,115.35,41.03,160.8,12.65,32.28,32.37,72.57,54.51,81.23,5.94,2.32,11.88,3.48,17.69,3.48,6.25,0,12.33-1.34,18.06-4.03,20.83-9.76,31.35-33.43,35.77-46.68,2.28-6.85,4.2-15.24,6.24-24.13,5.7-24.93,12.8-55.96,29.33-55.96s23.62,31.02,29.33,55.95c2.03,8.88,3.95,17.28,6.24,24.13,4.42,13.24,14.93,36.92,35.77,46.68,11.06,5.18,23.42,5.37,35.75.55,22.14-8.66,41.86-48.95,54.51-81.23,17.81-45.45,32.38-102.56,41.03-160.8Z"/></svg>
      </div>
      <div style={{fontSize:13,color:"#9ca3af"}}>Yükleniyor...</div>
    </div>
  );

  return (
    <window.DentI18n.Provider value={t}>
      <div className={`sidebar-overlay${sidebarOpen ? " is-open" : ""}`} onClick={() => setSidebarOpen(false)}/>
      <div className={`app${sidebarCollapsed ? " sb-collapsed" : ""}`}>
        <Sidebar active={active} onNav={handleNav} theme={tweaks.sidebarTheme} badges={badges} isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} isCollapsed={sidebarCollapsed} onToggleCollapse={() => setSidebarCollapsed(v => !v)}/>
        <div className="main">
          <Topbar active={active} onSearch={handleSearch} query={query} onNav={handleNav} onQuickAdd={() => setShowNewPatient(true)} onExport={() => setShowExport(true)} onToggleSidebar={() => setSidebarOpen(v => !v)} notifications={notifications} readNotifIds={readNotifIds} onMarkNotifsRead={markNotifsRead}/>
          {showExport && <window.DentDashboard.ExportModal data={data} onClose={() => setShowExport(false)}/>}
          <div className="content">
            {active === "dashboard" && <window.DentDashboard.Dashboard data={data} onNav={handleNav} setSelectedPatient={setSelectedPatient} onNewPatient={() => setShowNewPatient(true)}/>}
            {active === "patients" && <window.DentPatients data={data} selectedPatient={selectedPatient} setSelectedPatient={setSelectedPatient} filter={query} setFilter={setQuery} onNewPatient={() => setShowNewPatient(true)} onUpdatePatient={handleUpdatePatient} onImportPatients={handleImportPatients}/>}
            {active === "clinics" && <Clinics data={data} onNav={handleNav}
              onAddClinic={(clinic) => setClinics(prev => [...prev, clinic])}
              onEditClinic={(id, updates) => setClinics(prev => prev.map(c => c.id === id ? { ...c, ...updates } : c))}
              onDeleteClinic={(id) => setClinics(prev => prev.filter(c => c.id !== id))}
            />}
            {active === "finance" && <Finance data={data} transfers={transfers} onUpdateTransfers={setTransfers}/>}
            {active === "schedule" && <Schedule data={data} events={events} onUpdateEvents={setEvents} setSelectedPatient={setSelectedPatient} onNav={handleNav}/>}
            {active === "treatments" && <Treatments data={data} onNav={handleNav} setSelectedPatient={setSelectedPatient} onUpdatePatient={handleUpdatePatient} onUpdateCatalog={setCatalog}/>}
            {active === "stock" && <Stock data={data}/>}
            {active === "reports" && <Reports data={data}/>}
            {active === "settings" && <Settings tweaks={tweaks} setTweak={setTweak} data={data}/>}
            {active === "help" && <Help/>}
          </div>
        </div>

        {showNewPatient && (
          <NewPatientModal
            clinics={data.CLINICS}
            onSave={handleAddPatient}
            onClose={() => setShowNewPatient(false)}
          />
        )}

        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Sidebar teması">
            <window.TweakRadio value={tweaks.sidebarTheme} onChange={v => setTweak("sidebarTheme", v)}
              options={[{value:"dark",label:"Koyu"},{value:"light",label:"Açık"}]}/>
          </window.TweakSection>
          <window.TweakSection title="Renk paleti">
            <window.TweakColor value={tweaks.palette} onChange={v => setTweak("palette", v)}
              options={[
                { value: "blue", color: PALETTES.blue.accent, label: "Klinik Mavi" },
                { value: "teal", color: PALETTES.teal.accent, label: "Teal" },
                { value: "indigo", color: PALETTES.indigo.accent, label: "Indigo" },
                { value: "forest", color: PALETTES.forest.accent, label: "Forest" },
              ]}/>
          </window.TweakSection>

        </window.TweaksPanel>
      </div>
    </window.DentI18n.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
