﻿// Sidebar + Topbar + small UI primitives shared across views

const useT = () => React.useContext(window.DentI18n);

const DEFAULT_PROFILE = (() => {
  const meta = window._dentUser?.user_metadata || {};
  return {
    name: meta.full_name || "Dr. Mehmet Aydın",
    specialty: meta.specialty || "Diş Hekimi",
    email: window._dentUser?.email || "",
    phone: ""
  };
})();

function getProfile() {
  try { return JSON.parse(localStorage.getItem("df_profile_" + (window._dentUser?.id || ""))) || DEFAULT_PROFILE; } catch(e) { return DEFAULT_PROFILE; }
}

function initials(name) {
  return (name || "").split(" ").filter(Boolean).map(w => w[0]).slice(0, 2).join("").toUpperCase() || "DR";
}

function useProfile() {
  const [profile, setProfile] = React.useState(getProfile);
  React.useEffect(() => {
    const handler = () => setProfile(getProfile());
    window.addEventListener("df_profile_updated", handler);
    return () => window.removeEventListener("df_profile_updated", handler);
  }, []);
  return profile;
}

function Sidebar({ active, onNav, theme, badges = {}, isOpen, onClose, isCollapsed, onToggleCollapse }) {
  const t = useT();
  const I = window.DentIcons;
  const profile = useProfile();
  const trialEnd = new Date(window._dentUser?.user_metadata?.trial_end_date);
  const daysLeft = Math.ceil((trialEnd - new Date()) / 86400000);
  const groups = [
    {
      title: t.nav.workspace,
      items: [
        { id: "dashboard", label: t.nav.dashboard, icon: I.Dashboard },
        { id: "patients", label: t.nav.patients, icon: I.Patient },
        { id: "schedule", label: t.nav.schedule, icon: I.Calendar },
        { id: "treatments", label: t.nav.treatments, icon: I.Tooth },
        { id: "stock", label: t.nav.stock, icon: I.Stock },
      ],
    },
    {
      title: t.nav.operations,
      items: [
        { id: "clinics", label: t.nav.clinics, icon: I.Clinic },
        { id: "finance", label: t.nav.finance, icon: I.Money },
        { id: "reports", label: t.nav.reports, icon: I.Chart },
      ],
    },
    {
      title: t.nav.settings,
      items: [
        { id: "settings", label: t.nav.preferences, icon: I.Settings },
        { id: "help", label: t.nav.help, icon: I.Help },
      ],
    },
  ];

  const handleNav = (id) => { onNav(id); if (onClose) onClose(); };

  return (
    <aside className={`sidebar sidebar--${theme}${isOpen ? " is-open" : ""}`}>
      <div className="sidebar__brand">
        <div className="brand-mark">
          <svg width="22" height="22" viewBox="0 0 479.82 440.39" fill="currentColor">
            <path d="M239.91,229.04c18.22,0,33.05-14.83,33.05-33.05,0-15.16-10.27-27.97-24.22-31.84V20.12h-17.66s0,144.03,0,144.03c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05ZM239.91,180.61c8.48,0,15.38,6.9,15.38,15.38s-6.9,15.39-15.38,15.39-15.38-6.9-15.38-15.38,6.9-15.39,15.38-15.39Z"/>
            <path d="M19.81,197.47C9.51,128.08,37.01,66.89,93.39,33.78c18.21-10.69,38.17-16.12,59.33-16.12,11.33,0,22.98,1.58,34.87,4.69v90.98l-40.7,23.5v107.35c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05s33.05-14.83,33.05-33.05c0-15.16-10.27-27.97-24.22-31.84v-97.15l40.7-23.5V9.26C187.36,3.12,169.77,0,152.72,0c-24.35,0-47.32,6.24-68.28,18.55C21.63,55.44-9.06,123.3,2.34,200.07c9.03,60.8,24.33,120.64,43.08,168.5,9.35,23.85,19.21,43.88,29.31,59.52l14.84-9.58c-9.46-14.65-18.78-33.62-27.7-56.38-18.28-46.66-33.22-105.13-42.06-164.65ZM171.11,276.02c0,8.48-6.9,15.38-15.38,15.38s-15.38-6.9-15.38-15.38,6.9-15.38,15.38-15.38,15.38,6.9,15.38,15.38Z"/>
            <path d="M395.38,18.55C374.42,6.24,351.45,0,327.1,0c-17.05,0-34.64,3.12-52.54,9.26v114.27l40.7,23.5v97.15c-13.95,3.87-24.22,16.68-24.22,31.84,0,18.22,14.83,33.05,33.05,33.05s33.05-14.83,33.05-33.05c0-15.16-10.27-27.97-24.22-31.84v-107.35l-40.7-23.5V22.35c11.9-3.11,23.55-4.69,34.87-4.69,21.16,0,41.12,5.42,59.33,16.12,56.38,33.11,83.88,94.3,73.57,163.69-8.84,59.52-23.78,118-42.06,164.65-8.91,22.76-18.23,41.72-27.7,56.38l14.84,9.58c10.1-15.65,19.96-35.67,29.3-59.52,18.75-47.86,34.05-107.69,43.08-168.5,11.4-76.77-19.29-144.63-82.1-181.52ZM339.49,276.02c0,8.48-6.9,15.38-15.38,15.38s-15.38-6.9-15.38-15.38,6.9-15.38,15.38-15.38,15.38,6.9,15.38,15.38Z"/>
            <path d="M442.54,194.88c9.21-62.01-15.11-116.54-65.05-145.87-18.23-10.71-38.11-15.16-59.44-13.37v17.82c18.33-1.78,35.21,1.81,50.49,10.78,44.15,25.93,64.76,72.6,56.52,128.04-8.46,56.96-22.67,112.71-40.01,156.95-18.36,46.86-35.02,67.52-44.49,71.22-7.94,3.1-15.07,3.07-21.83-.09-10.85-5.09-20.51-18.3-26.5-36.27-2.01-6.04-3.84-14.03-5.78-22.48-7.1-31.04-15.94-69.68-46.55-69.68s-39.45,38.63-46.55,69.68c-1.93,8.45-3.76,16.44-5.78,22.48-5.99,17.96-15.65,31.18-26.5,36.27-6.75,3.16-13.89,3.2-21.83.09-9.47-3.7-26.13-24.36-44.49-71.22-17.34-44.25-31.54-99.99-40.01-156.95-8.24-55.44,12.36-102.11,56.52-128.04,15.28-8.97,32.16-12.56,50.49-10.78v-17.82c-21.33-1.78-41.2,2.66-59.44,13.37-49.94,29.33-74.26,83.86-65.05,145.87,8.65,58.24,23.23,115.35,41.03,160.8,12.65,32.28,32.37,72.57,54.51,81.23,5.94,2.32,11.88,3.48,17.69,3.48,6.25,0,12.33-1.34,18.06-4.03,20.83-9.76,31.35-33.43,35.77-46.68,2.28-6.85,4.2-15.24,6.24-24.13,5.7-24.93,12.8-55.96,29.33-55.96s23.62,31.02,29.33,55.95c2.03,8.88,3.95,17.28,6.24,24.13,4.42,13.24,14.93,36.92,35.77,46.68,11.06,5.18,23.42,5.37,35.75.55,22.14-8.66,41.86-48.95,54.51-81.23,17.81-45.45,32.38-102.56,41.03-160.8Z"/>
          </svg>
        </div>
        <div className="brand-text">
          <span className="brand-name">DentSide</span>
          <span className="brand-tag">Smarter Dental Management</span>
        </div>
        <button className="sidebar__close" onClick={onClose} aria-label="Kapat">
          <svg width="16" height="16" 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>
        <button className="sidebar__collapse-btn" onClick={onToggleCollapse} aria-label="Daralt">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" style={{transform: isCollapsed ? "rotate(180deg)" : "none", transition:"transform 0.2s"}}><polyline points="15 18 9 12 15 6"/></svg>
        </button>
      </div>

      <div className="sidebar__user">
        <div className="avatar avatar--md" style={{background: "linear-gradient(135deg, var(--accent), var(--accent-2))"}}>{initials(profile.name)}</div>
        <div className="user-meta">
          <span className="user-name">{profile.name || DEFAULT_PROFILE.name}</span>
          <span className="user-role">{profile.specialty || DEFAULT_PROFILE.specialty}</span>
        </div>
        <button className="user-switch" title={t.nav.switch}><I.Arrow size={14}/></button>
      </div>

      <nav className="sidebar__nav">
        {groups.map((g) => (
          <div key={g.title} className="nav-group">
            <div className="nav-group__title">{g.title}</div>
            {g.items.map((it) => {
              const IconC = it.icon;
              const isActive = active === it.id;
              return (
                <button
                  key={it.id}
                  className={`nav-item ${isActive ? "is-active" : ""}`}
                  onClick={() => handleNav(it.id)}
                >
                  <IconC size={17}/>
                  <span>{it.label}</span>
                  {it.id === "schedule" && badges.schedule > 0 && (
                    <span className="nav-badge">{badges.schedule}</span>
                  )}
                  {it.id === "finance" && badges.finance > 0 && (
                    <span className="nav-badge nav-badge--alert">{badges.finance}</span>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </nav>

      <div className="sidebar__upgrade">
        <div className="upgrade-card">
          <div style={{fontSize:11,fontWeight:600,marginBottom:10,padding:"5px 8px",borderRadius:6,background: daysLeft <= 3 ? "rgba(226,122,82,.15)" : "rgba(43,71,232,.1)",color: daysLeft <= 3 ? "#c0553a" : "var(--accent)"}}>
            ⏱ Deneme süresi: {daysLeft} gün kaldı
          </div>
          <div className="upgrade-card__head">
            <span className="upgrade-pill">PRO</span>
            <span className="upgrade-title">Pro Sürüm</span>
          </div>
          <button className="btn btn--block upgrade-soon-btn" disabled>
            <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"/><polyline points="12 6 12 12 16 14"/></svg>
            Yakında
          </button>
          <div style={{marginTop:10,paddingTop:10,borderTop:"1px solid var(--sb-line)",fontSize:11,color:"var(--text-mute)",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <span>DentSide v1.0</span>
            <a href="mailto:info@dentsideapp.com" style={{color:"var(--accent)",textDecoration:"none"}}>info@dentsideapp.com</a>
          </div>
        </div>
      </div>
    </aside>
  );
}

function NotifPanel({ onClose, onNav, notifications, readIds = new Set(), onMarkRead }) {
  const I = window.DentIcons;
  const typeIcon = { payment: "₺", appointment: "📅", alert: "⚠" };
  const typeColor = { payment: "var(--mint)", appointment: "var(--accent)", alert: "var(--coral)" };

  React.useEffect(() => {
    const handler = (e) => { if (!e.target.closest(".notif-panel") && !e.target.closest(".icon-btn--notif")) onClose(); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  React.useEffect(() => {
    if (notifications.length > 0 && onMarkRead) {
      const timer = setTimeout(() => onMarkRead(notifications.map(n => n.id)), 1500);
      return () => clearTimeout(timer);
    }
  }, []);

  const unreadCount = notifications.filter(n => !readIds.has(n.id)).length;

  const handleClick = (n) => {
    if (onMarkRead) onMarkRead([n.id]);
    if (n.nav) onNav(n.nav);
    onClose();
  };

  const markAll = () => {
    if (onMarkRead) onMarkRead(notifications.map(n => n.id));
  };

  return (
    <div className="notif-panel">
      <div className="notif-panel__head">
        <span className="notif-panel__title">Bildirimler</span>
        {unreadCount > 0
          ? <span className="notif-panel__count">{unreadCount} yeni</span>
          : <span className="notif-panel__count notif-panel__count--read">Tümü okundu</span>
        }
      </div>
      <div className="notif-panel__list">
        {notifications.length === 0 && (
          <div style={{padding:"16px 12px", fontSize:13, color:"var(--text-mute)", textAlign:"center"}}>Bildirim yok</div>
        )}
        {notifications.map(n => {
          const isUnread = !readIds.has(n.id);
          return (
            <div key={n.id} className={`notif-item${isUnread ? " is-unread" : ""}`} onClick={() => handleClick(n)} style={{cursor: n.nav ? "pointer" : "default"}}>
              <div className="notif-item__icon" style={{background: typeColor[n.type] + "18", color: typeColor[n.type]}}>
                {typeIcon[n.type]}
              </div>
              <div className="notif-item__body">
                <div className="notif-item__title">{n.title}</div>
                <div className="notif-item__text">{n.body}</div>
                <div className="notif-item__time">{n.time}</div>
              </div>
              {isUnread && <span className="notif-dot"/>}
            </div>
          );
        })}
      </div>
      <div className="notif-panel__foot" style={{display:"flex",gap:6}}>
        {unreadCount > 0 && (
          <button className="btn btn--ghost btn--sm" onClick={markAll}>Tümünü okundu işaretle</button>
        )}
        <button className="btn btn--ghost btn--sm" style={{marginLeft:"auto"}}>Tümünü gör</button>
      </div>
    </div>
  );
}

function ProfileSettingsModal({ onClose }) {
  const [tab, setTab] = React.useState("info");
  const [saved, setSaved] = React.useState("");

  const showSaved = (msg) => { setSaved(msg); setTimeout(() => setSaved(""), 2500); };

  // --- Profil Bilgileri ---
  const defaultInfo = DEFAULT_PROFILE;
  const [info, setInfo] = React.useState(() => { try { return JSON.parse(localStorage.getItem("df_profile_" + (window._dentUser?.id || ""))) || defaultInfo; } catch { return defaultInfo; } });
  const setInfoF = (k, v) => setInfo(f => ({ ...f, [k]: v }));

  // --- Şifre ---
  const [pwd, setPwd] = React.useState({ current: "", next: "", confirm: "" });
  const [pwdErr, setPwdErr] = React.useState("");
  const [pwdLoading, setPwdLoading] = React.useState(false);
  const setPwdF = (k, v) => setPwd(f => ({ ...f, [k]: v }));

  // --- Bildirimler ---
  const defaultNotifs = { payment: true, appointment: true, balance: true, weekly: false, sms: false };
  const [notifs, setNotifs] = React.useState(() => { try { return JSON.parse(localStorage.getItem("df_notifs")) || defaultNotifs; } catch { return defaultNotifs; } });
  const toggleNotif = (k) => setNotifs(f => ({ ...f, [k]: !f[k] }));

  const handleInfoSave = (e) => {
    e.preventDefault();
    localStorage.setItem("df_profile_" + (window._dentUser?.id || ""), JSON.stringify(info));
    window.dispatchEvent(new Event("df_profile_updated"));
    showSaved("Profil bilgileri kaydedildi.");
  };

  const handlePwdSave = async (e) => {
    e.preventDefault();
    setPwdErr("");
    if (pwd.next.length < 8) return setPwdErr("Yeni şifre en az 8 karakter olmalı.");
    if (!/[A-Z]/.test(pwd.next)) return setPwdErr("Yeni şifre en az bir büyük harf içermeli.");
    if (!/[0-9]/.test(pwd.next)) return setPwdErr("Yeni şifre en az bir rakam içermeli.");
    if (pwd.next !== pwd.confirm) return setPwdErr("Şifreler eşleşmiyor.");
    setPwdLoading(true);
    const email = window._dentUser?.email;
    const { error: authErr } = await window._sb.auth.signInWithPassword({ email, password: pwd.current });
    if (authErr) { setPwdErr("Mevcut şifre hatalı."); setPwdLoading(false); return; }
    const { error } = await window._sb.auth.updateUser({ password: pwd.next });
    setPwdLoading(false);
    if (error) return setPwdErr("Şifre güncellenemedi: " + error.message);
    setPwd({ current: "", next: "", confirm: "" });
    showSaved("Şifre başarıyla değiştirildi.");
  };

  const handleNotifSave = (e) => {
    e.preventDefault();
    localStorage.setItem("df_notifs", JSON.stringify(notifs));
    showSaved("Bildirim tercihleri kaydedildi.");
  };

  const tabs = [
    { id: "info", label: "Profil Bilgileri" },
    { id: "password", label: "Şifre" },
    { id: "notifs", label: "Bildirimler" },
  ];

  return (
    <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{maxWidth:520}}>
        <div className="modal__head">
          <span className="modal__title">Profil Ayarları</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="ps-tabs">
          {tabs.map(t => (
            <button key={t.id} className={`ps-tab ${tab===t.id?"is-on":""}`} onClick={() => { setTab(t.id); setSaved(""); setPwdErr(""); }}>
              {t.label}
            </button>
          ))}
        </div>

        {tab === "info" && (
          <form onSubmit={handleInfoSave}>
            <div className="modal__body">
              <div className="profile-info-row">
                <div className="avatar avatar--md" style={{background:"linear-gradient(135deg,var(--accent),var(--accent-2))"}}>MA</div>
                <div>
                  <div style={{fontWeight:700,fontSize:14,color:"var(--ink)"}}>{info.name}</div>
                  <div style={{fontSize:12,color:"var(--text-mute)"}}>{info.specialty}</div>
                </div>
              </div>
              <div className="form-field">
                <label>Ad Soyad</label>
                <input value={info.name} onChange={e => setInfoF("name", e.target.value)} required/>
              </div>
              <div className="form-field">
                <label>Uzmanlık</label>
                <input value={info.specialty} onChange={e => setInfoF("specialty", e.target.value)}/>
              </div>
              <div className="form-row">
                <div className="form-field">
                  <label>E-posta</label>
                  <input type="email" value={info.email} onChange={e => setInfoF("email", e.target.value)}/>
                </div>
                <div className="form-field">
                  <label>Telefon</label>
                  <input value={info.phone} onChange={e => setInfoF("phone", e.target.value)}/>
                </div>
              </div>
            </div>
            {saved && <div className="ps-success">{saved}</div>}
            <div className="modal__foot">
              <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
              <button type="submit" className="btn btn--accent">Kaydet</button>
            </div>
          </form>
        )}

        {tab === "password" && (
          <form onSubmit={handlePwdSave}>
            <div className="modal__body">
              <div className="form-field">
                <label>Mevcut Şifre</label>
                <input type="password" value={pwd.current} onChange={e => setPwdF("current", e.target.value)} placeholder="••••••••" required/>
              </div>
              <div className="form-field">
                <label>Yeni Şifre</label>
                <input type="password" value={pwd.next} onChange={e => setPwdF("next", e.target.value)} placeholder="••••••••" required/>
              </div>
              <div className="form-field">
                <label>Yeni Şifre Tekrar</label>
                <input type="password" value={pwd.confirm} onChange={e => setPwdF("confirm", e.target.value)} placeholder="••••••••" required/>
              </div>
              {pwdErr && <div className="ps-error">{pwdErr}</div>}
            </div>
            {saved && <div className="ps-success">{saved}</div>}
            <div className="modal__foot">
              <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
              <button type="submit" className="btn btn--accent" disabled={pwdLoading}>{pwdLoading ? "Güncelleniyor..." : "Şifreyi Güncelle"}</button>
            </div>
          </form>
        )}

        {tab === "notifs" && (
          <form onSubmit={handleNotifSave}>
            <div className="modal__body">
              {[
                { key:"payment",  label:"Ödeme bildirimleri",     desc:"Bekleyen ve geciken ödemeler" },
                { key:"appointment", label:"Randevu hatırlatıcıları", desc:"Günlük ve yaklaşan randevular" },
                { key:"balance",  label:"Kalan bakiye uyarıları", desc:"Yüksek bakiyeli hastalar" },
                { key:"weekly",   label:"Haftalık özet e-postası", desc:"Her Pazartesi gönderilir" },
                { key:"sms",      label:"SMS bildirimleri",        desc:"Kritik uyarılar için SMS" },
              ].map(n => (
                <div key={n.key} className="notif-pref-row">
                  <div>
                    <div className="notif-pref-label">{n.label}</div>
                    <div className="notif-pref-desc">{n.desc}</div>
                  </div>
                  <button type="button" className={`toggle ${notifs[n.key]?"is-on":""}`} onClick={() => toggleNotif(n.key)}>
                    <span className="toggle__knob"/>
                  </button>
                </div>
              ))}
            </div>
            {saved && <div className="ps-success">{saved}</div>}
            <div className="modal__foot">
              <button type="button" className="btn btn--ghost" onClick={onClose}>İptal</button>
              <button type="submit" className="btn btn--accent">Kaydet</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ProfileMenu({ onClose, onSettings }) {
  const I = window.DentIcons;
  const profile = useProfile();

  React.useEffect(() => {
    const handler = (e) => { if (!e.target.closest(".profile-menu") && !e.target.closest(".topbar__profile")) onClose(); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  return (
    <div className="profile-menu">
      <div className="profile-menu__head">
        <div className="avatar avatar--md" style={{background:"linear-gradient(135deg,var(--accent),var(--accent-2))"}}>{initials(profile.name)}</div>
        <div>
          <div className="profile-menu__name">{profile.name || DEFAULT_PROFILE.name}</div>
          <div className="profile-menu__role">{profile.specialty || DEFAULT_PROFILE.specialty}</div>
        </div>
      </div>
      <div className="profile-menu__divider"/>
      <button className="profile-menu__item" onClick={() => { onClose(); onSettings(); }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
        Profil ayarları
      </button>
      <div className="profile-menu__divider"/>
      <button className="profile-menu__item profile-menu__item--danger" onClick={() => { localStorage.removeItem('ds_start_mode'); window._sb.auth.signOut().then(() => { window.location.href = 'giris.html'; }); }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
        Çıkış Yap
      </button>
    </div>
  );
}

function Topbar({ active, onSearch, query, onNav, onQuickAdd, onExport, onToggleSidebar, notifications = [], readNotifIds = new Set(), onMarkNotifsRead }) {
  const t = useT();
  const I = window.DentIcons;
  const profile = useProfile();
  const [showNotif, setShowNotif] = React.useState(false);
  const [showProfile, setShowProfile] = React.useState(false);
  const [showProfileSettings, setShowProfileSettings] = React.useState(false);
  const [searchExpanded, setSearchExpanded] = React.useState(false);
  const searchInputRef = React.useRef(null);

  React.useEffect(() => {
    if (searchExpanded && searchInputRef.current) searchInputRef.current.focus();
  }, [searchExpanded]);
  const crumbMap = {
    dashboard: [t.nav.workspace, t.nav.dashboard],
    patients: [t.nav.workspace, t.nav.patients],
    schedule: [t.nav.workspace, t.nav.schedule],
    treatments: [t.nav.workspace, t.nav.treatments],
    stock: [t.nav.workspace, t.nav.stock],
    clinics: [t.nav.operations, t.nav.clinics],
    finance: [t.nav.operations, t.nav.finance],
    reports: [t.nav.operations, t.nav.reports],
    settings: [t.nav.settings, t.nav.preferences],
    help: [t.nav.settings, t.nav.help],
  };
  const crumb = crumbMap[active] || [];

  return (
    <header className="topbar">
      <button className="topbar__hamburger" onClick={onToggleSidebar} aria-label="Menü">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
      </button>
      <div className="topbar__crumb">
        {crumb.map((c, i) => (
          <React.Fragment key={i}>
            <span className={i === crumb.length - 1 ? "crumb crumb--active" : "crumb"}>{c}</span>
            {i < crumb.length - 1 && <span className="crumb-sep">/</span>}
          </React.Fragment>
        ))}
      </div>

      <div
        className={`topbar__search${searchExpanded ? " topbar__search--expanded" : ""}`}
        onClick={!searchExpanded ? () => setSearchExpanded(true) : undefined}
        style={!searchExpanded ? {cursor: "pointer"} : {}}
      >
        <I.Search size={16}/>
        <input
          ref={searchInputRef}
          value={query}
          onChange={(e) => onSearch(e.target.value)}
          placeholder={t.topbar.search}
          onKeyDown={(e) => e.key === "Escape" && (setSearchExpanded(false), onSearch(""))}
        />
        {searchExpanded
          ? <button
              onClick={(e) => { e.stopPropagation(); setSearchExpanded(false); onSearch(""); }}
              style={{background:"none",border:"none",cursor:"pointer",padding:"2px 0 2px 4px",color:"var(--text-mute)",display:"flex",alignItems:"center",flexShrink:0}}
            >
              <svg width="14" height="14" 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>
          : <kbd>⌘K</kbd>
        }
      </div>

      <div className="topbar__actions">
        <button className="btn btn--ghost topbar-export-btn" onClick={onExport} title="Rapor Al">
          <I.Export size={15}/>
          <span className="topbar-export-label">Rapor Al</span>
        </button>
        <button className="btn btn--accent topbar-add-btn" onClick={onQuickAdd}>
          <I.Plus size={15}/>
          <span className="topbar-add-label">Hasta Ekle</span>
        </button>
        <div style={{position:"relative"}}>
          <button className="icon-btn icon-btn--notif" title={t.topbar.notifications} onClick={() => setShowNotif(v => !v)}>
            <I.Bell size={18}/>
            {notifications.filter(n => !readNotifIds.has(n.id)).length > 0 && (
              <span className="badge-dot">{notifications.filter(n => !readNotifIds.has(n.id)).length}</span>
            )}
          </button>
          {showNotif && <NotifPanel onClose={() => setShowNotif(false)} onNav={onNav} notifications={notifications} readIds={readNotifIds} onMarkRead={onMarkNotifsRead}/>}
        </div>
        <div className="topbar__divider" />
        <div style={{position:"relative"}}>
          <div className="topbar__profile" onClick={() => setShowProfile(v => !v)} style={{cursor:"pointer"}}>
            <div className="avatar avatar--sm" style={{background: "linear-gradient(135deg, var(--accent), var(--accent-2))"}}>{initials(profile.name)}</div>
            <div>
              <div className="profile-name">{profile.name || DEFAULT_PROFILE.name}</div>
              <div className="profile-meta">{t.topbar.today}, {new Date().toLocaleDateString("tr-TR", { day:"numeric", month:"long", year:"numeric" })}</div>
            </div>
            <I.Arrow size={14}/>
          </div>
          {showProfile && <ProfileMenu onClose={() => setShowProfile(false)} onSettings={() => setShowProfileSettings(true)}/>}
          {showProfileSettings && <ProfileSettingsModal onClose={() => setShowProfileSettings(false)}/>}
        </div>
      </div>
    </header>
  );
}

// ──── Small primitives ────

const fmtTRY = (n, opts = {}) =>
  new Intl.NumberFormat("tr-TR", { style: "currency", currency: "TRY", maximumFractionDigits: 0, ...opts }).format(n);

const fmtDate = (d, locale = "tr") => {
  const date = typeof d === "string" ? new Date(d) : d;
  const months = locale === "tr"
    ? ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"]
    : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
};

const daysFromToday = (d) => {
  const today = new Date(); today.setHours(0,0,0,0);
  const target = new Date(d + "T00:00:00");
  return Math.round((target - today) / 86400000);
};

function Tag({ color = "neutral", children, dot = false }) {
  return (
    <span className={`tag tag--${color}`}>
      {dot && <span className="tag-dot"/>}
      {children}
    </span>
  );
}

function Card({ children, className = "", padding = 22, style = {} }) {
  return <div className={`card ${className}`} style={{padding, ...style}}>{children}</div>;
}

function StatusPill({ status }) {
  const t = useT();
  const map = {
    "Devam ediyor": { color: "blue", label: t.statuses.active },
    "Tamamlandı": { color: "green", label: t.statuses.done },
    "Planlandı": { color: "amber", label: t.statuses.planned },
    "Bekliyor": { color: "amber", label: t.statuses.waiting },
  };
  const s = map[status] || { color: "neutral", label: status };
  return <Tag color={s.color} dot>{s.label}</Tag>;
}

function Avatar({ name, size = 32, clinicColor }) {
  const ini = name.split(" ").map(s => s[0]).slice(0,2).join("").toUpperCase();
  const colors = ["#5B8DEF","#3FB893","#A78BFA","#F59E64","#EC6F8E","#3DD6D0"];
  const c = clinicColor || colors[ini.charCodeAt(0) % colors.length];
  return (
    <div className="avatar" style={{
      width: size, height: size,
      background: `linear-gradient(135deg, ${c}, ${c}cc)`,
      fontSize: size * 0.42,
    }}>{ini}</div>
  );
}

function ConfirmModal({ title, message, confirmLabel = "Tamam", danger = false, onConfirm, onCancel }) {
  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onCancel()}>
      <div className="modal" style={{maxWidth: 400}}>
        <div className="modal__head">
          <span className="modal__title">{title}</span>
        </div>
        <div className="modal__body">
          <p style={{fontSize: 14, color: "var(--text)", margin: 0, lineHeight: 1.6}}>{message}</p>
        </div>
        <div className="modal__foot">
          <button className="btn btn--ghost" onClick={onCancel}>İptal</button>
          <button className="btn btn--accent"
            style={danger ? {background:"var(--coral)", borderColor:"var(--coral)"} : {}}
            onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

window.DentUI = { Sidebar, Topbar, Tag, Card, StatusPill, Avatar, fmtTRY, fmtDate, daysFromToday, useT, ConfirmModal };
