// Profile — gamified identity, progress, and achievement surface.

const profileStyles = {
  scroll: { height: '100%', overflow: 'auto', direction: 'rtl', padding: '0 16px 160px' },
  hero: {
    position: 'relative', overflow: 'hidden',
    background: 'linear-gradient(135deg, var(--surface-invert), rgba(0,106,96,0.90))',
    color: 'var(--fg-on-invert)',
    border: '1px solid rgba(255,255,255,0.10)',
    borderRadius: 22, padding: 18, margin: '4px 0 16px',
    boxShadow: 'var(--shadow-ink), var(--shadow-press)',
  },
  motif: {
    position: 'absolute', insetInlineEnd: -34, top: -42,
    width: 180, height: 180, opacity: 0.10, pointerEvents: 'none',
  },
  avatar: {
    width: 64, height: 64, borderRadius: 18,
    background: 'var(--firoozeh)', color: '#fff',
    display: 'grid', placeItems: 'center',
    font: "800 26px 'Estedad', sans-serif",
    boxShadow: '0 10px 28px rgba(0,0,0,0.20)',
    flexShrink: 0,
  },
  heroName: { font: "700 21px/1.4 'Estedad', sans-serif", color: 'var(--fg-on-invert)' },
  heroMeta: { font: "400 12.5px/1.8 'Estedad', sans-serif", color: 'var(--label-on-invert)', marginTop: 3 },
  heroActions: { display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' },
  pillBtn: {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
    borderRadius: 999, padding: '9px 13px',
    font: "600 12.5px 'Estedad', sans-serif",
    border: '1px solid rgba(255,255,255,0.18)',
    background: 'rgba(255,255,255,0.10)', color: 'var(--fg-on-invert)',
    cursor: 'pointer',
    boxShadow: 'var(--shadow-press)',
    backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
    transition: 'transform var(--dur-micro) var(--ease-out), background var(--dur-micro) var(--ease-out), border-color var(--dur-micro) var(--ease-out)',
  },
  primaryPill: { background: 'var(--firoozeh)', borderColor: 'transparent', color: '#fff' },
  sectionHead: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
    padding: '0 4px', margin: '18px 0 10px',
  },
  sectionTitle: { font: "700 15px 'Estedad', sans-serif", color: 'var(--ink)' },
  sectionMeta: { font: "500 11.5px 'Estedad', sans-serif", color: 'var(--ink-3)' },
  progressCard: {
    background: 'var(--surface-glass)', border: '1px solid var(--c-border-xs)',
    borderRadius: 18, padding: 16, boxShadow: 'var(--shadow-lift), var(--shadow-press)', marginBottom: 14,
    backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
  },
  statGrid: { display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 8, marginBottom: 14 },
  stat: {
    background: 'var(--surface-glass)', border: '1px solid var(--c-border-xs)',
    borderRadius: 14, padding: '12px 13px', minHeight: 68,
    boxShadow: 'var(--shadow-press)',
  },
  statValue: { font: "800 20px 'Estedad', sans-serif", color: 'var(--ink)' },
  statLabel: { font: "500 11.5px/1.5 'Estedad', sans-serif", color: 'var(--ink-3)', marginTop: 3 },
  week: { display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 7, alignItems: 'end', height: 78, marginTop: 12 },
  weekCol: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 },
  weekBar: { width: '100%', borderRadius: 7, background: 'var(--firoozeh)', minHeight: 6 },
  weekBarEmpty: { background: 'var(--paper-2)' },
  weekLabel: { font: "600 10.5px 'Estedad', sans-serif", color: 'var(--ink-3)' },
  badgeGrid: { display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 10 },
  badge: {
    background: 'var(--surface-glass)', border: '1px solid var(--c-border-xs)',
    borderRadius: 16, padding: 13, minHeight: 118,
    display: 'grid', alignContent: 'space-between', gap: 10,
    boxShadow: 'var(--shadow-press)',
    transition: 'transform var(--dur-micro) var(--ease-out), border-color var(--dur-micro) var(--ease-out), opacity var(--dur-micro) var(--ease-out)',
  },
  badgeIcon: {
    width: 38, height: 38, borderRadius: 12,
    display: 'grid', placeItems: 'center',
  },
  badgeTitle: { font: "700 13px/1.4 'Estedad', sans-serif", color: 'var(--ink)' },
  badgeDesc: { font: "400 11.5px/1.7 'Estedad', sans-serif", color: 'var(--ink-3)', marginTop: 2 },
  inputRow: { display: 'flex', gap: 8, marginTop: 12 },
  input: {
    flex: 1, minWidth: 0, boxSizing: 'border-box',
    background: 'rgba(255,255,255,0.10)', color: 'var(--fg-on-invert)',
    border: '1px solid rgba(255,255,255,0.18)', borderRadius: 12,
    padding: '10px 12px', outline: 'none',
    font: "500 14px 'Estedad', sans-serif",
  },
};

