// Profile page — redesigned to match app style
const PRFIcons = window.Icons;

function pwStrength(pw) {
  if (!pw) return 0;
  let s = 0;
  if (pw.length >= 8)            s++;
  if (pw.length >= 12)           s++;
  if (/[A-Z]/.test(pw))         s++;
  if (/[0-9]/.test(pw))         s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  return s;
}
const PW_LABELS = ['', 'Çok zayıf', 'Zayıf', 'Orta', 'İyi', 'Güçlü'];
const PW_COLORS = ['', '#ef4444', '#f97316', '#f59e0b', '#22c55e', '#16a34a'];

function calcStreak(tasks) {
  const today = new Date(); today.setHours(0,0,0,0);
  const doneDays = new Set(
    tasks.filter(t => t.status === 'done').map(t => {
      const d = t.completedAt ? new Date(t.completedAt) : t.updatedAt ? new Date(t.updatedAt) : null;
      if (!d) return null;
      const dd = new Date(d); dd.setHours(0,0,0,0);
      return dd.getTime();
    }).filter(Boolean)
  );
  let streak = 0;
  for (let i = 0; i < 365; i++) {
    const d = new Date(today); d.setDate(d.getDate() - i);
    if (!doneDays.has(d.getTime())) break;
    streak++;
  }
  return streak;
}

