// ──── SCHEDULE ────

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",
];

function NewApptModal({ data, onSave, onClose, defaultDate }) {
  const allProcs = (data.TREATMENTS_CATALOG || []).map(c => c.name);

  const [patientMode, setPatientMode] = React.useState("existing");
  const [selectedCategories, setSelectedCategories] = React.useState([]);
  const toggleCat = (cat) => setSelectedCategories(prev => prev.includes(cat) ? prev.filter(c => c !== cat) : [...prev, cat]);
  const [form, setForm] = React.useState({
    patientId: data.PATIENTS[0]?.id || "",
    newPatientName: "",
    newPatientPhone: "",
    newPatientAge: "",
    newPatientGender: "K",
    clinicId: data.CLINICS[0]?.id || "",
    procedure: "",
    date: defaultDate || new Date().toISOString().slice(0, 10),
    startHour: 9,
    startMin: 0,
    duration: "1",
    notes: "",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = (e) => {
    e.preventDefault();
    const isNew = patientMode === "new";
    if (isNew && !form.newPatientName.trim()) return;
    if (!isNew && !form.patientId) return;
    if (!form.clinicId) return;
    onSave({
      id: "appt_" + Date.now(),
      date: form.date,
      startHour: parseFloat(form.startHour) + parseFloat(form.startMin) / 60,
      duration: parseFloat(form.duration),
      patientId: isNew ? null : form.patientId,
      newPatient: isNew ? { name: form.newPatientName.trim(), phone: form.newPatientPhone, age: parseInt(form.newPatientAge)||0, gender: form.newPatientGender, treatment: selectedCategories.join(", ") } : null,
      clinicId: form.clinicId,
      procedure: form.procedure,
      categories: selectedCategories,
      notes: form.notes,
    });
  };

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{maxWidth:440}}>
        <div className="modal__head">
          <span className="modal__title">Yeni Randevu</span>
          <button className="icon-btn" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal__body">
            <div className="form-field">
              <label>Hasta *</label>
              <div className="radio-group" style={{marginBottom:8}}>
                <button type="button" className={`radio-opt ${patientMode==="existing"?"is-on":""}`} onClick={() => setPatientMode("existing")}>Kayıtlı hasta</button>
                <button type="button" className={`radio-opt ${patientMode==="new"?"is-on":""}`} onClick={() => setPatientMode("new")}>Yeni Hasta</button>
              </div>
              {patientMode === "existing" ? (
                <select value={form.patientId} onChange={e => set("patientId", e.target.value)} required autoFocus>
                  {data.PATIENTS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              ) : (
                <div style={{display:"flex",flexDirection:"column",gap:8}}>
                  <input value={form.newPatientName} onChange={e=>set("newPatientName",e.target.value)} placeholder="Ad Soyad *" required autoFocus/>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                    <input value={form.newPatientPhone} onChange={e=>set("newPatientPhone",e.target.value)} placeholder="Telefon"/>
                    <input type="number" min="1" max="120" value={form.newPatientAge} onChange={e=>set("newPatientAge",e.target.value)} placeholder="Yaş"/>
                  </div>
                  <div className="radio-group">
                    <button type="button" className={`radio-opt ${form.newPatientGender==="K"?"is-on":""}`} onClick={()=>set("newPatientGender","K")}>Kadın</button>
                    <button type="button" className={`radio-opt ${form.newPatientGender==="E"?"is-on":""}`} onClick={()=>set("newPatientGender","E")}>Erkek</button>
                  </div>
                </div>
              )}
            </div>
            <div className="form-field">
              <label>Tedavi Kategorisi <span style={{color:"var(--text-mute)",fontWeight:400}}>(çoklu)</span></label>
              <div className="treat-chips">
                {TREATMENT_CATEGORIES.map(cat => (
                  <button key={cat} type="button" className={`treat-chip ${selectedCategories.includes(cat)?"is-on":""}`} onClick={()=>toggleCat(cat)}>
                    {selectedCategories.includes(cat) && <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="2,6 5,9 10,3"/></svg>}
                    {cat}
                  </button>
                ))}
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Klinik *</label>
                <select value={form.clinicId} onChange={e => set("clinicId", e.target.value)} required>
                  {data.CLINICS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <div className="form-field">
                <label>İşlem</label>
                <select value={form.procedure} onChange={e => set("procedure", e.target.value)}>
                  <option value="">— Seçin —</option>
                  {allProcs.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
            </div>
            <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>Saat</label>
                <div style={{display:"flex",gap:6}}>
                  <select value={form.startHour} onChange={e => set("startHour", e.target.value)} style={{flex:1}}>
                    {[8,9,10,11,12,13,14,15,16,17,18].map(h => <option key={h} value={h}>{String(h).padStart(2,"0")}:00</option>)}
                  </select>
                  <select value={form.startMin} onChange={e => set("startMin", e.target.value)} style={{width:72}}>
                    <option value={0}>:00</option>
                    <option value={30}>:30</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="form-field">
              <label>Süre</label>
              <div className="radio-group">
                {[["0.5","30 dk"],["1","1 saat"],["1.5","1.5 saat"],["2","2 saat"]].map(([v,l]) => (
                  <button key={v} type="button" className={`radio-opt ${form.duration===v?"is-on":""}`} onClick={() => set("duration", v)}>{l}</button>
                ))}
              </div>
            </div>
            <div className="form-field">
              <label>Not</label>
              <textarea value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Randevu notu..." style={{minHeight:52}}/>
            </div>
          </div>
          <div className="modal__foot">
            <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
            <button type="submit" className="btn btn--accent">Randevu Ekle</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function EventDetailModal({ event, patient, clinic, onClose, onGoToPatient, onDelete }) {
  const fmtH = (h) => `${String(Math.floor(h)).padStart(2,"0")}:${String(Math.round((h%1)*60)).padStart(2,"0")}`;
  const MO = ["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"];
  const fmtDate = (ds) => { const [y,m,d] = ds.split("-"); return `${parseInt(d)} ${MO[parseInt(m)-1]} ${y}`; };
  const rawPhone = (patient.phone || "").replace(/\D/g,"");
  const waPhone = rawPhone ? (rawPhone.startsWith("90") ? rawPhone : "90" + rawPhone.replace(/^0/,"")) : "";
  const waMsg = waPhone
    ? encodeURIComponent(`Sayın ${patient.name}, ${fmtDate(event.date)} tarihinde saat ${fmtH(event.startHour)}'deki randevunuzu hatırlatmak istedik. Herhangi bir değişiklik için lütfen bizimle iletişime geçin.`)
    : "";

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{maxWidth:340}}>
        <div className="modal__head" style={{borderBottom:`3px solid ${clinic.color}`}}>
          <span className="modal__title">{event.procedure}</span>
          <button className="icon-btn" onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div className="modal__body" style={{gap:10}}>
          <div style={{display:"flex",flexDirection:"column",gap:8,fontSize:13}}>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <div className="avatar avatar--xs" style={{background: `linear-gradient(135deg,${clinic.color},${clinic.color}aa)`}}>
                {patient.name.split(" ").map(s=>s[0]).slice(0,2).join("")}
              </div>
              <div>
                <div style={{fontWeight:600,color:"var(--ink)"}}>{patient.name}</div>
                {patient.id && (
                  <div style={{fontSize:12,color:"var(--text-mute)"}}>{patient.age} yaş · {patient.gender==="K"?"Kadın":"Erkek"}</div>
                )}
                {!patient.id && (
                  <div style={{fontSize:12,color:"var(--text-mute)"}}>Yeni hasta · Kayıt yok</div>
                )}
              </div>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,padding:"10px 0",borderTop:"1px solid var(--line)",borderBottom:"1px solid var(--line)"}}>
              <div>
                <div style={{fontSize:11,color:"var(--text-mute)",marginBottom:2}}>Tarih</div>
                <div style={{fontWeight:600}}>{event.date}</div>
              </div>
              <div>
                <div style={{fontSize:11,color:"var(--text-mute)",marginBottom:2}}>Saat</div>
                <div style={{fontWeight:600,fontFamily:"monospace"}}>{fmtH(event.startHour)} – {fmtH(event.startHour+event.duration)}</div>
              </div>
              <div>
                <div style={{fontSize:11,color:"var(--text-mute)",marginBottom:2}}>Klinik</div>
                <div style={{display:"flex",alignItems:"center",gap:5}}>
                  <span style={{width:8,height:8,borderRadius:"50%",background:clinic.color,display:"inline-block"}}/>
                  <span style={{fontWeight:600}}>{clinic.name}</span>
                </div>
              </div>
              <div>
                <div style={{fontSize:11,color:"var(--text-mute)",marginBottom:2}}>Süre</div>
                <div style={{fontWeight:600}}>{event.duration >= 1 ? event.duration + " saat" : (event.duration * 60) + " dk"}</div>
              </div>
            </div>
            {event.notes && <div style={{fontSize:12.5,color:"var(--text)",background:"var(--surface-2)",borderRadius:8,padding:"8px 10px"}}>{event.notes}</div>}
            {!event.patientId && (
              <div style={{fontSize:12,color:"var(--text-mute)",background:"var(--surface-2)",borderRadius:8,padding:"6px 10px",display:"flex",alignItems:"center",gap:6}}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                Sistem kaydı yok · Randevu sonrası eklenebilir
              </div>
            )}
            {waPhone && (
              <a href={`https://wa.me/${waPhone}?text=${waMsg}`} target="_blank" rel="noopener noreferrer"
                style={{display:"flex",alignItems:"center",gap:8,padding:"9px 12px",borderRadius:10,background:"#dcfce7",color:"#15803d",fontWeight:600,fontSize:13,textDecoration:"none",border:"1px solid #bbf7d0"}}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
                WhatsApp ile Hatırlatma Gönder
              </a>
            )}
          </div>
        </div>
        <div className="modal__foot" style={{justifyContent:"space-between"}}>
          <button className="btn btn--ghost btn--sm" style={{color:"var(--coral)"}} onClick={onDelete}>Sil</button>
          {event.patientId && <button className="btn btn--accent" onClick={onGoToPatient}>Hastaya Git</button>}
          {!event.patientId && <button className="btn btn--ghost" onClick={onClose}>Kapat</button>}
        </div>
      </div>
    </div>
  );
}

function Schedule({ data, events, onUpdateEvents, setSelectedPatient, onNav, onAddPatient, onUpdatePatient }) {
  const { Card, DatePicker } = window.DentUI;
  const I = window.DentIcons;
  const TODAY = new Date().toISOString().slice(0, 10);
  const HOURS = [8,9,10,11,12,13,14,15,16,17,18];
  const SLOT_H = 56;
  const DAY_NAMES = ["Pzt","Sal","Çar","Per","Cum","Cmt","Paz"];
  const MONTHS = ["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"];

  const isMob = window.innerWidth < 768;
  const [calView, setCalView] = React.useState(isMob ? "ay" : "hafta");
  const [currentDate, setCurrentDate] = React.useState(new Date());
  const [selectedEvent, setSelectedEvent] = React.useState(null);
  const [selectedDay, setSelectedDay] = React.useState(null);
  const [showNewAppt, setShowNewAppt] = React.useState(false);
  const [newApptDate, setNewApptDate] = React.useState(null);
  const LONG_DAYS = ["Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi","Pazar"];

  const findP = (id) => data.PATIENTS.find(p => p.id === id);
  const findC = (id) => data.CLINICS.find(c => c.id === id);
  const getEvPatient = (ev) => ev.patientId ? findP(ev.patientId) : (ev.patientName ? { name: ev.patientName, age: null, gender: null, id: null } : null);

  const toDateStr = (d) => {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${dd}`;
  };

  const dayIdx = (d) => d.getDay() === 0 ? 6 : d.getDay() - 1;

  const getWeekDays = (date) => {
    const d = new Date(date.getTime());
    d.setDate(d.getDate() - dayIdx(d));
    return Array.from({length:7}, (_, i) => { const dd = new Date(d); dd.setDate(d.getDate()+i); return dd; });
  };

  const getThreeDays = (date) => Array.from({length:3}, (_, i) => {
    const d = new Date(date); d.setDate(d.getDate() - 1 + i); return d;
  });

  const getMonthDays = (date) => {
    const y = date.getFullYear(), m = date.getMonth();
    const first = new Date(y, m, 1), last = new Date(y, m+1, 0);
    const startOff = first.getDay() === 0 ? 6 : first.getDay() - 1;
    const endOff = last.getDay() === 0 ? 0 : 7 - last.getDay();
    const days = [];
    for (let i = 1-startOff; i <= last.getDate()+endOff; i++) days.push(new Date(y, m, i));
    return days;
  };

  const navigate = (dir) => {
    const d = new Date(currentDate.getTime());
    if (isMob || calView === "ay") d.setMonth(d.getMonth() + dir);
    else if (calView === "gun") d.setDate(d.getDate() + dir);
    else d.setDate(d.getDate() + dir * 7);
    setCurrentDate(d);
    setSelectedDay(null);
    setSelectedEvent(null);
  };

  const fmtH = (h) => `${String(Math.floor(h)).padStart(2,"0")}:${String(Math.round((h%1)*60)).padStart(2,"0")}`;

  const getHeaderLabel = () => {
    if (calView === "gun") {
      const names = ["Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi","Pazar"];
      return `${names[dayIdx(currentDate)]}, ${currentDate.getDate()} ${MONTHS[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
    }
    if (calView === "hafta") {
      const w = getWeekDays(currentDate);
      const s = w[0], e = w[6];
      return s.getMonth() === e.getMonth()
        ? `${s.getDate()} – ${e.getDate()} ${MONTHS[s.getMonth()]} ${s.getFullYear()}`
        : `${s.getDate()} ${MONTHS[s.getMonth()]} – ${e.getDate()} ${MONTHS[e.getMonth()]} ${s.getFullYear()}`;
    }
    return `${MONTHS[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
  };

  const renderEvents = (dateStr, slotH, hourStart) => {
    return events.filter(ev => ev.date === dateStr).map(ev => {
      const p = getEvPatient(ev);
      const c = findC(ev.clinicId);
      if (!p || !c) return null;
      const top = (ev.startHour - hourStart) * slotH + 4;
      const height = Math.max(ev.duration * slotH - 4, 20);
      return (
        <button key={ev.id} className="cal-event"
          style={{ top, height, background: c.color+"1A", borderLeft:`3px solid ${c.color}`, zIndex: selectedEvent?.id===ev.id ? 3 : 1 }}
          onClick={(e) => { e.stopPropagation(); setSelectedEvent(selectedEvent?.id===ev.id ? null : ev); }}>
          <div className="cal-event__time">{fmtH(ev.startHour)}</div>
          <div className="cal-event__patient">{p.name}</div>
          <div className="cal-event__procedure">{ev.procedure}</div>
        </button>
      );
    });
  };

  const renderWeekView = () => {
    const isMob = window.innerWidth < 768;
    const weekDays = isMob ? getThreeDays(currentDate) : getWeekDays(currentDate);
    const gridStyle = isMob ? { gridTemplateColumns: `44px repeat(3, 1fr)` } : {};
    return (
      <Card padding={0}>
        <div className="cal-grid-scroll">
        <div className="cal-grid" style={gridStyle}>
          <div className="cal-hour-col">
            <div className="cal-day-head"/>
            {HOURS.map(h => <div key={h} className="cal-hour">{h}:00</div>)}
          </div>
          {weekDays.map(d => {
            const dStr = toDateStr(d);
            const isToday = dStr === TODAY;
            return (
              <div key={dStr} className={`cal-day ${isToday?"is-today":""}`}>
                <div className="cal-day-head">
                  <span className="cal-day__name">{DAY_NAMES[dayIdx(d)]}</span>
                  <span className={`cal-day__date ${isToday?"is-today":""}`}>{d.getDate()}</span>
                </div>
                <div className="cal-day-body" style={{height: HOURS.length * SLOT_H}}>
                  {HOURS.map(h => <div key={h} className="cal-slot"/>)}
                  {renderEvents(dStr, SLOT_H, HOURS[0])}
                </div>
              </div>
            );
          })}
        </div>
        </div>
      </Card>
    );
  };

  const renderDayView = () => {
    const dStr = toDateStr(currentDate);
    const isToday = dStr === TODAY;
    const SH = 72;
    return (
      <Card padding={0}>
        <div className="cal-grid" style={{gridTemplateColumns:"56px 1fr"}}>
          <div className="cal-hour-col">
            <div className="cal-day-head"/>
            {HOURS.map(h => <div key={h} className="cal-hour" style={{height:SH}}>{h}:00</div>)}
          </div>
          <div className={`cal-day ${isToday?"is-today":""}`}>
            <div className="cal-day-head" style={{justifyContent:"flex-start",flexDirection:"row",alignItems:"center",gap:10}}>
              <span className="cal-day__name">{["Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi","Pazar"][dayIdx(currentDate)]}</span>
              <span className={`cal-day__date ${isToday?"is-today":""}`}>{currentDate.getDate()}</span>
            </div>
            <div className="cal-day-body" style={{height: HOURS.length * SH}}>
              {HOURS.map(h => <div key={h} className="cal-slot" style={{height:SH}}/>)}
              {events.filter(ev => ev.date === dStr).map(ev => {
                const p = getEvPatient(ev);
                const c = findC(ev.clinicId);
                if (!p || !c) return null;
                const top = (ev.startHour - HOURS[0]) * SH + 4;
                const height = Math.max(ev.duration * SH - 4, 28);
                return (
                  <button key={ev.id} className="cal-event"
                    style={{ top, height, background: c.color+"1A", borderLeft:`3px solid ${c.color}` }}
                    onClick={(e) => { e.stopPropagation(); setSelectedEvent(selectedEvent?.id===ev.id ? null : ev); }}>
                    <div className="cal-event__time">{fmtH(ev.startHour)} – {fmtH(ev.startHour+ev.duration)}</div>
                    <div className="cal-event__patient">{p.name}</div>
                    <div className="cal-event__procedure">{ev.procedure}</div>
                    {ev.notes && <div style={{fontSize:11,color:"var(--text-mute)",marginTop:2,opacity:.8}}>{ev.notes}</div>}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </Card>
    );
  };

  const renderMonthView = () => {
    const monthDays = getMonthDays(currentDate);
    const curMonth = currentDate.getMonth();
    const activeDay = selectedDay || TODAY;
    const activeDayEvs = events.filter(e => e.date === activeDay).sort((a, b) => a.startHour - b.startHour);
    const activeDayObj = new Date(activeDay + "T00:00:00");

    return (
      <Card padding={0}>
        <div style={{overflowX:"hidden"}}>
          {/* Mobile: month navigation inside card */}
          {isMob && (
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px 8px",borderBottom:"1px solid var(--line)"}}>
              <button onClick={() => navigate(-1)} style={{background:"var(--surface-2)",border:"1px solid var(--line)",borderRadius:8,width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"var(--ink)"}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="15 18 9 12 15 6"/></svg>
              </button>
              <span style={{fontWeight:700,fontSize:14,color:"var(--ink)"}}>{MONTHS[currentDate.getMonth()]} {currentDate.getFullYear()}</span>
              <button onClick={() => navigate(1)} style={{background:"var(--surface-2)",border:"1px solid var(--line)",borderRadius:8,width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"var(--ink)"}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="9 18 15 12 9 6"/></svg>
              </button>
            </div>
          )}
          {/* Day names header */}
          <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",borderBottom:"1px solid var(--line)"}}>
            {DAY_NAMES.map(d => (
              <div key={d} style={{textAlign:"center",padding:"10px 0",fontSize:isMob?9:11.5,fontWeight:600,color:"var(--text-mute)",textTransform:"uppercase",letterSpacing:"0.05em"}}>{d}</div>
            ))}
          </div>
          {/* Days grid */}
          <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)"}}>
            {monthDays.map((d, i) => {
              const dStr = toDateStr(d);
              const inMonth = d.getMonth() === curMonth;
              const isToday = dStr === TODAY;
              const isSel = isMob && dStr === activeDay;
              const dayEvs = events.filter(ev => ev.date === dStr);

              if (isMob) {
                const dotColors = [...new Map(
                  dayEvs.map(ev => [ev.clinicId, findC(ev.clinicId)?.color]).filter(([, c]) => c)
                ).values()].slice(0, 3);
                return (
                  <div key={i} onClick={() => setSelectedDay(dStr)} style={{
                    minHeight:52, padding:"6px 2px 4px",
                    display:"flex", flexDirection:"column", alignItems:"center", gap:3,
                    cursor:"pointer",
                    borderRight: (i+1)%7===0 ? "none" : "1px solid var(--line)",
                    borderBottom: "1px solid var(--line)",
                    background: isSel ? "color-mix(in oklch, var(--accent), white 92%)" : "transparent",
                    opacity: inMonth ? 1 : 0.3,
                  }}>
                    <div style={{
                      width:24, height:24, borderRadius:"50%",
                      display:"flex", alignItems:"center", justifyContent:"center",
                      background: isToday ? "var(--accent)" : "transparent",
                      color: isToday ? "#fff" : isSel ? "var(--accent)" : "var(--ink)",
                      fontSize:12, fontWeight: isToday||isSel ? 700 : 500,
                    }}>{d.getDate()}</div>
                    {dotColors.length > 0 && (
                      <div style={{display:"flex",gap:2,justifyContent:"center"}}>
                        {dotColors.map((c, ci) => <span key={ci} style={{width:5,height:5,borderRadius:"50%",background:c,flexShrink:0}}/>)}
                      </div>
                    )}
                  </div>
                );
              }

              // Desktop: original pill style
              return (
                <div key={i} className="cal-month-cell" style={{
                  padding:"6px 8px",
                  borderRight: (i+1)%7===0 ? "none" : "1px solid var(--line)",
                  borderBottom: "1px solid var(--line)",
                  background: isToday ? "color-mix(in oklch, var(--accent), white 96%)" : "transparent",
                  opacity: inMonth ? 1 : 0.38,
                }}>
                  <div style={{display:"inline-flex",alignItems:"center",justifyContent:"center",width:24,height:24,borderRadius:"50%",marginBottom:4,background:isToday?"var(--accent)":"transparent",color:isToday?"#fff":"var(--ink)",fontSize:13,fontWeight:isToday?700:500}}>{d.getDate()}</div>
                  {dayEvs.slice(0,3).map((ev, ei) => {
                    const c = findC(ev.clinicId);
                    const p = getEvPatient(ev);
                    if (!c || !p) return null;
                    return (
                      <button key={ei} onClick={(e) => { e.stopPropagation(); setSelectedEvent(selectedEvent?.id===ev.id ? null : ev); }}
                        style={{display:"flex",alignItems:"center",gap:4,width:"100%",background:c.color+"20",borderRadius:4,padding:"2px 5px",marginBottom:2,border:"none",cursor:"pointer",textAlign:"left"}}>
                        <span style={{width:6,height:6,borderRadius:"50%",background:c.color,flexShrink:0}}/>
                        <span style={{fontSize:11,color:"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{fmtH(ev.startHour)} {p.name}</span>
                      </button>
                    );
                  })}
                  {dayEvs.length > 3 && <div style={{fontSize:11,color:"var(--text-mute)",paddingLeft:10}}>+{dayEvs.length-3} daha</div>}
                </div>
              );
            })}
          </div>

          {/* Mobile: selected day appointment cards */}
          {isMob && (
            <div style={{borderTop:"1px solid var(--line)",padding:"14px 12px 16px",display:"flex",flexDirection:"column",gap:8}}>
              <div style={{fontSize:11.5,fontWeight:600,color:"var(--text-mute)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:2}}>
                {LONG_DAYS[dayIdx(activeDayObj)]}, {activeDayObj.getDate()} {MONTHS[activeDayObj.getMonth()]}
              </div>
              {activeDayEvs.length === 0 ? (
                <div style={{fontSize:13,color:"var(--text-mute)",textAlign:"center",padding:"14px 0"}}>Bu gün için randevu yok</div>
              ) : activeDayEvs.map(ev => {
                const p = getEvPatient(ev);
                const c = findC(ev.clinicId);
                if (!p || !c) return null;
                return (
                  <div key={ev.id}
                    style={{background:c.color+"1A",borderLeft:`4px solid ${c.color}`,borderRadius:12,padding:"12px 14px",cursor:"pointer"}}
                    onClick={(e) => { e.stopPropagation(); setSelectedEvent(ev); }}>
                    <div style={{fontSize:14,fontWeight:700,color:"var(--ink)",marginBottom:2}}>{p.name}</div>
                    <div style={{fontSize:12.5,fontWeight:500,color:c.color,marginBottom:7}}>{ev.procedure}</div>
                    <div style={{display:"flex",alignItems:"center",gap:5,fontSize:12,color:"var(--text-mute)"}}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                      <span>{fmtH(ev.startHour)} – {fmtH(ev.startHour + ev.duration)}</span>
                      <span style={{color:c.color,fontWeight:600}}>· {c.name}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </Card>
    );
  };

  const selEv = selectedEvent;
  const selP = selEv ? getEvPatient(selEv) : null;
  const selC = selEv ? findC(selEv.clinicId) : null;

  return (
    <div className="view" onClick={() => setSelectedEvent(null)}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Takvim</h1>
          <p className="page-sub">{getHeaderLabel()}</p>
        </div>
        <div className="page-actions">
          {!isMob && (
            <div className="seg">
              <button className={`seg__opt ${calView==="gun"?"is-on":""}`} onClick={()=>{setCalView("gun");setSelectedEvent(null);}}>Gün</button>
              <button className={`seg__opt ${calView==="hafta"?"is-on":""}`} onClick={()=>{setCalView("hafta");setSelectedEvent(null);}}>Hafta</button>
              <button className={`seg__opt ${calView==="ay"?"is-on":""}`} onClick={()=>{setCalView("ay");setSelectedEvent(null);}}>Ay</button>
            </div>
          )}
          {!isMob && <>
            <button className="btn btn--ghost btn--sm icon-only" onClick={() => navigate(-1)}>
              <I.ArrowLeft size={14}/>
            </button>
            <button className="btn btn--ghost btn--sm" onClick={() => { setCurrentDate(new Date()); setSelectedDay(null); setSelectedEvent(null); }}>Bugün</button>
            <button className="btn btn--ghost btn--sm icon-only" onClick={() => navigate(1)}>
              <I.ArrowRight size={14}/>
            </button>
          </>}
          <button className="btn btn--accent" onClick={() => { setNewApptDate(toDateStr(currentDate)); setShowNewAppt(true); }}>
            <I.Plus size={15}/>Randevu
          </button>
        </div>
      </div>

      <div className="cal-clinic-key">
        {data.CLINICS.map(c => (
          <span key={c.id} className="cal-key">
            <span className="clinic-bullet" style={{background:c.color}}/> {c.name}
          </span>
        ))}
      </div>

      {isMob ? renderMonthView() : (
        <>
          {calView === "hafta" && renderWeekView()}
          {calView === "gun" && renderDayView()}
          {calView === "ay" && renderMonthView()}
        </>
      )}

      {selEv && selP && selC && (
        <EventDetailModal
          event={selEv} patient={selP} clinic={selC}
          onClose={() => setSelectedEvent(null)}
          onGoToPatient={() => { setSelectedPatient(selP.id); onNav("patients"); }}
          onDelete={() => { onUpdateEvents(prev => prev.filter(e => e.id !== selEv.id)); setSelectedEvent(null); }}
        />
      )}

      {showNewAppt && (
        <NewApptModal
          data={data}
          defaultDate={newApptDate}
          onSave={(appt) => {
            let finalAppt = appt;
            if (appt.newPatient && onAddPatient) {
              const np = appt.newPatient;
              const added = onAddPatient({ name: np.name, phone: np.phone, age: np.age, gender: np.gender, clinicId: appt.clinicId, treatment: np.treatment, status: "Devam ediyor", plan: [], totalFee: 0, paid: 0, balance: 0 });
              finalAppt = { ...appt, patientId: added.id, newPatient: null };
            } else if (!appt.newPatient && appt.patientId && appt.categories?.length && onUpdatePatient) {
              const patient = data.PATIENTS.find(p => p.id === appt.patientId);
              if (patient) {
                const newSession = {
                  id: "s" + Date.now(),
                  session: (patient.plan?.length || 0) + 1,
                  date: appt.date,
                  procedure: appt.procedure,
                  fee: 0, share: 0,
                  status: "Planlandı",
                  category: appt.categories[0],
                };
                onUpdatePatient(appt.patientId, { plan: [...(patient.plan || []), newSession] });
              }
            }
            onUpdateEvents(prev => [...prev, finalAppt]);
            setShowNewAppt(false);
          }}
          onClose={() => setShowNewAppt(false)}
        />
      )}
    </div>
  );
}

window._dsSchedule = Schedule;
