// Profile Page — Sayfa 7
// Profil + bütçe (bireysel & departman) + şifre değiştir + bildirim tercihleri

// ─────────── User data ───────────
const PROFILE_USER = {
  name: 'Ayşe Kaya',
  initials: 'AK',
  department: 'Finans · Raporlama & Analiz',
  position: 'Kıdemli Finansal Analist',
  email: 'ayse.kaya@sirket.com',
  phone: '+90 (5XX) 123 45 67',
  managerName: 'Mehmet Demir',
  managerTitle: 'Departman Müdürü · IT',
  joined: '03 Şubat 2022',
  employeeNo: 'EMP-08412',
  costCenter: 'CC-1402 / Finans',

  personalBudget: { limit: 50000, used: 12500 },
  yearStats: { requests: 7, approved: 5, pending: 1, rejected: 1 },

  departmentBudget: { name: 'Finans', limit: 750000, used: 462800, members: 24 },
};

const NOTIF_PREFS_DEFAULTS = {
  emailAll: true,
  inApp: true,
  onApprovalStep: true,
  onReject: true,
  onCompletion: true,
  weeklyDigest: false,
};

// ─────────── Atoms ───────────
function BudgetBar({ used, limit, c }) {
  const pct = Math.min(100, Math.round((used / limit) * 100));
  let color = c.success;
  if (pct >= 75) color = '#F59E0B';
  if (pct >= 90) color = c.danger;
  return (
    <div>
      <div style={{
        height: 10, borderRadius: 999,
        background: c.borderSoft,
        overflow: 'hidden',
        position: 'relative',
      }}>
        <div style={{
          width: pct + '%',
          height: '100%',
          background: color,
          borderRadius: 999,
          transition: 'width 600ms cubic-bezier(.4,.0,.2,1)',
        }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
        <span style={{ fontSize: 11.5, color: c.muted, fontWeight: 500 }}>{pct}% kullanıldı</span>
        <span style={{
          fontSize: 11.5, color: color, fontWeight: 600,
          letterSpacing: '0.02em',
        }}>{pct < 75 ? 'Sağlıklı' : pct < 90 ? 'Dikkat' : 'Limit yakın'}</span>
      </div>
    </div>
  );
}

function Toggle({ on, onChange, c }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      appearance: 'none', cursor: 'pointer',
      width: 38, height: 22, borderRadius: 999,
      background: on ? c.primary : c.border,
      border: 'none',
      position: 'relative',
      transition: 'background 160ms',
      flexShrink: 0,
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 18, height: 18, borderRadius: 999,
        background: '#fff',
        transition: 'left 160ms cubic-bezier(.4,.0,.2,1)',
        boxShadow: '0 1px 2px rgba(0,0,0,0.15)',
      }} />
    </button>
  );
}