const _pfa = n => String(n ?? 0).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
const _pDayKey = d => [d.getFullYear(), String(d.getMonth()+1).padStart(2,'0'), String(d.getDate()).padStart(2,'0')].join('-');
const _pDone = t => t.done || t.status === 'done';
const _pOpen = t => t.status !== 'cancelled' && !_pDone(t);

function Profile({ profile, gamify, tasks = [], knowledge = [], finances = [], account,
                   onUpdateProfile, onOpenSettings, onOpenAuth, onSignOut, onGoto,
                   isDesktop }) {
  const { Icons } = window;
  const asset = window.assetPath || ((name) => `assets/${name}`);
  const [editing, setEditing] = React.useState(false);
  const [nameDraft, setNameDraft] = React.useState(profile?.name || '');

  React.useEffect(() => setNameDraft(profile?.name || ''), [profile?.name]);

  const name = (profile?.name || account?.user?.name || 'کاربر لاگی').trim();
  const avatar = (profile?.avatar || name[0] || 'ل').trim()[0] || 'ل';
  const totalTasks = tasks.filter(t => t.status !== 'cancelled').length;
  const doneTasks = tasks.filter(t => t.status !== 'cancelled' && _pDone(t)).length;
  const openTasks = tasks.filter(_pOpen).length;
  const completionPct = totalTasks ? Math.round((doneTasks / totalTasks) * 100) : 0;
  const todayKey = _pDayKey(new Date());
  const todayTasks = tasks.filter(t => t.status !== 'cancelled' && (t.dueDate === todayKey || (!t.dueDate && t.section === 'today')));
  const todayWins = Math.max(todayTasks.filter(_pDone).length, gamify?.todayDoneCount || 0);
  const days = gamify?.days || {};
  const dayFmt = new Intl.DateTimeFormat('fa-IR', { weekday: 'short' });
  const week = Array.from({ length: 7 }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - (6 - i));
    const key = _pDayKey(d);
    return { key, label: dayFmt.format(d).slice(0, 1), n: Number(days[key]) || 0 };
  });
  const weekMax = Math.max(1, ...week.map(d => d.n));
  const weekTotal = week.reduce((sum, d) => sum + d.n, 0);

  const achievements = [
    { id: 'first', title: 'اولین برد', desc: 'اولین کار را کامل کردی', Icon: Icons.CheckCircle, on: doneTasks >= 1 },
    { id: 'focus', title: 'تمرکز سه‌تایی', desc: 'سه کار در یک روز', Icon: Icons.Bolt, on: Object.values(days).some(n => Number(n) >= 3) },
    { id: 'streak3', title: 'زنجیره روشن', desc: 'سه روز پشت‌سرهم', Icon: Icons.Flame, on: (gamify?.bestStreak || 0) >= 3 },
    { id: 'streak7', title: 'هفته کامل', desc: 'هفت روز پیوسته', Icon: Icons.Flame, on: (gamify?.bestStreak || 0) >= 7 },
    { id: 'level3', title: 'سطح منظم', desc: 'رسیدن به سطح ۳', Icon: Icons.Star, on: (gamify?.level || 1) >= 3 },
    { id: 'builder', title: 'سازنده عادت', desc: '۵۰ کار کامل‌شده', Icon: Icons.Sparkle, on: doneTasks >= 50 },
    { id: 'memory', title: 'حافظه فعال', desc: '۱۰ کارت حافظه', Icon: Icons.Book, on: knowledge.length >= 10 },
    { id: 'money', title: 'چرتکه‌دار', desc: '۱۰ رویداد مالی', Icon: Icons.Wallet, on: finances.length >= 10 },
  ];
  const unlocked = achievements.filter(a => a.on).length;

  const saveName = () => {
    const n = nameDraft.trim();
    if (n && n !== profile?.name && onUpdateProfile) onUpdateProfile({ name: n });
    setEditing(false);
  };

  const scrollStyle = { ...profileStyles.scroll, padding: isDesktop ? '0 24px 48px' : '0 16px 180px' };

  return (
    <div className="sb-flow" style={scrollStyle}>
      <div className="sb-gamify-card sb-animated-card" style={profileStyles.hero}>
        <img src={asset('shamse-pattern.svg')} style={profileStyles.motif} alt="" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, position: 'relative' }}>
          <div className="sb-xp-orb" style={profileStyles.avatar}>{avatar}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={profileStyles.heroName}>{name}</div>
            <div style={profileStyles.heroMeta}>
              سطح {_pfa(gamify?.level || 1)} · {gamify?.title || 'تازه‌کار'} · {_pfa(gamify?.xp || 0)} XP
            </div>
            <div style={profileStyles.heroMeta}>
              {account?.user ? (account.user.phone || account.user.email || 'حساب همگام‌سازی فعال') : 'داده‌ها روی همین دستگاه ذخیره می‌شوند'}
            </div>
          </div>
        </div>

        {editing && (
          <div style={profileStyles.inputRow}>
            <input
              style={profileStyles.input}
              value={nameDraft}
              onChange={e => setNameDraft(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && saveName()}
              maxLength={30}
              autoFocus
            />
            <button className="sb-lift-button" style={{ ...profileStyles.pillBtn, ...profileStyles.primaryPill }} onClick={saveName}>ثبت</button>
          </div>
        )}

        <div style={profileStyles.heroActions}>
          <button className="sb-lift-button" style={{ ...profileStyles.pillBtn, ...profileStyles.primaryPill }} onClick={() => setEditing(v => !v)}>
            <Icons.Edit size={14} /> ویرایش نام
          </button>
          {account?.user ? (
            <button className="sb-lift-button" style={profileStyles.pillBtn} onClick={onSignOut}>
              <Icons.X size={14} /> خروج
            </button>
          ) : (
            <button className="sb-lift-button" style={profileStyles.pillBtn} onClick={onOpenAuth}>
              <Icons.User size={14} /> ورود
            </button>
          )}
          <button className="sb-lift-button" style={profileStyles.pillBtn} onClick={onOpenSettings}>
            <Icons.Gear size={14} /> تنظیمات
          </button>
        </div>
      </div>

      <div className="sb-gamify-card sb-animated-card" style={profileStyles.progressCard}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
          <div>
            <div style={{ font: "700 15px 'Estedad', sans-serif", color: 'var(--ink)' }}>مسیر سطح بعدی</div>
            <div style={{ font: "400 12px 'Estedad', sans-serif", color: 'var(--ink-3)', marginTop: 2 }}>
              {_pfa(gamify?.into || 0)} از {_pfa(gamify?.need || 100)} XP
            </div>
          </div>
          <div style={{ font: "800 22px 'Estedad', sans-serif", color: 'var(--firoozeh-deep)' }}>{_pfa(gamify?.pct || 0)}٪</div>
        </div>
        <div className="sb-progress-track" style={{ height: 9, borderRadius: 999, background: 'var(--paper-2)', overflow: 'hidden', marginTop: 12 }}>
          <div className="sb-progress-bar" style={{ height: '100%', width: `${gamify?.pct || 0}%`, borderRadius: 999, background: 'var(--firoozeh)', transition: 'width 400ms ease' }} />
        </div>
      </div>

      <div style={profileStyles.statGrid}>
        <ProfileStat value={gamify?.streak || 0} label="روز پیوسته" Icon={Icons.Flame} tone="var(--saffron)" />
        <ProfileStat value={gamify?.bestStreak || 0} label="بهترین زنجیره" Icon={Icons.Star} tone="var(--firoozeh)" />
        <ProfileStat value={todayWins} label="برد امروز" Icon={Icons.CheckCircle} tone="var(--moss)" />
        <ProfileStat value={doneTasks} label="کار کامل‌شده" Icon={Icons.Bolt} tone="var(--garnet)" />
        <ProfileStat value={completionPct} suffix="٪" label="نرخ تکمیل" Icon={Icons.TrendUp} tone="var(--firoozeh)" />
        <ProfileStat value={openTasks} label="کار باز" Icon={Icons.Clock} tone="var(--ink-3)" />
      </div>

      <div style={profileStyles.sectionHead}>
        <div style={profileStyles.sectionTitle}>فعالیت هفته</div>
        <div style={profileStyles.sectionMeta}>{_pfa(weekTotal)} برد</div>
      </div>
      <div className="sb-animated-card" style={profileStyles.progressCard}>
        <div style={profileStyles.week}>
          {week.map(d => (
            <div key={d.key} style={profileStyles.weekCol}>
              <span style={{ font: "600 10.5px 'Estedad', sans-serif", color: 'var(--ink-3)' }}>{d.n ? _pfa(d.n) : '\u00A0'}</span>
              <span className="sb-week-bar" style={{
                ...profileStyles.weekBar,
                ...(d.n ? {} : profileStyles.weekBarEmpty),
                height: `${Math.max(6, (d.n / weekMax) * 48)}px`,
              }} />
              <span style={profileStyles.weekLabel}>{d.label}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={profileStyles.sectionHead}>
        <div style={profileStyles.sectionTitle}>نشان‌ها</div>
        <div style={profileStyles.sectionMeta}>{_pfa(unlocked)} از {_pfa(achievements.length)}</div>
      </div>
      <div className="sb-flow" style={profileStyles.badgeGrid}>
        {achievements.map(a => (
          <Achievement key={a.id} item={a} />
        ))}
      </div>

      <div style={profileStyles.sectionHead}>
        <div style={profileStyles.sectionTitle}>میانبرها</div>
      </div>
      <div className="sb-animated-card" style={{ ...profileStyles.progressCard, display: 'grid', gap: 8 }}>
        <QuickRow Icon={Icons.CheckCircle} title="کارهای امروز" meta={`${_pfa(todayWins)} برد ثبت شده`} onClick={() => onGoto('tasks')} />
        <QuickRow Icon={Icons.Book} title="حافظه" meta={`${_pfa(knowledge.length)} کارت`} onClick={() => onGoto('knowledge')} />
        <QuickRow Icon={Icons.Wallet} title="چرتکه" meta={`${_pfa(finances.length)} رویداد`} onClick={() => onGoto('finance')} />
      </div>
    </div>
  );
}

function ProfileStat({ value, suffix = '', label, Icon, tone }) {
  return (
    <div className="sb-stat-card sb-animated-card" style={profileStyles.stat}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <div style={profileStyles.statValue}>{_pfa(value)}{suffix}</div>
        <span style={{ color: tone, display: 'grid', placeItems: 'center' }}><Icon size={18} /></span>
      </div>
      <div style={profileStyles.statLabel}>{label}</div>
    </div>
  );
}

function Achievement({ item }) {
  const Icon = item.Icon;
  return (
    <div className={`${item.on ? 'sb-badge-unlocked' : 'sb-badge-locked'} sb-animated-card`} style={{
      ...profileStyles.badge,
      opacity: item.on ? 1 : 0.56,
      borderColor: item.on ? 'rgba(42,157,143,0.24)' : 'var(--c-border-xs)',
    }}>
      <div style={{
        ...profileStyles.badgeIcon,
        background: item.on ? 'var(--firoozeh-soft)' : 'var(--paper-2)',
        color: item.on ? 'var(--firoozeh-deep)' : 'var(--ink-4)',
      }}>
        <Icon size={18} />
      </div>
      <div>
        <div style={profileStyles.badgeTitle}>{item.title}</div>
        <div style={profileStyles.badgeDesc}>{item.desc}</div>
      </div>
      <div style={{ font: "700 11px 'Estedad', sans-serif", color: item.on ? 'var(--moss)' : 'var(--ink-4)' }}>
        {item.on ? 'باز شده' : 'قفل'}
      </div>
    </div>
  );
}

function QuickRow({ Icon, title, meta, onClick }) {
  return (
    <button
      className="sb-lift-button"
      style={{
        width: '100%', display: 'grid', gridTemplateColumns: 'auto 1fr auto', alignItems: 'center', gap: 10,
        background: 'var(--surface-glass)', border: '1px solid var(--c-border-xs)', borderRadius: 12, padding: '10px 12px',
        color: 'var(--ink)', textAlign: 'right', cursor: 'pointer',
        boxShadow: 'var(--shadow-press)',
        transition: 'transform var(--dur-micro) var(--ease-out), background var(--dur-micro) var(--ease-out)',
      }}
      onClick={onClick}
    >
      <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--paper-2)', color: 'var(--firoozeh-deep)', display: 'grid', placeItems: 'center' }}>
        <Icon size={16} />
      </span>
      <span>
        <span style={{ display: 'block', font: "700 13px 'Estedad', sans-serif", color: 'var(--ink)' }}>{title}</span>
        <span style={{ display: 'block', font: "400 11.5px 'Estedad', sans-serif", color: 'var(--ink-3)', marginTop: 2 }}>{meta}</span>
      </span>
      <span style={{ color: 'var(--ink-3)' }}>‹</span>
    </button>
  );
}

window.Profile = Profile;
