﻿// Patients list + detail panel

function Patients({ data, selectedPatient, setSelectedPatient, filter, setFilter, onNewPatient, onUpdatePatient, onImportPatients }) {
  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 [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 findC = (id) => data.CLINICS.find(c => c.id === id);

  const handleDownloadTemplate = () => {
    const XLSX = window.XLSX;
    const clinicNames = data.CLINICS.map(c => c.name).join(" / ");
    const rows = [
      ["Ad Soyad *", "Yaş", "Cinsiyet (K/E) *", "Telefon", `Klinik * (${clinicNames})`, "Tedavi", "Durum", "Toplam Tutar (₺)", "Tahsil Edilen (₺)", "Notlar"],
      ["Örnek: Ayşe Yılmaz", "35", "K", "+90 532 000 00 00", data.CLINICS[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 CLINIC_COLORS = ["#3B82F6","#8B5CF6","#10B981","#F59E0B","#EF4444","#06B6D4","#EC4899","#84CC16"];
        const newClinicsMap = {};
        dataRows.forEach(r => {
          const clinicName = String(r[4] || "").trim();
          if (!clinicName) return;
          const exists = data.CLINICS.find(c => c.name.toLowerCase() === clinicName.toLowerCase());
          if (!exists && !newClinicsMap[clinicName.toLowerCase()]) {
            const colorIdx = (Object.keys(newClinicsMap).length + data.CLINICS.length) % CLINIC_COLORS.length;
            newClinicsMap[clinicName.toLowerCase()] = {
              id: "clinic_imp_" + Date.now() + "_" + Object.keys(newClinicsMap).length,
              name: clinicName,
              color: CLINIC_COLORS[colorIdx],
              share: 50,
              contract: "Standart",
              city: "",
            };
          }
        });
        const newClinics = Object.values(newClinicsMap);
        const allClinics = [...data.CLINICS, ...newClinics];

        const imported = dataRows.map((r, i) => {
          const clinicName = String(r[4] || "").trim();
          const clinic = allClinics.find(c => c.name.toLowerCase() === clinicName.toLowerCase()) || allClinics[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(),
            clinicId: clinic.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;
  if (clinicFilter !== "all") patients = patients.filter(p => p.clinicId === clinicFilter);
  if (statusFilter !== "all") patients = patients.filter(p => p.status === statusFilter);
  if (filter) patients = patients.filter(p => p.name.toLowerCase().includes(filter.toLowerCase()));

  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">Hastalar</h1>
            <p className="page-sub">{patients.length} hasta · {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>
            <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 ${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 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.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).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"}}>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.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>
                  <svg className={`pt-chevron${isSel?" is-open":""}`} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="9 18 15 12 9 6"/></svg>
                </button>
              );
            })}
          </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)}/>
          </div>
        </div>
      )}
      {!isMobile && selP && <PatientDetail key={selP.id} patient={selP} data={data} onClose={() => setSelectedPatient(null)} onUpdate={(updates) => onUpdatePatient(selP.id, updates)}/>}

      {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 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 }) {
  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 isMobile = window.innerWidth < 768;

  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>
          </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" style={isMobile ? {display:"flex",flexWrap:"wrap",justifyContent:"center",overflowX:"visible",padding:"0 8px"} : {}}>
        {[
          ["plan","Tedavi Planı"],
          ["sessions","Seans Geçmişi"],
          ["payments","Ödemeler"],
          ["notes","Notlar"],
          ["files","Belgeler"],
        ].map(([k, label]) => (
          <button key={k} className={`pd-tab ${tab===k?"is-on":""}`}
            style={isMobile ? {flex:"0 0 33.333%",textAlign:"center",padding:"10px 4px",fontSize:"11.5px",boxSizing:"border-box"} : {}}
            onClick={()=>setTab(k)}>{label}</button>
        ))}
      </div>

      <div className="pd__body">
        {tab === "plan" && <PlanTab patient={patient} clinic={c} data={data} onUpdate={onUpdate}/>}
        {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>
    </aside>
  );
}

function PlanTab({ patient, clinic, data, onUpdate }) {
  const { fmtTRY, fmtDate, StatusPill } = 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" });
  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.toISOString().slice(0, 10);
      }
      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,
      };
    });
    const newPlan = [...patient.plan, ...newSessions];
    const newTotal = patient.totalFee + totalFee;
    onUpdate({ plan: newPlan, totalFee: newTotal, balance: newTotal - patient.paid });
    setForm({ procedure: "", date: "", fee: "", status: "Planlandı", count: "1", interval: "14" });
    setCustomProc("");
    setShowAdd(false);
  };

  return (
    <div className="plan">
      <div className="plan__head">
        <div>
          <h4 className="plan__title">{patient.treatment || "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>İşlem</label>
            <select value={form.procedure} onChange={e => handleProcedureChange(e.target.value)} required autoFocus>
              <option value="">— Seçin —</option>
              {procedures.map(p => <option key={p} value={p}>{p}</option>)}
              <option value="__custom__">✏ Farklı işlem gir...</option>
            </select>
            {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>
              <input type="date" value={form.date} onChange={e => set("date", e.target.value)}/>
            </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>
      )}

      <ol className="timeline">
        {patient.plan.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>
        ))}
        {patient.plan.length === 0 && <p style={{fontSize:13,color:"var(--text-mute)",padding:"12px 0"}}>Henüz seans eklenmedi.</p>}
      </ol>
    </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 } = 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>
              <input type="date" value={form.date} onChange={e => set("date", e.target.value)} 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"}}>
            <input type="date" value={editForm.date} onChange={e => setE("date", e.target.value)} style={{fontSize:12,padding:"3px 5px",border:"1px solid var(--line)",borderRadius:5}} 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 I = window.DentIcons;
  const [newNote, setNewNote] = React.useState("");
  const [saved, setSaved] = React.useState(false);

  const getDoc = () => {
    try { return JSON.parse(localStorage.getItem("df_profile_" + (window._dentUser?.id || ""))) || {}; } catch(e) { return {}; }
  };
  const doc = getDoc();
  const docName = doc.name || window._dentUser?.user_metadata?.full_name || "Dr. Mehmet Aydın";
  const docInitials = docName.split(" ").filter(Boolean).map(w => w[0]).slice(0, 2).join("").toUpperCase() || "DR";

  const handleSave = () => {
    if (!newNote.trim()) return;
    const existing = patient.notes ? patient.notes + "\n\n" : "";
    onUpdate({ notes: existing + newNote.trim() });
    setNewNote("");
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return (
    <div className="notes">
      {patient.notes && (
        <div className="note">
          <div className="note__head">
            <div className="note__author">
              <div className="avatar avatar--xs" style={{background:"linear-gradient(135deg, var(--accent), var(--accent-2))"}}>{docInitials}</div>
              <span>{docName}</span>
            </div>
          </div>
          <p style={{whiteSpace:"pre-wrap"}}>{patient.notes}</p>
        </div>
      )}
      <textarea className="note-input" value={newNote} onChange={e => setNewNote(e.target.value)} placeholder="Yeni not yaz..."/>
      <div className="note-actions">
        {saved && <span style={{fontSize:12,color:"var(--mint)"}}>Kaydedildi</span>}
        <button className="btn btn--accent btn--sm" onClick={handleSave} disabled={!newNote.trim()}>Kaydet</button>
      </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;