// ─────────── Avatar with upload affordance ───────────
function ProfileAvatar({ user, c }) {
  return (
    <div style={{ position: 'relative', flexShrink: 0 }}>
      <div style={{
        width: 96, height: 96, borderRadius: 999,
        background: 'linear-gradient(135deg, #2563EB, #1D4ED8)',
        color: '#fff', fontSize: 32, fontWeight: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        letterSpacing: '0.02em',
        boxShadow: '0 8px 22px -8px rgba(37,99,235,0.45)',
      }}>{user.initials}</div>
      <button
        title="Profil fotoğrafını değiştir"
        onClick={() => alert('Profil fotoğrafı yükleme prototipte henüz aktif değil.')}
        style={{
        position: 'absolute', bottom: 0, right: 0,
        appearance: 'none', cursor: 'pointer',
        width: 32, height: 32, borderRadius: 999,
        background: c.surface, color: c.text,
        border: `2px solid ${c.bg}`,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 2px 6px rgba(15,23,42,0.15)',
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
          <circle cx="12" cy="13" r="4" />
        </svg>
      </button>
    </div>
  );
}

// ─────────── Hero ───────────
function ProfileHero({ user, c }) {
  return (
    <div style={{
      background: c.card, border: `1px solid ${c.border}`, borderRadius: 16,
      padding: 24,
      display: 'flex', alignItems: 'center', gap: 22,
    }}>
      <ProfileAvatar user={user} c={c} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, color: c.text, letterSpacing: '-0.01em' }}>
          {user.name}
        </h1>
        <div style={{ fontSize: 13.5, color: c.muted, marginTop: 4 }}>
          {user.position} · {user.department}
        </div>
        <div style={{ display: 'flex', gap: 18, marginTop: 14, flexWrap: 'wrap' }}>
          <HeroStat label="Bu yıl talep" value={user.yearStats.requests} c={c} />
          <HeroStat label="Onaylanan"   value={user.yearStats.approved} c={c} accent={c.success} />
          <HeroStat label="Bekleyen"    value={user.yearStats.pending}  c={c} accent="#B45309" />
          <HeroStat label="Reddedilen"  value={user.yearStats.rejected} c={c} accent={c.danger} />
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
        <button
          onClick={() => alert('Profil düzenleme prototipte henüz aktif değil.\n\nBu ekran tamamlandığında ad, telefon ve pozisyon gibi alanlar buradan güncellenecek.')}
          style={{
            appearance: 'none', cursor: 'pointer',
            padding: '9px 14px', borderRadius: 10,
            background: 'transparent', color: c.text,
            border: `1px solid ${c.border}`,
            fontSize: 12.5, fontWeight: 500, fontFamily: 'inherit',
          }}>Profili düzenle</button>
        <div style={{ fontSize: 11, color: c.subtle }}>{user.joined} tarihinde katıldı</div>
      </div>
    </div>
  );
}

function HeroStat({ label, value, c, accent }) {
  return (
    <div>
      <div style={{ fontSize: 22, fontWeight: 700, color: accent || c.text, lineHeight: 1, letterSpacing: '-0.01em' }}>
        {value}
      </div>
      <div style={{ fontSize: 11.5, color: c.muted, marginTop: 4 }}>{label}</div>
    </div>
  );
}

// ─────────── Info card (field rows) ───────────
function ProfileInfoCard({ user, c }) {
  const rows = [
    ['Ad Soyad', user.name, true],
    ['Pozisyon', user.position, true],
    ['Departman', user.department, false],
    ['Kurumsal e-posta', user.email, false],
    ['Telefon', user.phone, true],
    ['Yönetici', `${user.managerName} · ${user.managerTitle}`, false],
    ['Çalışan no', user.employeeNo, false],
    ['Maliyet merkezi', user.costCenter, false],
  ];
  return (
    <SectionCard title="Profil bilgileri" subtitle="Departman ve yönetici bilgileri İK sistemi tarafından senkronize edilir." c={c}>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {rows.map(([label, val, editable], i) => (
          <div key={label} style={{
            display: 'grid', gridTemplateColumns: '160px 1fr auto',
            gap: 16, alignItems: 'center',
            padding: '14px 0',
            borderTop: i === 0 ? 'none' : `1px solid ${c.borderSoft}`,
          }}>
            <div style={{ fontSize: 12.5, color: c.muted, fontWeight: 500 }}>{label}</div>
            <div style={{ fontSize: 13.5, color: c.text, fontFamily: label === 'Çalışan no' || label === 'Maliyet merkezi' ? 'ui-monospace, "SF Mono", Menlo, monospace' : 'inherit' }}>
              {val}
            </div>
            {editable ? (
              <button
                onClick={() => alert(`"${label}" alanı prototipte henüz düzenlenemez.\n\nBu özellik gerçek uygulamada aktif olacak.`)}
                style={editLink(c)}>Düzenle</button>
            ) : (
              <span style={{
                fontSize: 10.5, color: c.subtle, padding: '2px 6px',
                background: c.chipBg, borderRadius: 4,
                letterSpacing: '0.06em', fontWeight: 600, textTransform: 'uppercase',
              }}>İK</span>
            )}
          </div>
        ))}
      </div>
    </SectionCard>
  );
}
function editLink(c) {
  return {
    appearance: 'none', cursor: 'pointer',
    background: 'transparent', color: c.primary,
    border: 'none', padding: 0,
    fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit',
  };
}

