﻿// 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 }) {
  const t = useT();
  const I = window.DentIcons;
  const profile = useProfile();
  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 (
    <>
    <div className={`sidebar-overlay${isOpen ? " is-open" : ""}`} onClick={onClose}/>
    <aside className={`sidebar sidebar--${theme}${isOpen ? " is-open" : ""}`}>
      <div className="sidebar__brand">
        <div className="brand-mark">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 3c-3.2 0-5.5 1.6-5.5 5 0 1.5.4 2.5.9 4s.4 3 .9 5c.4 1.7 1.4 4 2.2 4s1-1.5 1.5-3.5.5-3.5 2-3.5 1.5 1.5 2 3.5 1 3.5 1.5 3.5 1.7-2.3 2.2-4c.5-2 .4-3.5.9-5s.9-2.5.9-4c0-3.4-2.3-5-5.5-5z" fill="currentColor" fillOpacity=".15"/>
            <path d="M12 3c-3.2 0-5.5 1.6-5.5 5 0 1.5.4 2.5.9 4s.4 3 .9 5c.4 1.7 1.4 4 2.2 4s1-1.5 1.5-3.5.5-3.5 2-3.5 1.5 1.5 2 3.5 1 3.5 1.5 3.5 1.7-2.3 2.2-4c.5-2 .4-3.5.9-5s.9-2.5.9-4c0-3.4-2.3-5-5.5-5z"/>
          </svg>
        </div>
        <div className="brand-text">
          <span className="brand-name">DentSide</span>
          <span className="brand-tag">Hekim Operasyonu</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>
      </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 className="upgrade-card__head">
            <span className="upgrade-pill">PRO</span>
            <span className="upgrade-title">Pro Sürüm</span>
          </div>
          <p className="upgrade-body">Yakında geliyor:</p>
          <ul className="upgrade-features">
            <li>Çoklu hekim yönetimi</li>
            <li>Bulut yedekleme</li>
            <li>AI asistan</li>
            <li>WhatsApp entegrasyonu</li>
          </ul>
          <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>
      </div>
    </aside>
    </>
  );
}

const NOTIFICATIONS = [
  { id: 1, type: "payment",     title: "Bekleyen ödeme",       body: "Ataşehir Estetik Klinik — ₺2.200 hakediş henüz aktarılmadı.", time: "2 saat önce", read: false, nav: "finance" },
  { id: 2, type: "appointment", title: "Yarınki randevu",       body: "Selin Topaloğlu — Kontrol + plak 9-12, Levent Ortodonti.",   time: "5 saat önce", read: false, nav: "schedule" },
  { id: 3, type: "alert",       title: "Kalan bakiye uyarısı", body: "Can Doğan — ₺14.000 kalan bakiye tahsil edilmedi.",            time: "1 gün önce", read: false, nav: "patients" },
];

function NotifPanel({ onClose, onNav }) {
  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);
  }, []);

  const handleClick = (n) => {
    if (n.nav) onNav(n.nav);
    onClose();
  };

  return (
    <div className="notif-panel">
      <div className="notif-panel__head">
        <span className="notif-panel__title">Bildirimler</span>
        <span className="notif-panel__count">{NOTIFICATIONS.filter(n => !n.read).length} yeni</span>
      </div>
      <div className="notif-panel__list">
        {NOTIFICATIONS.map(n => (
          <div key={n.id} className="notif-item" 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>
          </div>
        ))}
      </div>
      <div className="notif-panel__foot">
        <button className="btn btn--ghost btn--sm" style={{width:"100%"}}>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 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 = (e) => {
    e.preventDefault();
    setPwdErr("");
    if (pwd.next.length < 6) return setPwdErr("Yeni şifre en az 6 karakter olmalı.");
    if (pwd.next !== pwd.confirm) return setPwdErr("Şifreler eşleşmiyor.");
    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">Ş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, onToggleSidebar }) {
  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 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">
        <I.Search size={16}/>
        <input
          value={query}
          onChange={(e) => onSearch(e.target.value)}
          placeholder={t.topbar.search}
        />
        <kbd>⌘K</kbd>
      </div>

      <div className="topbar__actions">
        <button className="icon-btn" title={t.topbar.quickAdd} onClick={onQuickAdd}>
          <I.Plus size={18}/>
        </button>
        <div style={{position:"relative"}}>
          <button className="icon-btn icon-btn--notif" title={t.topbar.notifications} onClick={() => setShowNotif(v => !v)}>
            <I.Bell size={18}/>
            {(() => { const cnt = NOTIFICATIONS.filter(n => !n.read).length; return cnt > 0 ? <span className="badge-dot">{cnt}</span> : null; })()}
          </button>
          {showNotif && <NotifPanel onClose={() => setShowNotif(false)} onNav={onNav}/>}
        </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>
  );
}

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