﻿// Patients list + detail panel

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

const CHRONIC_CONDITIONS = [
  "Diyabet", "Hipertansiyon", "Kalp Hastalığı", "Kan Sulandırıcı",
  "Astım", "Epilepsi", "Hepatit B", "Hepatit C", "HIV",
  "Tiroid Hastalığı", "Böbrek Hastalığı", "Kanser / Kemoterapi",
  "Osteoporoz", "Hamilelik",
];

function useSpeechToText(onFinal) {
  const [listening, setListening] = React.useState(false);
  const recRef = React.useRef(null);
  const cbRef = React.useRef(onFinal);
  cbRef.current = onFinal;
  const supported = !!(window.SpeechRecognition || window.webkitSpeechRecognition);
  const toggle = React.useCallback(() => {
    if (!supported) return;
    if (recRef.current) {
      recRef.current.stop();
      recRef.current = null;
      setListening(false);
      return;
    }
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    const rec = new SR();
    rec.lang = 'tr-TR';
    rec.continuous = true;
    rec.interimResults = false;
    rec.onresult = (e) => {
      let text = '';
      for (let i = e.resultIndex; i < e.results.length; i++) {
        if (e.results[i].isFinal) text += e.results[i][0].transcript;
      }
      if (text.trim()) cbRef.current(text.trim() + ' ');
    };
    rec.onend = () => { setListening(false); recRef.current = null; };
    rec.onerror = () => { setListening(false); recRef.current = null; };
    rec.start();
    recRef.current = rec;
    setListening(true);
  }, [supported]);
  React.useEffect(() => () => { recRef.current?.stop(); }, []);
  return { listening, toggle, supported };
}

function VoiceButton({ onTranscript, style }) {
  const { listening, toggle, supported } = useSpeechToText(onTranscript);
  if (!supported) return null;
  return (
    <button type="button" className={`voice-btn${listening ? ' voice-btn--active' : ''}`} onClick={toggle}
      title={listening ? 'Dinleniyor — durdurmak için tıkla' : 'Sesle not ekle (Türkçe)'} style={style}>
      {listening
        ? <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><rect x="7" y="7" width="10" height="10" rx="1.5"/></svg>
        : <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="2" width="6" height="11" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="19" x2="12" y2="22"/><line x1="8" y1="22" x2="16" y2="22"/></svg>
      }
      <span>{listening ? 'Durdurun' : 'Sesle'}</span>
    </button>
  );
}