// ─────────── Section card wrapper ───────────
function SectionCard({ title, subtitle, c, children, action }) {
  return (
    <div style={{
      background: c.card, border: `1px solid ${c.border}`, borderRadius: 14,
      padding: 22,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 14 }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: c.text }}>{title}</h3>
          {subtitle && <p style={{ margin: '4px 0 0', fontSize: 12, color: c.muted, lineHeight: 1.5 }}>{subtitle}</p>}
        </div>
        {action}
      </div>
      {children}
    </div>
  );
}

// ─────────── Personal budget card ───────────
function PersonalBudgetCard({ user, c }) {
  const b = user.personalBudget;
  const remaining = b.limit - b.used;
  return (
    <SectionCard
      title="Bireysel Bütçe"
      subtitle="2026 yıllık IT bütçeniz"
      c={c}
      action={
        <span style={{
          padding: '4px 8px', borderRadius: 4,
          background: c.chipBg, color: c.muted,
          fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em',
          textTransform: 'uppercase',
        }}>2026</span>
      }>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
        <span style={{ fontSize: 30, fontWeight: 700, color: c.text, letterSpacing: '-0.02em', lineHeight: 1 }}>
          {formatTL(remaining)}
        </span>
        <span style={{ fontSize: 13, color: c.muted }}>kullanılabilir</span>
      </div>
      <div style={{ fontSize: 12, color: c.subtle, marginBottom: 16 }}>
        {formatTL(b.limit)} yıllık limit · KDV hariç
      </div>

      <BudgetBar used={b.used} limit={b.limit} c={c} />

      <div style={{
        marginTop: 18, paddingTop: 16,
        borderTop: `1px solid ${c.borderSoft}`,
        display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14,
      }}>
        <BudgetStat label="Bu yıl kullanılan" value={formatTL(b.used)} c={c} />
        <BudgetStat label="Kalan" value={formatTL(remaining)} c={c} accent={c.success} />
      </div>

      <div style={{
        marginTop: 16,
        padding: 12,
        background: c.selectedBg,
        border: `1px solid ${c.primary}22`,
        borderRadius: 10,
        fontSize: 12, lineHeight: 1.55, color: c.selectedText,
      }}>
        Bu yıl <strong style={{ fontWeight: 700 }}>{user.yearStats.requests}</strong> talep oluşturdunuz; <strong style={{ fontWeight: 700 }}>{user.yearStats.approved}</strong> tanesi onaylandı.
        Onaylı tutar yıllık bütçenizden düşülmüştür.
      </div>
    </SectionCard>
  );
}

function BudgetStat({ label, value, c, accent }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: accent || c.text, letterSpacing: '-0.01em' }}>
        {value}
      </div>
    </div>
  );
}

// ─────────── Department budget (read-only) ───────────
function DepartmentBudgetCard({ user, c }) {
  const b = user.departmentBudget;
  const remaining = b.limit - b.used;
  return (
    <SectionCard
      title={`${b.name} Departman Bütçesi`}
      subtitle={`${b.members} çalışanın paylaştığı toplam bütçe · sadece görüntüleme`}
      c={c}
      action={
        <span style={{
          padding: '4px 8px', borderRadius: 4,
          background: c.chipBg, color: c.muted,
          fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em',
          textTransform: 'uppercase',
        }}>R/O</span>
      }>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>
            {formatTL(b.used)} <span style={{ color: c.muted, fontSize: 13, fontWeight: 500 }}>/ {formatTL(b.limit)}</span>
          </div>
          <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 4 }}>
            {formatTL(remaining)} kullanılabilir · KDV hariç
          </div>
        </div>
      </div>
      <BudgetBar used={b.used} limit={b.limit} c={c} />
    </SectionCard>
  );
}