function Profile({ user, onUpdateUser, setActiveView, onLogout, accentColor, onSetAccentColor,
                   state, theme, onSetTheme, onReplaceState }) {

  const [name,   setName]   = React.useState(user?.name  || '');
  const [email,  setEmail]  = React.useState(user?.email || '');
  const [title,  setTitle]  = React.useState(user?.title || '');
  const [phone,  setPhone]  = React.useState(user?.phone || '');
  const [bio,    setBio]    = React.useState(user?.bio   || '');
  const [profileMsg,  setProfileMsg]  = React.useState(null);
  const [profileBusy, setProfileBusy] = React.useState(false);

  const [curPw,  setCurPw]  = React.useState('');
  const [newPw,  setNewPw]  = React.useState('');
  const [confPw, setConfPw] = React.useState('');
  const [pwMsg,  setPwMsg]  = React.useState(null);
  const [pwBusy, setPwBusy] = React.useState(false);
  const strength = pwStrength(newPw);

  const [avatarUrl,  setAvatarUrl]  = React.useState(user?.avatarUrl || null);
  const [avatarBusy, setAvatarBusy] = React.useState(false);
  const fileRef   = React.useRef(null);
  const importRef = React.useRef(null);

  const [defaultView,   setDefaultView]   = React.useState(user?.defaultProjectView || 'kanban');
  const [settingsSaved, setSettingsSaved] = React.useState(false);
  const [exportMsg,     setExportMsg]     = React.useState(null);

  // Digest bildirim ayarları
  const [digestEnabled,       setDigestEnabled]       = React.useState(user?.digestEnabled       ?? false);
  const [digestHour,          setDigestHour]          = React.useState(user?.digestHour          ?? 8);
  const [digestIncludeOverdue,setDigestIncludeOverdue]= React.useState(user?.digestIncludeOverdue ?? true);
  const [digestProjects,      setDigestProjects]      = React.useState(user?.digestProjects       || []);
  const [digestMsg,           setDigestMsg]           = React.useState(null);
  const [digestBusy,          setDigestBusy]          = React.useState(false);

  const [pushSupported, setPushSupported] = React.useState(false);
  const [pushSubscribed, setPushSubscribed] = React.useState(false);
  const [pushBusy, setPushBusy] = React.useState(false);
  const [pushMsg, setPushMsg] = React.useState(null);

  React.useEffect(() => {
    if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
    setPushSupported(true);
    navigator.serviceWorker.ready.then(reg =>
      reg.pushManager.getSubscription().then(sub => setPushSubscribed(!!sub))
    ).catch(() => {});
  }, []);

  const urlBase64ToUint8Array = (base64String) => {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
    const raw = atob(base64);
    return Uint8Array.from([...raw].map(c => c.charCodeAt(0)));
  };

  const enablePush = async () => {
    setPushBusy(true); setPushMsg(null);
    try {
      const perm = await Notification.requestPermission();
      if (perm !== 'granted') { setPushMsg({ ok: false, text: 'Bildirim izni verilmedi.' }); return; }
      const keyRes = await fetch('./api/push.php', { credentials: 'include' });
      const keyData = await keyRes.json();
      if (!keyData.ok) throw new Error('Anahtar alınamadı.');
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(keyData.publicKey),
      });
      const res = await fetch('./api/push.php', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'subscribe', subscription: sub.toJSON() }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      setPushSubscribed(true);
      setPushMsg({ ok: true, text: 'Push bildirimleri açıldı.' });
    } catch (err) {
      setPushMsg({ ok: false, text: err.message || 'Etkinleştirilemedi.' });
    } finally { setPushBusy(false); setTimeout(() => setPushMsg(null), 3000); }
  };

  const disablePush = async () => {
    setPushBusy(true); setPushMsg(null);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      if (sub) {
        await fetch('./api/push.php', {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ action: 'unsubscribe', endpoint: sub.endpoint }),
        });
        await sub.unsubscribe();
      }
      setPushSubscribed(false);
      setPushMsg({ ok: true, text: 'Push bildirimleri kapatıldı.' });
    } catch (err) {
      setPushMsg({ ok: false, text: err.message || 'Kapatılamadı.' });
    } finally { setPushBusy(false); setTimeout(() => setPushMsg(null), 3000); }
  };

  const sendTestPush = async () => {
    setPushBusy(true); setPushMsg(null);
    try {
      const res = await fetch('./api/push.php', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'test' }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      setPushMsg({ ok: data.sent > 0, text: data.sent > 0 ? 'Deneme bildirimi gönderildi.' : 'Aktif abonelik bulunamadı.' });
    } catch (err) {
      setPushMsg({ ok: false, text: err.message || 'Gönderilemedi.' });
    } finally { setPushBusy(false); setTimeout(() => setPushMsg(null), 3000); }
  };

  const initials = (user?.name || 'U').split(' ').filter(Boolean)
    .map(w => w[0]).join('').slice(0, 2).toUpperCase();

  // Stats
  const allTasks      = (state?.tasks || []).filter(t => !t.archived);
  const doneTasks     = allTasks.filter(t => t.status === 'done');
  const activeProjs   = (state?.projects || []).filter(p => !p.archived).length;
  const streak        = calcStreak(allTasks);
  const monthStart    = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
  const doneThisMonth = doneTasks.filter(t => {
    const d = t.completedAt ? new Date(t.completedAt) : t.updatedAt ? new Date(t.updatedAt) : null;
    return d && d >= monthStart;
  }).length;
  const completionRate = allTasks.length ? Math.round(doneTasks.length / allTasks.length * 100) : 0;

  // Handlers
  const saveProfile = async () => {
    const n = name.trim(), e = email.trim();
    if (!n) return;
    setProfileBusy(true); setProfileMsg(null);
    try {
      const res  = await fetch('./api/profile.php?action=update_profile', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: n, email: e, title: title.trim(), phone: phone.trim(), bio: bio.trim() }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      onUpdateUser({ name: data.user.name, email: data.user.email, title: data.user.title, phone: data.user.phone, bio: data.user.bio });
      setProfileMsg({ ok: true, text: 'Profil güncellendi.' });
    } catch (err) {
      setProfileMsg({ ok: false, text: err.message || 'Güncelleme başarısız.' });
    } finally { setProfileBusy(false); }
  };

  const changePassword = async () => {
    if (!curPw || !newPw) return;
    if (newPw !== confPw) { setPwMsg({ ok: false, text: 'Şifreler eşleşmiyor.' }); return; }
    if (newPw.length < 8) { setPwMsg({ ok: false, text: 'En az 8 karakter gerekli.' }); return; }
    setPwBusy(true); setPwMsg(null);
    try {
      const res  = await fetch('./api/profile.php?action=change_password', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currentPassword: curPw, newPassword: newPw }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      setCurPw(''); setNewPw(''); setConfPw('');
      setPwMsg({ ok: true, text: 'Şifre başarıyla değiştirildi.' });
    } catch (err) {
      setPwMsg({ ok: false, text: err.message || 'Şifre değiştirilemedi.' });
    } finally { setPwBusy(false); }
  };

  const uploadAvatar = async (file) => {
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) { alert('Dosya 2 MB\'ı geçemez.'); return; }
    setAvatarBusy(true);
    const fd = new FormData(); fd.append('avatar', file);
    try {
      const res  = await fetch('./api/profile.php?action=upload_avatar', { method: 'POST', credentials: 'include', body: fd });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      const url = data.avatarUrl + '?t=' + Date.now();
      setAvatarUrl(url); onUpdateUser({ avatarUrl: data.avatarUrl });
    } catch (err) { alert(err.message || 'Avatar yüklenemedi.'); }
    finally { setAvatarBusy(false); if (fileRef.current) fileRef.current.value = ''; }
  };

  const deleteAvatar = async () => {
    setAvatarBusy(true);
    try {
      const res  = await fetch('./api/profile.php?action=delete_avatar', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: '{}' });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      setAvatarUrl(null); onUpdateUser({ avatarUrl: null });
    } catch (err) { alert(err.message || 'Avatar kaldırılamadı.'); }
    finally { setAvatarBusy(false); }
  };

  const saveSettings = async (dpv) => {
    const view = dpv || defaultView;
    try {
      await fetch('./api/profile.php?action=update_settings', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ default_project_view: view }),
      });
      onUpdateUser({ defaultProjectView: view });
      setSettingsSaved(true);
      setTimeout(() => setSettingsSaved(false), 2000);
    } catch (_) {}
  };

  const saveDigest = async () => {
    setDigestBusy(true); setDigestMsg(null);
    try {
      const res  = await fetch('./api/profile.php?action=update_digest', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: digestEnabled, hour: digestHour,
          includeOverdue: digestIncludeOverdue, projectKeys: digestProjects,
        }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error);
      setDigestMsg({ ok: true, text: 'Bildirim ayarları kaydedildi.' });
    } catch (err) {
      setDigestMsg({ ok: false, text: err.message || 'Kaydedilemedi.' });
    } finally { setDigestBusy(false); setTimeout(() => setDigestMsg(null), 3000); }
  };

  const exportJSON = () => {
    try {
      const blob = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
      const url  = URL.createObjectURL(blob);
      const a    = document.createElement('a');
      a.href = url; a.download = `navia-yedek-${new Date().toISOString().split('T')[0]}.json`;
      a.click(); URL.revokeObjectURL(url);
      setExportMsg({ ok: true, text: 'JSON yedeği indirildi.' });
    } catch (_) { setExportMsg({ ok: false, text: 'İndirme başarısız.' }); }
    setTimeout(() => setExportMsg(null), 3000);
  };

  const exportCSV = () => {
    try {
      const projs = Object.fromEntries((state?.projects || []).map(p => [p.id, p.name]));
      const STATUS_TR = { todo: 'Yapılacak', doing: 'Devam Ediyor', review: 'İncelemede', done: 'Tamamlandı' };
      const PRIO_TR   = { high: 'Yüksek', medium: 'Orta', low: 'Düşük' };
      const esc = v => `"${(v || '').replace(/"/g, '""')}"`;
      const headers = ['Başlık', 'Firma', 'Durum', 'Öncelik', 'Teslim Tarihi', 'Oluşturulma'];
      const rows = (state?.tasks || []).filter(t => !t.archived).map(t => [
        esc(t.title), esc(projs[t.projectId] || ''),
        STATUS_TR[t.status] || t.status, PRIO_TR[t.priority] || t.priority,
        t.due || '', t.createdAt ? t.createdAt.split('T')[0] : '',
      ]);
      const csv  = [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
      const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8' });
      const url  = URL.createObjectURL(blob);
      const a    = document.createElement('a'); a.href = url;
      a.download = `navia-gorevler-${new Date().toISOString().split('T')[0]}.csv`;
      a.click(); URL.revokeObjectURL(url);
      setExportMsg({ ok: true, text: 'CSV indirildi.' });
    } catch (_) { setExportMsg({ ok: false, text: 'İndirme başarısız.' }); }
    setTimeout(() => setExportMsg(null), 3000);
  };

  const handleImport = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result);
        if (!data.projects || !data.tasks) throw new Error('Geçersiz yedek dosyası.');
        if (window.confirm(`${data.projects.length} firma ve ${data.tasks.length} görev geri yüklenecek. Emin misiniz?`)) {
          onReplaceState?.(data);
          setExportMsg({ ok: true, text: 'Yedek başarıyla geri yüklendi.' });
          setTimeout(() => setExportMsg(null), 3000);
        }
      } catch (err) { alert(err.message || 'Geçersiz dosya.'); }
    };
    reader.readAsText(file);
    if (importRef.current) importRef.current.value = '';
  };

  return (
    <div className="content prf-page">

      {/* ── Üst başlık ─────────────────────────────── */}
      <div className="prf-header">
        <div className="prf-header-left">
          {/* Avatar + isim */}
          <div
            className={`prf-avatar-wrap${avatarBusy ? ' busy' : ''}`}
            onClick={() => !avatarBusy && fileRef.current?.click()}
            title="Fotoğraf değiştir"
          >
            {avatarUrl
              ? <img src={avatarUrl} alt={name} className="prf-avatar-img" />
              : <div className="prf-avatar-initials">{initials}</div>
            }
            <div className="prf-avatar-overlay">
              {avatarBusy ? <PRFIcons.Activity size={18} className="spin" /> : <PRFIcons.Camera size={16} />}
            </div>
          </div>
          <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp"
            style={{ display: 'none' }} onChange={e => uploadAvatar(e.target.files?.[0])} />

          <div className="prf-header-info">
            <div className="prf-header-name">{name || 'Kullanıcı'}</div>
            {title && <div className="prf-header-title">{title}</div>}
            <div className="prf-header-email">{email}</div>
            <div className="prf-avatar-actions">
              <button className="btn btn-ghost btn-sm" onClick={() => fileRef.current?.click()} disabled={avatarBusy}>
                <PRFIcons.Upload size={13} /> Fotoğraf yükle
              </button>
              {avatarUrl && (
                <button className="btn btn-ghost btn-sm" onClick={deleteAvatar} disabled={avatarBusy}
                  style={{ color: 'var(--p-high)' }}>
                  <PRFIcons.Trash size={13} /> Kaldır
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Stat chips */}
        <div className="prf-stat-chips">
          <div className="prf-chip">
            <PRFIcons.CheckCircle size={14} style={{ color: '#22c55e' }} />
            <span><strong>{doneTasks.length}</strong> tamamlandı</span>
          </div>
          <div className="prf-chip">
            <PRFIcons.Folder size={14} style={{ color: 'var(--accent)' }} />
            <span><strong>{activeProjs}</strong> firma</span>
          </div>
          <div className="prf-chip">
            <PRFIcons.Calendar size={14} style={{ color: '#3b82f6' }} />
            <span><strong>{doneThisMonth}</strong> bu ay</span>
          </div>
          <div className="prf-chip">
            <PRFIcons.TrendingUp size={14} style={{ color: '#f97316' }} />
            <span><strong>{completionRate}%</strong> oran</span>
          </div>
          {streak > 0 && (
            <div className="prf-chip prf-chip-accent">
              <span><strong>{streak}</strong> günlük seri 🔥</span>
            </div>
          )}
        </div>
      </div>

      {/* ── Ana içerik ─────────────────────────────── */}
      <div className="prf-body">

        {/* SOL SÜTUN */}
        <div className="prf-col-left">

          {/* Kişisel bilgiler */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.User size={15} /> Kişisel Bilgiler
            </h3>
            <div className="field">
              <label className="field-label">Ad Soyad</label>
              <input className="input" value={name} maxLength={160}
                onChange={e => { setName(e.target.value); setProfileMsg(null); }}
                placeholder="Adınız Soyadınız" />
            </div>
            <div className="field">
              <label className="field-label">E-posta</label>
              <input className="input" type="email" value={email} maxLength={190}
                onChange={e => { setEmail(e.target.value); setProfileMsg(null); }}
                placeholder="email@domain.com" />
            </div>
            <div className="prf-two-col">
              <div className="field">
                <label className="field-label">Unvan</label>
                <input className="input" value={title} maxLength={100}
                  onChange={e => { setTitle(e.target.value); setProfileMsg(null); }}
                  placeholder="Grafik Tasarımcı…" />
              </div>
              <div className="field">
                <label className="field-label">Telefon</label>
                <input className="input" type="tel" value={phone} maxLength={50}
                  onChange={e => { setPhone(e.target.value); setProfileMsg(null); }}
                  placeholder="+90 555 000 00 00" />
              </div>
            </div>
            <div className="field">
              <label className="field-label">
                Kısa bio
                <span className="prf-char-count">({bio.length}/300)</span>
              </label>
              <textarea className="input" value={bio} maxLength={300} rows={3}
                style={{ resize: 'vertical' }}
                onChange={e => { setBio(e.target.value); setProfileMsg(null); }}
                placeholder="Kendinizden kısaca bahsedin…" />
            </div>
            {profileMsg && <div className={`profile-msg ${profileMsg.ok ? 'ok' : 'err'}`}>{profileMsg.text}</div>}
            <div className="prf-footer">
              <button className="btn btn-primary btn-sm" onClick={saveProfile} disabled={profileBusy || !name.trim()}>
                <PRFIcons.Save size={13} /> {profileBusy ? 'Kaydediliyor…' : 'Kaydet'}
              </button>
            </div>
          </div>

          {/* Şifre */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.Lock size={15} /> Şifre Değiştir
            </h3>
            <div className="field">
              <label className="field-label">Mevcut şifre</label>
              <input className="input" type="password" value={curPw}
                onChange={e => { setCurPw(e.target.value); setPwMsg(null); }}
                placeholder="••••••••" autoComplete="current-password" />
            </div>
            <div className="field">
              <label className="field-label">Yeni şifre</label>
              <input className="input" type="password" value={newPw}
                onChange={e => { setNewPw(e.target.value); setPwMsg(null); }}
                placeholder="En az 8 karakter" autoComplete="new-password" />
              {newPw && (
                <div className="pw-strength-wrap">
                  <div className="pw-strength-bar">
                    {[1,2,3,4,5].map(i => (
                      <div key={i} className="pw-strength-seg"
                        style={{ background: i <= strength ? PW_COLORS[strength] : 'var(--border)' }} />
                    ))}
                  </div>
                  <span className="pw-strength-label" style={{ color: PW_COLORS[strength] }}>
                    {PW_LABELS[strength]}
                  </span>
                </div>
              )}
            </div>
            <div className="field">
              <label className="field-label">Tekrar</label>
              <input className="input" type="password" value={confPw}
                onChange={e => { setConfPw(e.target.value); setPwMsg(null); }}
                placeholder="••••••••" autoComplete="new-password"
                onKeyDown={e => { if (e.key === 'Enter') changePassword(); }} />
              {confPw && newPw !== confPw && <div className="pw-mismatch">Şifreler eşleşmiyor</div>}
            </div>
            {pwMsg && <div className={`profile-msg ${pwMsg.ok ? 'ok' : 'err'}`}>{pwMsg.text}</div>}
            <div className="prf-footer">
              <button className="btn btn-primary btn-sm" onClick={changePassword}
                disabled={pwBusy || !curPw || !newPw || !confPw || newPw !== confPw || strength < 2}>
                <PRFIcons.Lock size={13} /> {pwBusy ? 'Değiştiriliyor…' : 'Şifreyi Değiştir'}
              </button>
            </div>
          </div>

        </div>

        {/* SAĞ SÜTUN */}
        <div className="prf-col-right">

          {/* Görünüm & Ayarlar */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.Settings size={15} /> Görünüm & Ayarlar
            </h3>
            <div className="field">
              <label className="field-label">Tema</label>
              <div className="prf-toggle-row">
                {[
                  { id: 'light', label: 'Açık',  icon: <PRFIcons.Sun  size={14} /> },
                  { id: 'dark',  label: 'Koyu',  icon: <PRFIcons.Moon size={14} /> },
                ].map(t => (
                  <button key={t.id}
                    className={`prf-toggle-btn${(theme || 'light') === t.id ? ' active' : ''}`}
                    onClick={() => onSetTheme?.(t.id)}
                  >{t.icon} {t.label}</button>
                ))}
              </div>
            </div>

            <div className="field">
              <label className="field-label">Vurgu Rengi</label>
              <div className="accent-swatch-grid">
                {(window.ACCENT_PRESETS || []).map(preset => (
                  <button key={preset.id}
                    className={`accent-swatch${(accentColor||'orange') === preset.id ? ' active' : ''}`}
                    style={{ '--sw': preset.light['--accent'] }}
                    onClick={() => onSetAccentColor?.(preset.id)}
                    title={preset.name}
                  />
                ))}
              </div>
            </div>

            <div className="field">
              <label className="field-label">Varsayılan proje görünümü</label>
              <div className="prf-toggle-row">
                {[
                  { id: 'kanban', label: 'Kanban', icon: <PRFIcons.Kanban size={14} /> },
                  { id: 'list',   label: 'Liste',  icon: <PRFIcons.List   size={14} /> },
                ].map(v => (
                  <button key={v.id}
                    className={`prf-toggle-btn${defaultView === v.id ? ' active' : ''}`}
                    onClick={() => { setDefaultView(v.id); saveSettings(v.id); }}
                  >{v.icon} {v.label}</button>
                ))}
              </div>
              {settingsSaved && <div className="profile-msg ok" style={{ marginTop: 6 }}>Kaydedildi ✓</div>}
            </div>
          </div>

          {/* Dışa Aktar */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.Download size={15} /> Veri & Yedek
            </h3>
            <p className="prf-desc">Verilerinizi yedekleyin veya başka bir platforma taşıyın.</p>
            <div className="prf-export-row">
              <button className="btn btn-ghost btn-sm prf-export-item" onClick={exportJSON}>
                <PRFIcons.Download size={14} style={{ color: 'var(--accent)' }} />
                <span>JSON Yedek</span>
                <small>Tüm veri</small>
              </button>
              <button className="btn btn-ghost btn-sm prf-export-item" onClick={exportCSV}>
                <PRFIcons.FileText size={14} style={{ color: '#22c55e' }} />
                <span>CSV</span>
                <small>Excel için</small>
              </button>
              <button className="btn btn-ghost btn-sm prf-export-item"
                onClick={() => importRef.current?.click()}>
                <PRFIcons.Upload size={14} style={{ color: '#f59e0b' }} />
                <span>Geri Yükle</span>
                <small>JSON'dan</small>
              </button>
            </div>
            <input ref={importRef} type="file" accept=".json" style={{ display: 'none' }}
              onChange={e => handleImport(e.target.files?.[0])} />
            {exportMsg && (
              <div className={`profile-msg ${exportMsg.ok ? 'ok' : 'err'}`} style={{ marginTop: 8 }}>
                {exportMsg.text}
              </div>
            )}
          </div>

          {/* E-posta Bildirimleri */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.Bell size={15} /> E-posta Bildirimleri
            </h3>

            {/* Açık/Kapalı */}
            <div className="field">
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <label className="field-label" style={{margin:0}}>Günlük özet e-postası</label>
                <button
                  className={"prf-toggle-btn" + (digestEnabled ? ' active' : '')}
                  onClick={() => setDigestEnabled(v => !v)}
                  style={{minWidth:64}}
                >{digestEnabled ? 'Açık' : 'Kapalı'}</button>
              </div>
            </div>

            {digestEnabled && (<>
              {/* Saat */}
              <div className="field">
                <label className="field-label">Gönderim saati</label>
                <select className="input" style={{maxWidth:160}}
                  value={digestHour} onChange={e => setDigestHour(Number(e.target.value))}>
                  {Array.from({length:18},(_,i)=>i+5).map(h => (
                    <option key={h} value={h}>{String(h).padStart(2,'0')}:00</option>
                  ))}
                </select>
              </div>

              {/* Gecikmiş dahil et */}
              <div className="field">
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                  <label className="field-label" style={{margin:0}}>Gecikmiş görevleri dahil et</label>
                  <button
                    className={"prf-toggle-btn" + (digestIncludeOverdue ? ' active' : '')}
                    onClick={() => setDigestIncludeOverdue(v => !v)}
                    style={{minWidth:64}}
                  >{digestIncludeOverdue ? 'Evet' : 'Hayır'}</button>
                </div>
              </div>

              {/* Proje filtresi */}
              {(state?.projects||[]).filter(p=>!p.archived).length > 0 && (
                <div className="field">
                  <label className="field-label">
                    Firmalar <span className="prf-char-count">(boş = hepsi)</span>
                  </label>
                  <div style={{display:'flex',flexWrap:'wrap',gap:6,marginTop:4}}>
                    {(state?.projects||[]).filter(p=>!p.archived).map(p => {
                      const sel = digestProjects.includes(p.project_key||p.id);
                      return (
                        <button key={p.id}
                          onClick={() => setDigestProjects(prev =>
                            sel ? prev.filter(k=>k!==(p.project_key||p.id))
                                : [...prev, p.project_key||p.id]
                          )}
                          style={{
                            padding:'4px 10px',borderRadius:6,fontSize:12,fontWeight:600,
                            border:'1.5px solid',cursor:'pointer',
                            background: sel ? (p.color||'var(--accent)') : 'transparent',
                            borderColor: p.color||'var(--accent)',
                            color: sel ? '#fff' : (p.color||'var(--accent)'),
                          }}
                        >{p.name}</button>
                      );
                    })}
                  </div>
                  {digestProjects.length > 0 && (
                    <button className="btn btn-ghost btn-sm" style={{marginTop:6,fontSize:11}}
                      onClick={() => setDigestProjects([])}>Tüm firmaları seç</button>
                  )}
                </div>
              )}
            </>)}

            {digestMsg && <div className={"profile-msg " + (digestMsg.ok ? 'ok' : 'err')} style={{marginTop:8}}>{digestMsg.text}</div>}
            <div className="prf-footer">
              <button className="btn btn-primary btn-sm" onClick={saveDigest} disabled={digestBusy}>
                <PRFIcons.Save size={13} /> {digestBusy ? 'Kaydediliyor…' : 'Kaydet'}
              </button>
            </div>
          </div>

          {/* Push Bildirimleri */}
          {pushSupported && (
            <div className="card prf-section">
              <h3 className="prf-section-title">
                <PRFIcons.Bell size={15} /> Push Bildirimleri
              </h3>
              <div className="field">
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                  <label className="field-label" style={{margin:0}}>Bu cihaza push bildirimi gönder</label>
                  <button
                    className={"prf-toggle-btn" + (pushSubscribed ? ' active' : '')}
                    onClick={() => (pushSubscribed ? disablePush() : enablePush())}
                    disabled={pushBusy}
                    style={{minWidth:64}}
                  >{pushSubscribed ? 'Açık' : 'Kapalı'}</button>
                </div>
              </div>
              {pushMsg && <div className={"profile-msg " + (pushMsg.ok ? 'ok' : 'err')} style={{marginTop:8}}>{pushMsg.text}</div>}
              {pushSubscribed && (
                <div className="prf-footer">
                  <button className="btn btn-ghost btn-sm" onClick={sendTestPush} disabled={pushBusy}>
                    Deneme bildirimi gönder
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Hesap */}
          <div className="card prf-section">
            <h3 className="prf-section-title">
              <PRFIcons.User size={15} /> Hesap
            </h3>
            <div className="prf-info-list">
              <div className="prf-info-row">
                <span className="prf-info-label">E-posta</span>
                <span className="prf-info-val">{user?.email}</span>
              </div>
              <div className="prf-info-row">
                <span className="prf-info-label">Plan</span>
                <span className="prf-info-val">Bireysel</span>
              </div>
            </div>
            <div className="prf-footer" style={{ justifyContent: 'flex-start' }}>
              <button className="btn btn-ghost btn-sm" onClick={onLogout}
                style={{ color: 'var(--p-high)' }}>
                <PRFIcons.LogOut size={14} /> Çıkış Yap
              </button>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}

window.Profile = Profile;