function Patients({ data, selectedPatient, setSelectedPatient, filter, setFilter, onNewPatient, onUpdatePatient, onImportPatients, onAddEvents }) {
  const { useT, Card, StatusPill, Avatar, fmtTRY, fmtDate, daysFromToday } = window.DentUI;
  const I = window.DentIcons;
  const t = useT();
  const [clinicFilter, setClinicFilter] = React.useState("all");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [showArchive, setShowArchive] = React.useState(false);
  const [importResult, setImportResult] = React.useState(null);
  const importRef = React.useRef();
  const [windowWidth, setWindowWidth] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const handler = () => setWindowWidth(window.innerWidth);
    window.addEventListener("resize", handler);
    return () => window.removeEventListener("resize", handler);
  }, []);

  const [showOdontogram, setShowOdontogram] = React.useState(false);
  const [odontActiveTool, setOdontActiveTool] = React.useState('caries');
  React.useEffect(() => { setShowOdontogram(false); }, [selectedPatient]);

  const findC = (id) => (data.DOCTORS || []).find(d => d.id === id);

  const handleDownloadTemplate = () => {
    const XLSX = window.XLSX;
    const doctorNames = (data.DOCTORS || []).map(d => d.name).join(" / ");
    const rows = [
      ["Ad Soyad *", "Yaş", "Cinsiyet (K/E) *", "Telefon", `Hekim * (${doctorNames || "Hekim adı"})`, "Tedavi", "Durum", "Toplam Tutar (₺)", "Tahsil Edilen (₺)", "Notlar"],
      ["Örnek: Ayşe Yılmaz", "35", "K", "+90 532 000 00 00", (data.DOCTORS||[])[0]?.name || "", "İmplant", "Devam ediyor", "18000", "9000", "Örnek not..."],
    ];
    const ws = XLSX.utils.aoa_to_sheet(rows);
    ws["!cols"] = [22,6,18,16,28,20,16,18,18,40].map(w => ({ wch: w }));
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Hasta Taslağı");
    XLSX.writeFile(wb, "DentSide_Hasta_Taslak.xlsx");
  };

  const handleImport = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const XLSX = window.XLSX;
        const wb = XLSX.read(ev.target.result, { type: "array" });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const rows = XLSX.utils.sheet_to_json(ws, { header: 1 });
        const dataRows = rows.slice(1).filter(r => r[0]);

        const DOCTOR_COLORS = ["#3B82F6","#8B5CF6","#10B981","#F59E0B","#EF4444","#06B6D4","#EC4899","#84CC16"];
        const newDoctorsMap = {};
        const existingDoctors = data.DOCTORS || [];
        dataRows.forEach(r => {
          const doctorName = String(r[4] || "").trim();
          if (!doctorName) return;
          const exists = existingDoctors.find(d => d.name.toLowerCase() === doctorName.toLowerCase());
          if (!exists && !newDoctorsMap[doctorName.toLowerCase()]) {
            const colorIdx = (Object.keys(newDoctorsMap).length + existingDoctors.length) % DOCTOR_COLORS.length;
            newDoctorsMap[doctorName.toLowerCase()] = {
              id: "doc_imp_" + Date.now() + "_" + Object.keys(newDoctorsMap).length,
              name: doctorName,
              color: DOCTOR_COLORS[colorIdx],
              share: 50,
              contract: "Yüzdelik",
              specialty: "Genel Diş Hekimliği",
            };
          }
        });
        const newClinics = Object.values(newDoctorsMap);
        const allDoctors = [...existingDoctors, ...newClinics];

        const imported = dataRows.map((r, i) => {
          const doctorName = String(r[4] || "").trim();
          const doctor = allDoctors.find(d => d.name.toLowerCase() === doctorName.toLowerCase()) || allDoctors[0];
          const totalFee = parseFloat(r[7]) || 0;
          const paid = parseFloat(r[8]) || 0;
          return {
            id: "imp_" + Date.now() + "_" + i,
            name: String(r[0] || "").trim(),
            age: parseInt(r[1]) || 0,
            gender: String(r[2] || "K").trim().toUpperCase() === "E" ? "E" : "K",
            phone: String(r[3] || "").trim(),
            doctorId: doctor?.id || "",
            treatment: String(r[5] || "").trim(),
            status: String(r[6] || "Devam ediyor").trim(),
            totalFee,
            paid,
            balance: totalFee - paid,
            notes: String(r[9] || "").trim(),
            plan: [],
            payments: [],
            files: [],
          };
        }).filter(p => p.name);
        setImportResult({ count: imported.length, patients: imported, newClinics });
      } catch (err) {
        setImportResult({ error: "Dosya okunamadı. Lütfen taslak formatını kullanın." });
      }
    };
    reader.readAsArrayBuffer(file);
    e.target.value = "";
  };

  const confirmImport = () => {
    onImportPatients({ patients: importResult.patients, newClinics: importResult.newClinics });
    setImportResult(null);
  };

  let patients = data.PATIENTS.filter(p => showArchive ? p.archived : !p.archived);
  if (!showArchive && clinicFilter !== "all") patients = patients.filter(p => p.clinicId === clinicFilter);
  if (!showArchive && statusFilter !== "all") patients = patients.filter(p => p.status === statusFilter);
  if (filter) patients = patients.filter(p => p.name.toLowerCase().includes(filter.toLowerCase()));
  const archivedCount = data.PATIENTS.filter(p => p.archived).length;

  const isMobile = windowWidth < 768;
  const selP = selectedPatient
    ? data.PATIENTS.find(p => p.id === selectedPatient)
    : (isMobile ? null : data.PATIENTS[0]);

  return (
    <div className="view view--split" style={isMobile ? {display:"block"} : {}}>
      <div className="split__list" style={isMobile ? {width:"100%"} : {}}>
        <div className="page-head" style={isMobile ? {flexDirection:"column", alignItems:"stretch", gap:8} : {}}>
          <div>
            <h1 className="page-title">{showArchive ? "Arşiv" : "Hastalar"}</h1>
            <p className="page-sub">{patients.length} hasta · {showArchive ? "arşivlendi" : `${data.CLINICS.length} klinik`}</p>
          </div>
          <div className="page-actions" style={isMobile ? {display:"flex", flexWrap:"nowrap", gap:4, justifyContent:"flex-start"} : {}}>
            <button className="btn btn--ghost pt-btn-secondary" onClick={handleDownloadTemplate}>
              <I.Export size={15}/>Taslak İndir
            </button>
            <button className="btn btn--ghost pt-btn-secondary" onClick={() => importRef.current.click()}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
              Excel İmport
            </button>
            {!isMobile && <button className={`btn ${showArchive ? "btn--accent" : "btn--ghost"}`} onClick={() => { setShowArchive(v => !v); setClinicFilter("all"); setStatusFilter("all"); }} style={{gap:6}}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg>
              Arşiv{archivedCount > 0 ? ` (${archivedCount})` : ""}
            </button>}
            <input ref={importRef} type="file" accept=".xlsx,.xls" style={{display:"none"}} onChange={handleImport}/>
          </div>
        </div>

        {isMobile ? (
          <div className="seg" style={{marginBottom:8}}>
            <button className={`seg__opt ${!showArchive && statusFilter==="all"?"is-on":""}`} onClick={()=>{ setShowArchive(false); setStatusFilter("all"); }}>Tümü</button>
            <button className={`seg__opt ${!showArchive && statusFilter==="Devam ediyor"?"is-on":""}`} onClick={()=>{ setShowArchive(false); setStatusFilter("Devam ediyor"); }}>Aktif</button>
            <button className={`seg__opt ${!showArchive && statusFilter==="Tamamlandı"?"is-on":""}`} onClick={()=>{ setShowArchive(false); setStatusFilter("Tamamlandı"); }}>Biten</button>
            <button className={`seg__opt ${showArchive?"is-on":""}`} onClick={()=>{ setShowArchive(true); setStatusFilter("all"); }}>Arşiv{archivedCount > 0 ? ` (${archivedCount})` : ""}</button>
          </div>
        ) : (!showArchive && (
          <div className="filters-bar">
            <div className="chips">
              <button className={`chip ${clinicFilter==="all"?"is-on":""}`} onClick={()=>setClinicFilter("all")}>
                Tüm Klinikler
                <span className="chip-count">{data.PATIENTS.filter(p=>!p.archived).length}</span>
              </button>
              {data.CLINICS.map(c => (
                <button key={c.id} className={`chip ${clinicFilter===c.id?"is-on":""}`} onClick={()=>setClinicFilter(c.id)}>
                  <span className="clinic-bullet" style={{background:c.color}}/>
                  {c.name.split(" ").slice(0,2).join(" ")}
                  <span className="chip-count">{data.PATIENTS.filter(p=>p.clinicId===c.id&&!p.archived).length}</span>
                </button>
              ))}
            </div>
            <div className="seg">
              <button className={`seg__opt ${statusFilter==="all"?"is-on":""}`} onClick={()=>setStatusFilter("all")}>Tümü</button>
              <button className={`seg__opt ${statusFilter==="Devam ediyor"?"is-on":""}`} onClick={()=>setStatusFilter("Devam ediyor")}>Aktif</button>
              <button className={`seg__opt ${statusFilter==="Tamamlandı"?"is-on":""}`} onClick={()=>setStatusFilter("Tamamlandı")}>Biten</button>
            </div>
          </div>
        ))}

        {isMobile ? (
          <div style={{borderRadius:"12px",background:"#fff",border:"1px solid #e5e7eb"}}>
            {patients.length === 0 && (
              <div style={{padding:"20px",textAlign:"center",color:"#9ca3af",fontSize:"13px"}}>{showArchive ? "Arşivde hasta yok" : "Hasta bulunamadı"}</div>
            )}
            {patients.map((p, idx) => {
              const c = findC(p.clinicId);
              const isSel = p.id === selectedPatient;
              const ini = p.name.split(" ").map(function(s){return s[0];}).slice(0,2).join("").toUpperCase();
              const clinicColor = (c && c.color) ? c.color : "#5B8DEF";
              const statusColor = p.status === "Tamamlandı" ? "#10b981" : "#2B47E8";
              return (
                <div
                  key={p.id}
                  onClick={() => setSelectedPatient(isSel ? null : p.id)}
                  style={{
                    padding:"11px 14px",
                    borderTop: idx === 0 ? "none" : "1px solid #e5e7eb",
                    background: isSel ? "#eef1fd" : "#fff",
                    cursor:"pointer",
                  }}
                >
                  <span style={{
                    display:"inline-block", verticalAlign:"middle",
                    width:"38px", height:"38px", borderRadius:"50%",
                    background:"linear-gradient(135deg,"+clinicColor+","+clinicColor+"cc)",
                    textAlign:"center", lineHeight:"38px",
                    color:"#fff", fontWeight:"600", fontSize:"15px",
                    flexShrink:"0",
                  }}>{ini}</span>
                  <span style={{
                    display:"inline-block", verticalAlign:"middle",
                    paddingLeft:"10px",
                    width:"calc(100% - 48px)",
                    boxSizing:"border-box",
                  }}>
                    <span style={{display:"block",fontSize:"14px",fontWeight:"700",color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{p.name}</span>
                    <span style={{display:"block",fontSize:"12px",color:"#6b7280",marginTop:"2px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>
                      {c ? c.name : "—"} · <span style={{color:statusColor,fontWeight:"600"}}>{p.status}</span>
                    </span>
                  </span>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="pt-table">
            <div className="pt-row pt-row--head">
              <span>Hasta</span>
              <span>Klinik</span>
              <span>Tedavi</span>
              <span>Durum</span>
              <span>Toplam / Kalan</span>
              <span>Son seans</span>
            </div>
            {patients.length === 0 && (
              <div style={{padding:"32px",textAlign:"center",color:"#9ca3af",fontSize:"13px"}}>{showArchive ? "Arşivde hasta yok" : "Hasta bulunamadı"}</div>
            )}
            {patients.map(p => {
              const c = findC(p.clinicId);
              const lastSession = [...p.plan].filter(s => s.status === "Tamamlandı").pop();
              const isSel = p.id === selectedPatient;
              const pct = p.totalFee ? Math.round((p.paid / p.totalFee) * 100) : 0;
              return (
                <button key={p.id} className={`pt-row ${isSel?"is-sel":""}`} onClick={() => setSelectedPatient(isSel ? null : p.id)}>
                  <span className="pt-patient">
                    <Avatar name={p.name} size={36} clinicColor={c.color}/>
                    <div>
                      <div className="pt-name">{p.name}</div>
                      <div className="pt-meta">{p.age} y · {p.gender}<span className="pt-meta-clinic"> · {c.name}</span></div>
                    </div>
                  </span>
                  <span className="pt-clinic">
                    <span className="clinic-bullet" style={{background:c.color}}/>
                    <span>{c.name}</span>
                  </span>
                  <span className="pt-treat">{p.treatment}</span>
                  <span><StatusPill status={p.status}/></span>
                  <span>
                    <div className="pt-pay">
                      <div className="pt-pay__row">
                        <span className="num">{fmtTRY(p.totalFee)}</span>
                        <span className="num" style={{color: p.balance > 0 ? "var(--coral)" : "var(--mint)"}}>
                          {p.balance > 0 ? fmtTRY(p.balance) : "Tamam"}
                        </span>
                      </div>
                      <div className="pt-pay__bar">
                        <span className="pt-pay__fill" style={{width:`${pct}%`}}/>
                      </div>
                    </div>
                  </span>
                  <span className="pt-last muted">{lastSession ? fmtDate(lastSession.date) : "—"}</span>
                </button>
              );
            })}
          </div>
        )}
        {!isMobile && selP && showOdontogram && (
          <div className="split-odont">
            <div className="split-odont__head">
              <span className="split-odont__title">Odontogram — {selP.name}</span>
              <button className="icon-btn" onClick={() => setShowOdontogram(false)} title="Kapat">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
                  <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                </svg>
              </button>
            </div>
            <OdontogramChart
              patient={selP}
              onUpdate={(updates) => onUpdatePatient(selP.id, updates)}
              activeTool={odontActiveTool}
              setActiveTool={setOdontActiveTool}
            />
          </div>
        )}
      </div>

      {isMobile && selP && (
        <div className="pt-detail-overlay" onClick={() => setSelectedPatient(null)}>
          <div className="pt-detail-sheet" onClick={e => e.stopPropagation()}>
            <div className="pt-sheet-handle" onClick={() => setSelectedPatient(null)}>
              <button className="pt-sheet-close">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="6 9 12 15 18 9"/></svg>
              </button>
            </div>
            <PatientDetail key={selP.id} patient={selP} data={data} onClose={() => setSelectedPatient(null)} onUpdate={(updates) => onUpdatePatient(selP.id, updates)} onAddEvents={onAddEvents}/>
          </div>
        </div>
      )}
      {!isMobile && selP && <PatientDetail key={selP.id} patient={selP} data={data} onClose={() => setSelectedPatient(null)} onUpdate={(updates) => onUpdatePatient(selP.id, updates)} onOpenOdontogram={() => setShowOdontogram(true)} onAddEvents={onAddEvents}/>}

      {importResult && (
        <div className="modal-overlay" onClick={() => setImportResult(null)}>
          <div className="modal" style={{maxWidth:400}} onClick={e => e.stopPropagation()}>
            <div className="modal__head">
              <span className="modal__title">{importResult.error ? "Hata" : "İmport Onayı"}</span>
              <button className="icon-btn" onClick={() => setImportResult(null)}>
                <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>
            <div className="modal__body">
              {importResult.error ? (
                <div style={{color:"var(--coral)",fontSize:13}}>{importResult.error}</div>
              ) : (
                <>
                  <div style={{fontSize:13,color:"var(--text)",marginBottom:8}}>
                    <b style={{color:"var(--accent)"}}>{importResult.count} hasta</b> bulundu. Sisteme eklensin mi?
                  </div>
                  {importResult.newClinics?.length > 0 && (
                    <div style={{marginBottom:10,padding:"8px 12px",background:"#FFF7ED",border:"1px solid #FED7AA",borderRadius:8,fontSize:12.5}}>
                      <span style={{color:"#C2410C",fontWeight:600}}>Yeni klinik{importResult.newClinics.length > 1 ? "ler" : ""} oluşturulacak: </span>
                      <span style={{color:"var(--ink)"}}>{importResult.newClinics.map(c => c.name).join(", ")}</span>
                    </div>
                  )}
                  <div style={{background:"var(--surface-2)",borderRadius:8,padding:"10px 12px",maxHeight:180,overflowY:"auto"}}>
                    {importResult.patients.map((p, i) => (
                      <div key={i} style={{fontSize:12.5,padding:"4px 0",borderBottom:"1px solid var(--line)",display:"flex",justifyContent:"space-between"}}>
                        <span style={{fontWeight:600,color:"var(--ink)"}}>{p.name}</span>
                        <span style={{color:"var(--text-mute)"}}>{p.treatment || "—"}</span>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
            <div className="modal__foot">
              <button className="btn btn--ghost" onClick={() => setImportResult(null)}>İptal</button>
              {!importResult.error && <button className="btn btn--accent" onClick={confirmImport}>Ekle</button>}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function PatientMoreMenu({ patient, onUpdate, onClose }) {
  const { ConfirmModal } = window.DentUI;
  const [confirmDel, setConfirmDel] = React.useState(false);

  React.useEffect(() => {
    const h = (e) => { if (!e.target.closest(".patient-more-menu") && !e.target.closest(".modal-overlay")) onClose(); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);

  const statuses = ["Devam ediyor", "Tamamlandı", "Bekliyor"];

  return (
    <>
      <div className="patient-more-menu profile-menu" style={{top:"calc(100% + 4px)", right:0, width:200}}>
        <div style={{padding:"6px 8px 4px", fontSize:11, fontWeight:700, color:"var(--text-mute)", textTransform:"uppercase", letterSpacing:"0.05em"}}>Durum Değiştir</div>
        {statuses.map(s => (
          <button key={s} className={`profile-menu__item ${patient.status===s?"is-active":""}`}
            style={patient.status===s?{color:"var(--accent)",fontWeight:600}:{}}
            onClick={() => { onUpdate({ status: s }); onClose(); }}>
            {patient.status === s && "✓ "}{s}
          </button>
        ))}
        <div className="profile-menu__divider"/>
        <button className="profile-menu__item" onClick={() => {
          const phone = patient.phone?.replace(/\s/g,"");
          if (phone) window.open(`tel:${phone}`);
          onClose();
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.62 3.38 2 2 0 0 1 3.6 1.22h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 8.85a16 16 0 0 0 5.35 5.35l1.11-.91a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7a2 2 0 0 1 1.72 2.02z"/></svg>
          Ara
        </button>
        <div className="profile-menu__divider"/>
        <button className="profile-menu__item" onClick={() => { onUpdate({ archived: !patient.archived }); onClose(); }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg>
          {patient.archived ? "Arşivden Çıkar" : "Arşivle"}
        </button>
        <div className="profile-menu__divider"/>
        <button className="profile-menu__item profile-menu__item--danger"
          onClick={() => setConfirmDel(true)}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
          Hastayı Sil
        </button>
      </div>
      {confirmDel && (
        <ConfirmModal
          title="Hastayı Sil"
          message={`"${patient.name}" kalıcı olarak silinecek. Bu işlem geri alınamaz.`}
          confirmLabel="Sil"
          danger
          onConfirm={() => { onUpdate({ _delete: true }); onClose(); }}
          onCancel={() => setConfirmDel(false)}
        />
      )}
    </>
  );
}

function PatientDetail({ patient, data, onUpdate, onClose, onOpenOdontogram, onAddEvents }) {
  const { Card, StatusPill, Avatar, fmtTRY, fmtDate, Tag } = window.DentUI;
  const I = window.DentIcons;
  const c = data.CLINICS.find(cc => cc.id === patient.clinicId);
  const [tab, setTab] = React.useState("plan");
  const [showMore, setShowMore] = React.useState(false);
  const [showOdontogram, setShowOdontogram] = React.useState(false);
  const [editingKronik, setEditingKronik] = React.useState(false);
  const [tempKronik, setTempKronik] = React.useState([]);
  const [tempDiger, setTempDiger] = React.useState("");
  const isMobile = window.innerWidth < 768;

  const openKronikEdit = () => {
    setTempKronik(patient.kronikHastaliklar || []);
    setTempDiger(patient.digerKronikHastalik || "");
    setEditingKronik(true);
  };
  const toggleTempKronik = (k) => setTempKronik(prev => prev.includes(k) ? prev.filter(x => x !== k) : [...prev, k]);
  const saveKronik = () => {
    onUpdate({ kronikHastaliklar: tempKronik, digerKronikHastalik: tempDiger.trim() });
    setEditingKronik(false);
  };

  const sessionShare = patient.plan.filter(s => s.status === "Tamamlandı").reduce((a,b) => a + b.share, 0);
  const totalShare = sessionShare > 0 ? sessionShare : Math.round(patient.paid * (c?.share || 50) / 100);
  const plannedShare = patient.plan.filter(s => s.status === "Planlandı").reduce((a,b) => a + b.share, 0);
  const pct = patient.totalFee ? Math.round((patient.paid / patient.totalFee) * 100) : 0;

  return (
    <aside className="patient-detail">
      <div className="pd__head">
        <button className="pd__back-btn" onClick={onClose}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="15 18 9 12 15 6"/></svg>
          Geri
        </button>
        <div className="pd__head-row">
          <Avatar name={patient.name} size={56} clinicColor={c.color}/>
          <div className="pd__head-main">
            <h2 className="pd__name">{patient.name}</h2>
            <div className="pd__meta">
              {patient.age} yaş · {patient.gender === "K" ? "Kadın" : "Erkek"} · <a href="#"><I.Phone size={11}/> {patient.phone}</a>
            </div>
            <div className="pd__head-tags">
              <StatusPill status={patient.status}/>
              <Tag color="neutral">
                <span className="clinic-bullet" style={{background:c.color, width:6,height:6}}/>
                {c.name}
              </Tag>
            </div>
            {!editingKronik ? (
              <div style={{marginTop:8,display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"}}>
                {(patient.kronikHastaliklar?.length > 0 || patient.digerKronikHastalik) && (
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#b91c1c" strokeWidth="2.2" strokeLinecap="round" style={{flexShrink:0}}><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
                )}
                {(patient.kronikHastaliklar || []).map(k => (
                  <span key={k} style={{display:"inline-flex",alignItems:"center",padding:"2px 7px",borderRadius:99,fontSize:11,fontWeight:600,background:"#fee2e2",color:"#b91c1c",border:"1px solid #fca5a5"}}>{k}</span>
                ))}
                {patient.digerKronikHastalik && (
                  <span style={{display:"inline-flex",alignItems:"center",padding:"2px 7px",borderRadius:99,fontSize:11,fontWeight:600,background:"#fee2e2",color:"#b91c1c",border:"1px solid #fca5a5"}}>{patient.digerKronikHastalik}</span>
                )}
                <button onClick={openKronikEdit} title="Kronik hastalıkları düzenle"
                  style={{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 7px",borderRadius:99,fontSize:11,fontWeight:600,background:"var(--surface-2)",color:"var(--text-mute)",border:"1px solid var(--line)",cursor:"pointer"}}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                  {(patient.kronikHastaliklar?.length > 0 || patient.digerKronikHastalik) ? "Düzenle" : "Kronik hastalık ekle"}
                </button>
              </div>
            ) : (
              <div style={{marginTop:10,background:"#fff5f5",border:"1px solid #fca5a5",borderRadius:10,padding:"12px 14px"}}>
                <div style={{fontSize:11,fontWeight:700,color:"#b91c1c",textTransform:"uppercase",letterSpacing:".04em",marginBottom:8}}>Kronik Hastalıklar</div>
                <div className="treat-chips" style={{marginBottom:10}}>
                  {CHRONIC_CONDITIONS.map(k => (
                    <button key={k} type="button"
                      className={`treat-chip ${tempKronik.includes(k) ? "is-on" : ""}`}
                      style={tempKronik.includes(k) ? {background:"#fee2e2",color:"#b91c1c",borderColor:"#fca5a5"} : {}}
                      onClick={() => toggleTempKronik(k)}>
                      {tempKronik.includes(k) && <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>}
                      {k}
                    </button>
                  ))}
                </div>
                <input value={tempDiger} onChange={e => setTempDiger(e.target.value)}
                  placeholder="Listede yoksa buraya yazın... (örn: Sedef hastalığı)"
                  style={{width:"100%",border:"1px solid #fca5a5",borderRadius:7,padding:"7px 10px",fontSize:12.5,fontFamily:"inherit",outline:"none",background:"#fff",color:"var(--ink)",marginBottom:10}}/>
                <div style={{display:"flex",gap:8}}>
                  <button className="btn btn--ghost btn--sm" onClick={() => setEditingKronik(false)}>İptal</button>
                  <button className="btn btn--sm" style={{background:"#b91c1c",color:"#fff"}} onClick={saveKronik}>Kaydet</button>
                </div>
              </div>
            )}
          </div>
          <div style={{position:"relative"}}>
            <button className="icon-btn" onClick={() => setShowMore(v => !v)}><I.More size={18}/></button>
            {showMore && <PatientMoreMenu patient={patient} onUpdate={onUpdate} onClose={() => setShowMore(false)}/>}
          </div>
        </div>

        <div className="pd__stats">
          <div className="pd-stat">
            <span className="pd-stat__l">Toplam tutar</span>
            <span className="pd-stat__v num">{fmtTRY(patient.totalFee)}</span>
          </div>
          <div className="pd-stat">
            <span className="pd-stat__l">Tahsil</span>
            <span className="pd-stat__v num" style={{color:"var(--mint)"}}>{fmtTRY(patient.paid)}</span>
          </div>
          <div className="pd-stat">
            <span className="pd-stat__l">Kalan</span>
            <span className="pd-stat__v num" style={{color: patient.balance > 0 ? "var(--coral)" : "var(--mint)"}}>
              {fmtTRY(patient.balance)}
            </span>
          </div>
          <div className="pd-stat">
            <span className="pd-stat__l">Hekim hakedişi</span>
            <span className="pd-stat__v num" style={{color:"var(--accent)"}}>{fmtTRY(totalShare)}</span>
          </div>
        </div>

        <div className="pd__progress">
          <div className="pd__progress-track">
            <div className="pd__progress-fill" style={{width:`${pct}%`}}/>
          </div>
          <span className="pd__progress-lbl">Ödeme ilerlemesi · %{pct}</span>
        </div>
      </div>

      <div className="pd__tabs">
        {[
          ["plan","Tedavi Planı"],
          ["sessions","Seans Geçmişi"],
          ["payments","Ödemeler"],
          ["odontogram","Odontogram"],
          ["notes","Notlar"],
          ["files","Belgeler"],
        ].map(([k, label]) => (
          <button key={k} className={`pd-tab ${tab===k?"is-on":""}`}
            onClick={() => {
              if (k === "odontogram") {
                isMobile ? setShowOdontogram(true) : (onOpenOdontogram && onOpenOdontogram());
              } else {
                setTab(k);
              }
            }}>{label}</button>
        ))}
      </div>

      <div className="pd__body">
        {tab === "plan" && <PlanTab patient={patient} clinic={c} data={data} onUpdate={onUpdate} onAddEvents={onAddEvents}/>}
        {tab === "sessions" && <SessionsTab patient={patient}/>}
        {tab === "payments" && <PaymentsTab patient={patient} clinic={c} onUpdate={onUpdate}/>}
        {tab === "notes" && <NotesTab patient={patient} onUpdate={onUpdate}/>}
        {tab === "files" && <FilesTab patient={patient} onUpdate={onUpdate}/>}
      </div>
      {isMobile && showOdontogram && <OdontogramModal patient={patient} onUpdate={onUpdate} onClose={() => setShowOdontogram(false)}/>}
    </aside>
  );
}

function ProcSelect({ procedures, value, onChange, required, autoFocus }) {
  const [open, setOpen] = React.useState(autoFocus || false);
  const ref = React.useRef();
  const display = value === "__custom__" ? "✏ Farklı işlem gir..." : value || "— Seçin —";
  const isEmpty = !value;

  React.useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const select = (v) => { onChange(v); setOpen(false); };

  return (
    <div ref={ref} style={{position:"relative"}}>
      <button type="button"
        style={{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",
          background:"var(--surface-2)",border:`1px solid ${open?"var(--accent)":"var(--line)"}`,
          borderRadius:"var(--radius)",padding:"9px 11px",fontSize:"13.5px",
          color:isEmpty?"var(--text-mute)":"var(--ink)",fontFamily:"inherit",cursor:"pointer",
          boxShadow:open?"0 0 0 3px color-mix(in oklch, var(--accent), transparent 88%)":"none",
          outline:"none",textAlign:"left",gap:8}}
        onClick={() => setOpen(v => !v)}>
        <span style={{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{display}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" style={{flexShrink:0,opacity:.5,transform:open?"rotate(180deg)":"none",transition:"transform .15s"}}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
      {open && (
        <div style={{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:999,
          background:"var(--surface)",border:"1px solid var(--line)",borderRadius:"var(--radius)",
          boxShadow:"var(--shadow-lg)",maxHeight:220,overflowY:"auto",padding:"4px 0"}}>
          {procedures.map(p => (
            <div key={p} onClick={() => select(p)}
              style={{padding:"9px 12px",fontSize:"13.5px",color:"var(--ink)",cursor:"pointer",
                background:value===p?"color-mix(in oklch, var(--accent), transparent 90%)":"transparent",
                fontWeight:value===p?600:400}}>
              {p}
            </div>
          ))}
          <div onClick={() => select("__custom__")}
            style={{padding:"9px 12px",fontSize:"13.5px",color:"var(--accent)",cursor:"pointer",
              borderTop:"1px solid var(--line)",marginTop:2,fontWeight:500}}>
            ✏ Farklı işlem gir...
          </div>
        </div>
      )}
    </div>
  );
}

function PlanTab({ patient, clinic, data, onUpdate, onAddEvents }) {
  const { fmtTRY, fmtDate, StatusPill, DatePicker } = window.DentUI;
  const I = window.DentIcons;
  const catalog = data.TREATMENTS_CATALOG || [];
  const procedures = catalog.map(c => c.name);
  const [showAdd, setShowAdd] = React.useState(false);
  const [form, setForm] = React.useState({ procedure: "", date: "", fee: "", status: "Planlandı", count: "1", interval: "14", category: patient.treatment || "" });
  const grouped = React.useMemo(() => {
    const g = {};
    (patient.plan || []).forEach(s => {
      const cat = s.category || patient.treatment || "Genel";
      if (!g[cat]) g[cat] = [];
      g[cat].push(s);
    });
    return g;
  }, [patient.plan, patient.treatment]);
  const [customProc, setCustomProc] = React.useState("");
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const handleProcedureChange = (name) => {
    const entry = catalog.find(c => c.name === name);
    setForm(f => ({ ...f, procedure: name, fee: entry?.baseFee != null ? String(entry.baseFee) : f.fee }));
  };
  const isCustom = form.procedure === "__custom__";
  const count = Math.max(1, Math.min(99, parseInt(form.count) || 1));
  const interval = Math.max(1, parseInt(form.interval) || 14);

  const toggleSessionStatus = (sessionId) => {
    const newPlan = patient.plan.map(s =>
      s.id === sessionId
        ? { ...s, status: s.status === "Tamamlandı" ? "Planlandı" : "Tamamlandı" }
        : s
    );
    onUpdate({ plan: newPlan });
  };

  const handleAdd = (e) => {
    e.preventDefault();
    const finalProc = isCustom ? customProc.trim() : form.procedure;
    if (!finalProc) return;
    const totalFee = parseFloat(form.fee) || 0;
    const totalShare = Math.round(totalFee * (clinic?.share || 50) / 100);
    const startDate = form.date ? new Date(form.date + "T00:00:00") : null;
    const newSessions = Array.from({ length: count }, (_, i) => {
      let sessionDate = "";
      if (startDate) {
        const d = new Date(startDate);
        d.setDate(d.getDate() + i * interval);
        sessionDate = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
      }
      return {
        id: "s" + Date.now() + "_" + i,
        session: patient.plan.length + 1 + i,
        date: sessionDate,
        procedure: finalProc,
        fee: i === 0 ? totalFee : 0,
        share: i === 0 ? totalShare : 0,
        status: form.status,
        category: form.category || patient.treatment || "Genel",
      };
    });
    const newPlan = [...patient.plan, ...newSessions];
    const newTotal = patient.totalFee + totalFee;
    onUpdate({ plan: newPlan, totalFee: newTotal, balance: newTotal - patient.paid });
    if (onAddEvents) {
      const newEvents = newSessions.filter(s => s.date).map(s => ({
        id: 'appt_' + s.id,
        date: s.date,
        startHour: 9,
        duration: 1,
        patientId: patient.id,
        clinicId: patient.clinicId,
        procedure: s.procedure,
        notes: '',
      }));
      if (newEvents.length) onAddEvents(newEvents);
    }
    setForm({ procedure: "", date: "", fee: "", status: "Planlandı", count: "1", interval: "14", category: patient.treatment || "" });
    setCustomProc("");
    setShowAdd(false);
  };

  return (
    <div className="plan">
      <div className="plan__head">
        <div>
          <h4 className="plan__title">Tedavi Planı</h4>
          <p className="plan__sub">{patient.plan.length} seans · {patient.plan.filter(s=>s.status==="Tamamlandı").length} tamamlandı</p>
        </div>
        <button className="btn btn--ghost btn--sm" onClick={() => setShowAdd(v => !v)}>
          <I.Plus size={13}/>{showAdd ? "İptal" : "Seans ekle"}
        </button>
      </div>

      {showAdd && (
        <form onSubmit={handleAdd} className="inline-form">
          <div className="form-field">
            <label>Kategori</label>
            <select value={form.category} onChange={e => set("category", e.target.value)}>
              <option value="">— Kategori seçin —</option>
              {TREATMENT_CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div className="form-field">
            <label>İşlem</label>
            <ProcSelect procedures={procedures} value={form.procedure} onChange={handleProcedureChange} required autoFocus/>
            {isCustom && (
              <input value={customProc} onChange={e => setCustomProc(e.target.value)}
                placeholder="İşlem adını yazın..." required autoFocus
                style={{background:"var(--surface-2)",border:"1px solid var(--accent)",borderRadius:"var(--radius)",padding:"9px 11px",fontSize:"13.5px",color:"var(--ink)",outline:"none",width:"100%",marginTop:6}}/>
            )}
          </div>
          <div className="form-row">
            <div className="form-field">
              <label>Başlangıç tarihi</label>
              <DatePicker value={form.date} onChange={v => set("date", v)}/>
            </div>
            <div className="form-field">
              <label>Toplam ücret (₺)</label>
              <input type="number" min="0" value={form.fee} onChange={e => set("fee", e.target.value)} placeholder="0"/>
            </div>
          </div>
          <div className="form-row">
            <div className="form-field">
              <label>Seans sayısı</label>
              <input type="number" min="1" max="99" value={form.count} onChange={e => set("count", e.target.value)} placeholder="1"/>
            </div>
            {count > 1 && (
              <div className="form-field">
                <label>Seans aralığı (gün)</label>
                <input type="number" min="1" value={form.interval} onChange={e => set("interval", e.target.value)} placeholder="14"/>
              </div>
            )}
          </div>
          {count > 1 && form.date && (
            <div className="plan-preview">
              <span>📅 {count} seans · her {interval} günde bir</span>
              <span className="muted">Son seans: {(() => { const d = new Date(form.date + "T00:00:00"); d.setDate(d.getDate() + (count-1)*interval); return d.toLocaleDateString("tr-TR"); })()}</span>
            </div>
          )}
          <div className="form-field">
            <label>Durum</label>
            <div className="radio-group">
              {["Planlandı","Tamamlandı"].map(s => (
                <button key={s} type="button" className={`radio-opt ${form.status===s?"is-on":""}`} onClick={() => set("status", s)}>{s}</button>
              ))}
            </div>
          </div>
          {form.fee > 0 && clinic && (
            <div style={{fontSize:12,color:"var(--text-mute)",padding:"4px 0"}}>
              Hakediş: <b style={{color:"var(--accent)"}}>₺{Math.round(parseFloat(form.fee||0) * clinic.share / 100).toLocaleString("tr-TR")}</b>
              <span className="muted"> (%{clinic.share} pay)</span>
            </div>
          )}
          <div style={{display:"flex",gap:8,justifyContent:"flex-end",marginTop:4}}>
            <button type="button" className="btn btn--ghost btn--sm" onClick={() => setShowAdd(false)}>İptal</button>
            <button type="submit" className="btn btn--accent btn--sm">
              {count > 1 ? `${count} Seans Ekle` : "Ekle"}
            </button>
          </div>
        </form>
      )}

      {patient.plan.length === 0 && <p style={{fontSize:13,color:"var(--text-mute)",padding:"12px 0"}}>Henüz seans eklenmedi.</p>}
      {Object.entries(grouped).map(([cat, sessions]) => (
        <div key={cat} style={{marginBottom:16}}>
          <div style={{display:"flex",alignItems:"center",gap:8,padding:"6px 0 4px",borderBottom:"1px solid var(--line)",marginBottom:8}}>
            <span style={{fontSize:13,fontWeight:700,color:"var(--ink)"}}>{cat}</span>
            <span style={{fontSize:12,color:"var(--text-mute)"}}>{sessions.length} seans · {sessions.filter(s=>s.status==="Tamamlandı").length} tamamlandı</span>
          </div>
          <ol className="timeline">
            {sessions.map((s) => (
              <li key={s.id} className={`tl-item tl-item--${s.status === "Tamamlandı" ? "done" : "planned"}`}>
                <div className="tl-dot"><span>{s.session}</span></div>
                <div className="tl-body">
                  <div className="tl-row">
                    <span className="tl-procedure">{s.procedure}</span>
                    <button type="button" className="tl-status-btn" title="Durumu değiştir" onClick={() => toggleSessionStatus(s.id)}>
                      <StatusPill status={s.status}/>
                    </button>
                  </div>
                  <div className="tl-meta">
                    <span><I.Calendar size={11}/> {fmtDate(s.date)}</span>
                    {s.fee > 0 && (
                      <>
                        <span className="muted">Ücret <b className="num">{fmtTRY(s.fee)}</b></span>
                        <span className="muted">Hakediş <b className="num" style={{color:"var(--accent)"}}>{fmtTRY(s.share)}</b></span>
                      </>
                    )}
                  </div>
                </div>
              </li>
            ))}
          </ol>
        </div>
      ))}
    </div>
  );
}

function SessionsTab({ patient }) {
  const { fmtTRY, fmtDate, StatusPill } = window.DentUI;
  const done = patient.plan.filter(s => s.status === "Tamamlandı");
  return (
    <div>
      <div className="ses-table">
        <div className="ses-row ses-row--head">
          <span>Seans</span>
          <span>Tarih</span>
          <span>İşlem</span>
          <span>Ücret</span>
          <span>Hakediş</span>
        </div>
        {done.map(s => (
          <div key={s.id} className="ses-row">
            <span>#{s.session}</span>
            <span className="muted">{fmtDate(s.date)}</span>
            <span>{s.procedure}</span>
            <span className="num">{fmtTRY(s.fee)}</span>
            <span className="num" style={{color:"var(--accent)"}}>{fmtTRY(s.share)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function PaymentsTab({ patient, clinic, onUpdate }) {
  const { fmtTRY, Tag, DatePicker } = window.DentUI;
  const [showAdd, setShowAdd] = React.useState(false);
  const [form, setForm] = React.useState({ date: "", amount: "", method: "Hasta → Klinik" });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const [editingIdx, setEditingIdx] = React.useState(null);
  const [editForm, setEditForm] = React.useState({});
  const setE = (k, v) => setEditForm(f => ({ ...f, [k]: v }));
  const payments = patient.payments || [];

  const recalc = (newPayments) => {
    const newPaid = newPayments.filter(p => p.status === "Tahsil edildi").reduce((a, p) => a + p.amount, 0);
    onUpdate({ payments: newPayments, paid: newPaid, balance: patient.totalFee - newPaid });
  };

  const handleAdd = (e) => {
    e.preventDefault();
    const amount = parseFloat(form.amount) || 0;
    const newPayments = [...payments, { date: form.date, amount, method: form.method, status: "Tahsil edildi" }];
    recalc(newPayments);
    setForm({ date: "", amount: "", method: "Hasta → Klinik" });
    setShowAdd(false);
  };

  const handleEditSave = (e) => {
    e.preventDefault();
    const newPayments = payments.map((p, i) =>
      i === editingIdx ? { ...p, date: editForm.date, amount: parseFloat(editForm.amount) || 0, method: editForm.method } : p
    );
    recalc(newPayments);
    setEditingIdx(null);
  };

  const handleDelete = (i) => {
    recalc(payments.filter((_, idx) => idx !== i));
    if (editingIdx === i) setEditingIdx(null);
  };

  return (
    <div>
      <div className="payments-summary" style={{gridTemplateColumns:"1fr 1fr 1fr"}}>
        <div className="pay-block">
          <span className="pay-l">Toplam tutar</span>
          <span className="pay-v num">{fmtTRY(patient.totalFee)}</span>
        </div>
        <div className="pay-block">
          <span className="pay-l">Tahsil edildi</span>
          <span className="pay-v num" style={{color:"var(--mint)"}}>{fmtTRY(patient.paid)}</span>
        </div>
        <div className="pay-block">
          <span className="pay-l">Kalan bakiye</span>
          <span className="pay-v num" style={{color: patient.balance > 0 ? "var(--coral)" : "var(--mint)"}}>
            {fmtTRY(patient.balance)}
          </span>
        </div>
      </div>
      <div className="pay-block" style={{marginBottom:12}}>
        <span className="pay-l">Hekim hakedişi (%{clinic.share})</span>
        <span className="pay-v num" style={{color:"var(--accent)"}}>
          {(() => {
            const fromSessions = patient.plan.filter(s=>s.status==="Tamamlandı").reduce((a,b)=>a+b.share,0);
            return fmtTRY(fromSessions > 0 ? fromSessions : Math.round(patient.paid * clinic.share / 100));
          })()}
        </span>
      </div>

      <div style={{display:"flex",justifyContent:"flex-end",marginBottom:10}}>
        <button className="btn btn--ghost btn--sm" onClick={() => setShowAdd(v => !v)}>
          + {showAdd ? "İptal" : "Ödeme ekle"}
        </button>
      </div>

      {showAdd && (
        <form onSubmit={handleAdd} className="inline-form" style={{marginBottom:12}}>
          <div className="form-row">
            <div className="form-field">
              <label>Tarih</label>
              <DatePicker value={form.date} onChange={v => set("date", v)} required/>
            </div>
            <div className="form-field">
              <label>Tutar (₺)</label>
              <input type="number" min="0" value={form.amount} onChange={e => set("amount", e.target.value)} placeholder="0" required/>
            </div>
          </div>
          <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>
            <button type="button" className="btn btn--ghost btn--sm" onClick={() => setShowAdd(false)}>İptal</button>
            <button type="submit" className="btn btn--accent btn--sm">Kaydet</button>
          </div>
        </form>
      )}

      <div className="ses-table">
        <div className="ses-row ses-row--head" style={{gridTemplateColumns:"90px 1fr 80px 100px 56px"}}>
          <span>Tarih</span><span>Yön</span><span>Tutar</span><span>Durum</span><span></span>
        </div>
        {payments.length === 0 && <p style={{fontSize:13,color:"var(--text-mute)",padding:"12px 0"}}>Henüz ödeme eklenmedi.</p>}
        {payments.map((p, i) => editingIdx === i ? (
          <form key={i} onSubmit={handleEditSave} style={{display:"grid",gridTemplateColumns:"90px 1fr 80px 100px 56px",gap:6,padding:"6px 0",borderBottom:"1px solid var(--line)",alignItems:"center"}}>
            <DatePicker value={editForm.date} onChange={v => setE("date", v)} required/>
            <input value={editForm.method} onChange={e => setE("method", e.target.value)} style={{fontSize:12,padding:"3px 5px",border:"1px solid var(--line)",borderRadius:5}}/>
            <input type="number" min="0" value={editForm.amount} onChange={e => setE("amount", e.target.value)} style={{fontSize:12,padding:"3px 5px",border:"1px solid var(--line)",borderRadius:5}} required/>
            <span style={{display:"flex",gap:4}}>
              <button type="submit" className="btn btn--accent btn--sm" style={{padding:"2px 8px",fontSize:11}}>Kaydet</button>
            </span>
            <button type="button" className="icon-btn" style={{color:"var(--text-mute)"}} onClick={() => setEditingIdx(null)}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </form>
        ) : (
          <div key={i} className="ses-row" style={{gridTemplateColumns:"90px 1fr 80px 100px 56px"}}>
            <span className="muted">{p.date}</span>
            <span>{p.method}</span>
            <span className="num">{fmtTRY(p.amount)}</span>
            <span><Tag color={p.status === "Tahsil edildi" ? "green" : "amber"} dot>{p.status}</Tag></span>
            <span style={{display:"flex",gap:2}}>
              <button className="icon-btn" title="Düzenle" onClick={() => { setEditingIdx(i); setEditForm({ date: p.date, amount: String(p.amount), method: p.method }); }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
              </button>
              <button className="icon-btn" title="Sil" style={{color:"var(--coral)"}} onClick={() => handleDelete(i)}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
              </button>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function NotesTab({ patient, onUpdate }) {
  const [text, setText] = React.useState(patient.notes || "");
  const [dirty, setDirty] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  React.useEffect(() => {
    if (!dirty) setText(patient.notes || "");
  }, [patient.notes]);

  const handleChange = (val) => { setText(val); setDirty(true); setSaved(false); };

  const handleSave = () => {
    onUpdate({ notes: text });
    setDirty(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const handleTranscript = React.useCallback((t) => {
    setText(prev => prev ? prev + t : t);
    setDirty(true);
  }, []);

  return (
    <div className="notes">
      <textarea className="note-input" style={{minHeight:260}} value={text} onChange={e => handleChange(e.target.value)} placeholder="Notlar buraya yazılır. Odontogramdan yapılan işlemler otomatik eklenir..."/>
      <div className="note-actions">
        <VoiceButton onTranscript={handleTranscript}/>
        <div style={{display:'flex',alignItems:'center',gap:8,marginLeft:'auto'}}>
          {saved && <span style={{fontSize:12,color:"var(--mint)"}}>Kaydedildi</span>}
          <button className="btn btn--accent btn--sm" onClick={handleSave} disabled={!dirty}>Kaydet</button>
        </div>
      </div>
    </div>
  );
}

function FilesTab({ patient, onUpdate }) {
  const I = window.DentIcons;
  const [dragging, setDragging] = React.useState(false);
  const [preview, setPreview] = React.useState(null);
  const inputRef = React.useRef();
  const files = patient.files || [];

  const getType = (name) => {
    const ext = name.split(".").pop().toLowerCase();
    if (["jpg","jpeg","png","gif","webp"].includes(ext)) return "img";
    if (ext === "pdf") return "pdf";
    if (["xls","xlsx","csv"].includes(ext)) return "xls";
    if (["dcm","dicom"].includes(ext)) return "dcm";
    return "other";
  };

  const typeColor = { img: "#5B8DEF", dcm: "#A78BFA", pdf: "#EC6F8E", xls: "#3FB893", other: "#94A3B8" };

  const fmtSize = (bytes) => {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + " KB";
    return (bytes / (1024 * 1024)).toFixed(1) + " MB";
  };

  const fmtDate = (ts) => {
    const d = new Date(ts);
    const months = ["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"];
    return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
  };

  const addFiles = (fileList) => {
    const newFiles = Array.from(fileList).map(f => ({
      id: Date.now() + Math.random(),
      name: f.name,
      size: f.size,
      date: Date.now(),
      type: getType(f.name),
      url: URL.createObjectURL(f),
    }));
    onUpdate({ files: [...files, ...newFiles] });
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    if (e.dataTransfer.files.length) addFiles(e.dataTransfer.files);
  };

  const handleRemove = (id) => {
    if (preview?.id === id) setPreview(null);
    onUpdate({ files: files.filter(f => f.id !== id) });
  };

  const openFile = (f) => {
    if (!f.url) return;
    if (f.type === "img" || f.type === "pdf") {
      setPreview(f);
    } else {
      window.open(f.url, "_blank");
    }
  };

  const previewIdx = preview ? files.findIndex(f => f.id === preview.id) : -1;
  const previewableFiles = files.filter(f => f.type === "img" || f.type === "pdf");

  const navPreview = (dir) => {
    const cur = previewableFiles.findIndex(f => f.id === preview.id);
    const next = previewableFiles[cur + dir];
    if (next) setPreview(next);
  };

  return (
    <div className="files">
      {files.map((f) => (
        <div key={f.id} className="file" onClick={() => openFile(f)} style={{cursor: f.url ? "pointer" : "default"}}>
          <div className="file__icon" style={{background: (typeColor[f.type] || typeColor.other) + "22", color: typeColor[f.type] || typeColor.other}}>
            {f.type === "img" && f.url
              ? <img src={f.url} alt="" style={{width:36,height:36,objectFit:"cover",borderRadius:6}}/>
              : <I.Document size={20}/>
            }
          </div>
          <div className="file__main">
            <div className="file__name">{f.name}</div>
            <div className="file__meta muted">{fmtSize(f.size)} · {fmtDate(f.date)}</div>
          </div>
          {f.url && (
            <a href={f.url} download={f.name} className="icon-btn" title="İndir"
              onClick={e => e.stopPropagation()}>
              <I.Export size={16}/>
            </a>
          )}
          <button className="icon-btn" title="Sil"
            onClick={e => { e.stopPropagation(); handleRemove(f.id); }}
            style={{color:"var(--coral)"}}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/></svg>
          </button>
        </div>
      ))}

      <div
        className={`file-upload ${dragging ? "is-dragging" : ""}`}
        onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
        onDragLeave={() => setDragging(false)}
        onDrop={handleDrop}
        onClick={() => inputRef.current.click()}
      >
        <I.Plus size={20}/>
        <span>{dragging ? "Bırakın..." : "Dosya yükle veya buraya sürükle"}</span>
        <input ref={inputRef} type="file" multiple style={{display:"none"}}
          onChange={(e) => { if (e.target.files.length) addFiles(e.target.files); e.target.value=""; }}/>
      </div>

      {preview && (
        <div className="file-preview-overlay" onClick={() => setPreview(null)}>
          <div className="file-preview-box" onClick={e => e.stopPropagation()}>
            <div className="file-preview-head">
              <span className="file-preview-name">{preview.name}</span>
              <div style={{display:"flex",gap:8}}>
                <a href={preview.url} download={preview.name} className="btn btn--ghost btn--sm">
                  <I.Export size={14}/> İndir
                </a>
                <button className="icon-btn" onClick={() => setPreview(null)}>
                  <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>
            </div>
            <div className="file-preview-body">
              {preview.type === "img" && <img src={preview.url} alt={preview.name} className="file-preview-img"/>}
              {preview.type === "pdf" && <iframe src={preview.url} className="file-preview-pdf" title={preview.name}/>}
            </div>
            {previewableFiles.length > 1 && (
              <div className="file-preview-nav">
                <button className="btn btn--ghost btn--sm" onClick={() => navPreview(-1)}
                  disabled={previewableFiles.findIndex(f=>f.id===preview.id) === 0}>← Önceki</button>
                <span style={{fontSize:12,color:"var(--text-mute)"}}>
                  {previewableFiles.findIndex(f=>f.id===preview.id)+1} / {previewableFiles.length}
                </span>
                <button className="btn btn--ghost btn--sm" onClick={() => navPreview(1)}
                  disabled={previewableFiles.findIndex(f=>f.id===preview.id) === previewableFiles.length-1}>Sonraki →</button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

window.DentPatients = Patients;