// ─────────── Change password ───────────
function ChangePasswordCard({ c }) {
  const [cur, setCur] = React.useState('');
  const [next, setNext] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [showCur, setShowCur] = React.useState(false);
  const [showNext, setShowNext] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  const matches = next.length >= 8 && next === confirm;

  const strength =
    next.length === 0 ? 0
    : next.length < 8 ? 1
    : /[A-Z]/.test(next) && /[0-9]/.test(next) && /[^A-Za-z0-9]/.test(next) ? 4
    : /[A-Z]/.test(next) && /[0-9]/.test(next) ? 3
    : 2;
  const strLabel = ['—', 'Zayıf', 'Orta', 'İyi', 'Güçlü'][strength];
  const strColor = ['#94A3B8', '#EF4444', '#F59E0B', '#10B981', '#10B981'][strength];

  return (
    <SectionCard title="Şifre değiştir" subtitle="Son 30 günde 1 kez şifre değiştirildi · sonraki zorunlu değişim 91 gün sonra." c={c}>
      <PwField label="Mevcut şifre" value={cur} onChange={setCur} show={showCur} setShow={setShowCur} c={c} />
      <div style={{ height: 12 }} />
      <PwField label="Yeni şifre" value={next} onChange={setNext} show={showNext} setShow={setShowNext} c={c} />

      {/* Strength */}
      <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
        {[1, 2, 3, 4].map((i) => (
          <div key={i} style={{
            flex: 1, height: 4, borderRadius: 999,
            background: strength >= i ? strColor : c.borderSoft,
            transition: 'background 200ms',
          }} />
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11.5 }}>
        <span style={{ color: c.muted }}>En az 8 karakter, 1 büyük harf, 1 rakam.</span>
        <span style={{ color: strColor, fontWeight: 600 }}>{strLabel}</span>
      </div>

      <div style={{ height: 12 }} />
      <PwField label="Yeni şifre (tekrar)" value={confirm} onChange={setConfirm} show={showNext} setShow={setShowNext} c={c} error={confirm && next !== confirm ? 'Şifreler eşleşmiyor' : ''} />

      <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
        <button onClick={() => { setSaved(true); setTimeout(() => setSaved(false), 1800); setCur(''); setNext(''); setConfirm(''); }}
          disabled={!matches || saved}
          style={{
            appearance: 'none', cursor: (!matches || saved) ? 'not-allowed' : 'pointer',
            padding: '10px 18px', borderRadius: 10,
            background: saved ? c.success : (matches ? c.primary : c.borderSoft),
            color: saved || matches ? '#fff' : c.muted,
            border: 'none',
            fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            transition: 'background 160ms',
          }}>
          {saved
            ? <React.Fragment><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg> Güncellendi</React.Fragment>
            : 'Şifreyi güncelle'}
        </button>
        <button
          onClick={() => { setCur(''); setNext(''); setConfirm(''); }}
          style={{
            appearance: 'none', cursor: 'pointer',
            padding: '10px 18px', borderRadius: 10,
            background: 'transparent', color: c.text,
            border: `1px solid ${c.border}`,
            fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
          }}>Vazgeç</button>
      </div>
    </SectionCard>
  );
}

function PwField({ label, value, onChange, show, setShow, c, error }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: c.muted, marginBottom: 6 }}>{label}</label>
      <div style={{ position: 'relative' }}>
        <input
          type={show ? 'text' : 'password'}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="••••••••"
          style={{
            width: '100%', boxSizing: 'border-box',
            padding: '10px 42px 10px 12px',
            background: c.inputBg, color: c.text,
            border: `1px solid ${error ? c.danger : c.border}`,
            borderRadius: 10,
            fontSize: 13.5, fontFamily: 'inherit', outline: 'none',
            letterSpacing: show ? 'normal' : '0.12em',
            transition: 'border-color 120ms',
          }}
        />
        <button onClick={() => setShow(!show)} type="button"
          style={{
            position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
            appearance: 'none', background: 'transparent', border: 'none',
            cursor: 'pointer', color: c.muted, padding: 6, borderRadius: 6,
            display: 'inline-flex', alignItems: 'center',
          }}>
          <IconEye open={show} />
        </button>
      </div>
      {error && <div style={{ marginTop: 6, fontSize: 11.5, color: c.danger }}>{error}</div>}
    </div>
  );
}

// ─────────── Notification preferences ───────────
function NotifPrefsCard({ c }) {
  const [prefs, setPrefs] = React.useState(NOTIF_PREFS_DEFAULTS);
  const set = (k, v) => setPrefs((p) => ({ ...p, [k]: v }));

  const groups = [
    {
      title: 'Kanallar',
      desc: 'Bildirimler size hangi kanaldan ulaşsın?',
      items: [
        ['emailAll', 'E-posta bildirimleri', 'kurumsal e-postanıza özet ve önemli olaylar gönderilir'],
        ['inApp', 'Uygulama içi bildirimler', 'oturum açıkken anlık bildirimler'],
      ],
    },
    {
      title: 'Olay tetikleyicileri',
      desc: 'Hangi olaylarda bildirim almak istersiniz?',
      items: [
        ['onApprovalStep', 'Talebim onay aşaması ilerlediğinde', 'her aşama tamamlandığında'],
        ['onReject', 'Talebim reddedildiğinde', 'red gerekçesi ile birlikte'],
        ['onCompletion', 'Talebim tamamlandığında / teslim alındığında', 'satınalma tamamlandığında'],
        ['weeklyDigest', 'Haftalık özet e-postası', 'her pazartesi 09:00'],
      ],
    },
  ];

  return (
    <SectionCard
      title="Bildirim tercihleri"
      subtitle="Bildirimlerin nasıl alındığını yönetin. Değişiklikler otomatik olarak kaydedilir."
      c={c}>
      {groups.map((g, gi) => (
        <div key={g.title} style={{ marginTop: gi === 0 ? 0 : 24 }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: '0.12em',
            color: c.subtle, textTransform: 'uppercase', marginBottom: 12,
          }}>{g.title}</div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {g.items.map(([k, label, hint], i) => (
              <div key={k} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                gap: 16, padding: '12px 0',
                borderTop: i === 0 ? 'none' : `1px solid ${c.borderSoft}`,
              }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 500, color: c.text }}>{label}</div>
                  <div style={{ fontSize: 12, color: c.muted, marginTop: 3 }}>{hint}</div>
                </div>
                <Toggle on={prefs[k]} onChange={(v) => set(k, v)} c={c} />
              </div>
            ))}
          </div>
        </div>
      ))}
    </SectionCard>
  );
}

// ─────────── MAIN PAGE ───────────
function ProfilePage({ initialDark = false }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);

  const [headerSearch, setHeaderSearch] = React.useState('');
  const c = catalogTheme(dark);
  const user = PROFILE_USER;

  return (
    <div style={{
      width: '100%', height: '100%',
      background: c.bg, color: c.text,
      fontFamily: 'Inter, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      <CatalogHeader
        c={c} dark={dark}
        onToggleDark={() => setDark((x) => !x)}
        search={headerSearch} setSearch={setHeaderSearch}
        cartCount={0} notifCount={3}
      />

      <div style={{ padding: '28px 32px 40px', maxWidth: 1100, margin: '0 auto', width: '100%', boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: c.muted, marginBottom: 14 }}>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Hesabım</a>
          <span style={{ color: c.subtle }}>/</span>
          <span style={{ color: c.text, fontWeight: 500 }}>Profilim</span>
        </div>

        <ProfileHero user={user} c={c} />

        {/* 2-col grid */}
        <div style={{
          marginTop: 18,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18,
          alignItems: 'flex-start',
        }}>
          <ProfileInfoCard user={user} c={c} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <PersonalBudgetCard user={user} c={c} />
            <DepartmentBudgetCard user={user} c={c} />
          </div>
        </div>

        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, alignItems: 'flex-start' }}>
          <ChangePasswordCard c={c} />
          <NotifPrefsCard c={c} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ProfilePage, PROFILE_USER, NOTIF_PREFS_DEFAULTS,
  BudgetBar, Toggle, ProfileAvatar, ProfileHero, ProfileInfoCard,
  PersonalBudgetCard, DepartmentBudgetCard, ChangePasswordCard, NotifPrefsCard,
  SectionCard,
});
