// profile-app.jsx — Mounts the Profile design canvas + Tweaks panel.
//
// Sprint v1.7 · Profile. Mobile-first 420px + Desktop 1400px on the
// canonical baseline §12 chrome + the page-specific Profile primitives
// from profile-pieces.jsx (PfIcon / ProfileHero / StatCard / MenuRow /
// ProfileEditField).
//
// The Logout confirm modal is built on `MyCardsDetailModal layout="dialog"`
// (v1.7 additive) — the same canonical pattern as PredictionMatchSheet
// (sheetCustom §14.0) and PackDetailSheet (Shop v1.5).
//
// Artboards in DesignCanvas (minimum per spec):
//   Mobile Default · Desktop Default · Edit Profile · Logout Modal ·
//   FA / EN / AR locale switch

const { useState: pfaUseState, useEffect: pfaUseEffect,
        useRef: pfaUseRef, useMemo: pfaUseMemo } = React;


// ─── micro-helpers ─────────────────────────────────────────────────────────
const _pfaT = (n, locale) =>
  (window.toLocaleDigits ? window.toLocaleDigits(n, locale) : String(n));

const _pfaFmt = (n, locale) =>
  _pfaT((typeof n === 'number' ? n : 0).toLocaleString('en-US'), locale);


// ─── ProfilePhone — artboard phone frame ──────────────────────────────────
function ProfilePhone({ w = 420, h = 920, children }) {
  return (
    <div className="pf-phone" style={{ width: w, height: h }}>
      <div className="pf-phone-inner">{children}</div>
    </div>
  );
}


// ─── PfPageBar ────────────────────────────────────────────────────────────
// Secondary-screen app bar: back button + centered title + inline-end action.
// Distinct from the Home Hub AppBar (which is for main-tab screens with
// avatar / coin / XP). Profile is a secondary screen navigated to via avatar
// tap, so it needs a simpler page-level header. Follows §13.1 glass surface.
//
// The back chevron points in the logical "back" direction:
//   RTL (fa / ar): points right (→) — matches wireframe §S14
//   LTR (en):       points left  (←)
//
// Props
//   locale   — 'fa' | 'en' | 'ar'
//   title    — string
//   onBack   — fn | null
//   action   — ReactElement | null — rendered in inline-end slot
function PfPageBar({ locale = 'fa', title = '', onBack, action }) {
  const ll = window.PROF_I18N?.[locale] || {};
  const isLTR = locale === 'en';
  return (
    <div className="pf-appbar">
      <button type="button" className="pf-appbar-back"
              onClick={onBack}
              aria-label={ll.appBarBack || 'Back'}>
        {window.HHIcon
          ? <window.HHIcon name="chevron" size={20}
              style={{ transform: isLTR ? 'scaleX(-1)' : 'none' }}/>
          : '→'}
      </button>
      <span className="pf-appbar-title">{title}</span>
      <div className="pf-appbar-actions">{action}</div>
    </div>
  );
}


// ─── LogoutConfirmModal ───────────────────────────────────────────────────
// Centered small modal — Wireframes §S39.
// Built on `MyCardsDetailModal layout="dialog"` (v1.7 additive layout).
// The "danger circle !" icon, title, description, and two buttons all live
// in the `body` slot; no separate header/footer needed.
//
// Props
//   open      — bool
//   onClose   — fn — also wired to "انصراف"
//   onConfirm — fn — wired to "خروج"
//   locale    — 'fa' | 'en' | 'ar'
//   inline    — bool — true in artboard mode (position:absolute; not portal)
function LogoutConfirmModal({ open, onClose, onConfirm, locale = 'fa', inline = false }) {
  if (!open) return null;
  const ll = window.PROF_I18N?.[locale] || {};
  if (!window.MyCardsDetailModal) return null;

  const body = (
    <div className="pf-logout">
      {/* danger icon circle */}
      <div className="pf-logout-icon-wrap" aria-hidden="true">
        <span className="pf-logout-icon">!</span>
      </div>
      <h2 className="pf-logout-title">{ll.logoutTitle}</h2>
      <p className="pf-logout-desc">{ll.logoutBody}</p>
      <div className="pf-logout-actions">
        {/* انصراف — accent gradient (§13.9 CTA) */}
        <button type="button" className="pf-logout-cancel" onClick={onClose}>
          {ll.logoutCancel}
        </button>
        {/* خروج — danger outline */}
        <button type="button" className="pf-logout-confirm" onClick={onConfirm}>
          {ll.logoutConfirm}
        </button>
      </div>
    </div>
  );

  return (
    <window.MyCardsDetailModal
      open={open}
      layout="dialog"
      locale={locale}
      onClose={onClose}
      inline={inline}
      body={body}
    />
  );
}


// ─── EditProfileScreen ────────────────────────────────────────────────────
// §S38 — rendered as a standalone artboard, not a route/modal.
// Contains: page bar (back + "ویرایش پروفایل" + "ذخیره") +
//           centered avatar 96px + camera button + change link +
//           5 read-only form fields + "حذف حساب کاربری" danger button.
function EditProfileScreen({
  locale    = 'fa',
  user      = window.PROF_USER,
  onBack,
}) {
  if (!user) return null;
  const ll = window.PROF_I18N?.[locale] || {};

  const PEF  = window.ProfileEditField;
  const PH   = window.ProfileHero;
  const TC   = window.TeamCrest;

  const saveBtn = (
    <button type="button" className="pf-appbar-save">{ll.editSave}</button>
  );

  return (
    <div className="pf-screen">
      <PfPageBar locale={locale} title={ll.editTitle} action={saveBtn} onBack={onBack}/>

      <div className="pf-screen-scroll">
        <div className="pf-body pf-body--edit">
          {/* Avatar area — centered */}
          <div className="pf-edit-avatar-section">
            <div className="pf-edit-avatar-wrap" style={{ position: 'relative', display: 'inline-block' }}>
              {/* 96px avatar */}
              <span className="pf-avatar pf-avatar--initials"
                    style={{
                      width: 96, height: 96,
                      background: (() => {
                        const pal = (typeof window.resolveAvatarPalette === 'function')
                          ? window.resolveAvatarPalette(user.avatarSeed || '')
                          : { from: 'var(--accent-primary)', to: 'var(--accent-primary-2)' };
                        return `linear-gradient(150deg, ${pal.from} 0%, ${pal.to} 100%)`;
                      })(),
                    }}>
                <span className="pf-avatar-glyph" style={{ fontSize: 34 }}>
                  {(user.avatarInitial && (user.avatarInitial[locale] || user.avatarInitial.fa)) || '?'}
                </span>
              </span>
              {/* Camera button — absolute, inline-start bottom */}
              <button type="button" className="pf-edit-camera-btn"
                      aria-label={ll.editCameraAria}>
                {window.HHIcon
                  ? <window.HHIcon name="plus" size={13}/>
                  : '+'}
              </button>
            </div>
            <a href="#" className="pf-edit-change-link" onClick={(e) => e.preventDefault()}>
              {ll.editChangeAvatar}
            </a>
          </div>

          {/* Form fields */}
          <div className="pf-edit-fields">
            {PEF && <>
              <PEF label={ll.editFieldUsername}
                   value={user.username || '@keyvan'}/>
              <PEF label={ll.editFieldDisplayName}
                   value={user.displayName?.[locale] || user.displayName?.fa || ''}/>
              <PEF label={ll.editFieldFavoriteTeam}
                   value={user.favoriteTeam?.name?.[locale] || ''}
                   leading={TC
                     ? <TC team={user.favoriteTeam?.code || 'PER'}
                            size={22}
                            layout="inline"/>
                     : null}/>
              <PEF label={ll.editFieldEmail}
                   value={user.emailMasked || ''}
                   action={{ label: ll.editEmailAction, onClick: () => {} }}/>
              <PEF label={ll.editFieldPhone}
                   value={(user.phoneMasked && user.phoneMasked[locale]) || ''}
                   verified={true}
                   verifiedLabel={ll.editPhoneVerified}/>
            </>}
          </div>

          {/* Danger zone */}
          <div className="pf-edit-danger">
            <button type="button" className="pf-edit-delete-btn"
                    aria-label={ll.editDeleteAria}>
              {ll.editDeleteAccount}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}


// ─── ProfileMobile ────────────────────────────────────────────────────────
// Mobile 420px layout — §S14. Layout (top → bottom):
//
//   PfPageBar (sticky)                   ← back + "پروفایل" + "ویرایش" pill
//   ┌─ scroll ────────────────────────────────────────────────────────────┐
//   │  ProfileHero (variant='hero')       ← avatar 80px + name + XP bar  │
//   │  pf-stats-grid (2-col)              ← 6 StatCards                  │
//   │  SectionHead "منو"                                                  │
//   │  pf-menu-group                      ← 5 MenuRows                   │
//   │  pf-footer                          ← version                      │
//   └─────────────────────────────────────────────────────────────────────┘
//
// Props
//   locale         — 'fa' | 'en' | 'ar'
//   user           — PROF_USER shape (defaults to window.PROF_USER)
//   onEdit         — fn — called by ویرایش pill (navigation only in canvas)
//   onMenuTap      — fn(item) — called by MenuRow taps
//   logoutOpen     — bool — whether the logout modal is visible
//   onLogoutClose  — fn
function ProfileMobile({
  locale       = 'fa',
  user         = window.PROF_USER,
  onBack,
  onEdit,
  onMenuTap,
  logoutOpen   = false,
  onLogoutClose,
  inline       = false,
}) {
  if (!user) return null;
  const ll  = window.PROF_I18N?.[locale] || {};
  const PH  = window.ProfileHero;
  const SC  = window.StatCard;
  const MR  = window.MenuRow;
  const SH  = window.SectionHead;
  const MI  = window.PROF_MENU_ITEMS || [];

  const statDefs = [
    { key: 'statLevel',        value: user.level },
    { key: 'statTotalXP',      value: user.totalXP },
    { key: 'statTotalCoins',   value: user.totalCoins },
    { key: 'statLineupsCount', value: user.lineupsCount },
    { key: 'statPacksOpened',  value: user.packsOpened },
    { key: 'statActiveCards',  value: user.activeCards },
  ];

  const handleMenuTap = (item) => {
    if (item.key === 'logout') { onLogoutClose && onLogoutClose('open'); return; }
    onMenuTap && onMenuTap(item);
  };

  const editPill = (
    <button type="button" className="pf-appbar-pill" onClick={onEdit}>
      {ll.editPill}
    </button>
  );

  return (
    <div className="pf-screen">
      <PfPageBar locale={locale} title={ll.pageTitle} action={editPill} onBack={onBack}/>

      <div className="pf-screen-scroll">
        <div className="pf-body">
          {/* Hero */}
          {PH && <PH user={user} locale={locale} variant="hero"/>}

          {/* Stat grid */}
          <div className="pf-stats-grid">
            {SC && statDefs.map(({ key, value }) => (
              <SC key={key}
                  label={ll[key] || key}
                  value={_pfaFmt(value, locale)}/>
            ))}
          </div>

          {/* Menu */}
          <div className="pf-menu-section">
            {SH && <SH title={ll.menuSection}/>}
            <div className="pf-menu-group">
              {MI.map((item) => (
                MR && (
                  <MR key={item.key}
                      item={item}
                      label={ll[`menu${item.key.charAt(0).toUpperCase() + item.key.slice(1)}`]
                             || item.key}
                      locale={locale}
                      onClick={handleMenuTap}/>
                )
              ))}
            </div>
          </div>

          {/* Footer version */}
          <div className="pf-footer">
            <span className="pf-footer-version">
              {ll.version?.(window.PROF_VERSION || '1.0.0')}
            </span>
          </div>
        </div>
      </div>

      {/* Logout confirm — inline so it stays inside the phone artboard */}
      <LogoutConfirmModal
        open={logoutOpen}
        onClose={onLogoutClose}
        onConfirm={() => { onLogoutClose && onLogoutClose(); }}
        locale={locale}
        inline={inline}
      />
    </div>
  );
}


// ─── ProfileDesktop ───────────────────────────────────────────────────────
// Desktop 1400px layout — sidebar + main content.
//
//   DesktopTopbar (sticky)
//   ┌─ pf-desktop-wrap (lb-desktop-wrap pattern) ──────────────────────────┐
//   │  pf-desktop-scroll                                                    │
//   │    pf-desktop (grid: main 1fr + side 320px)                          │
//   │      aside.pf-desktop-side                                           │
//   │        ProfileHero (variant='sidebar')                               │
//   │        pf-stats-grid                ← 6 StatCards                   │
//   │      main.pf-desktop-main                                            │
//   │        SectionHead "منو"                                              │
//   │        pf-menu-group                ← 5 MenuRows                    │
//   │        pf-footer                   ← version                        │
//   │  LogoutConfirmModal (inline)                                         │
//   └───────────────────────────────────────────────────────────────────────┘
function ProfileDesktop({
  locale      = 'fa',
  user        = window.PROF_USER,
  onEdit,
  onMenuTap,
  logoutOpen  = false,
  onLogoutClose,
}) {
  if (!user) return null;
  const ll  = window.PROF_I18N?.[locale] || {};
  const PH  = window.ProfileHero;
  const SC  = window.StatCard;
  const MR  = window.MenuRow;
  const SH  = window.SectionHead;
  const DT  = window.DesktopTopbar;
  const MI  = window.PROF_MENU_ITEMS || [];

  const statDefs = [
    { key: 'statLevel',        value: user.level },
    { key: 'statTotalXP',      value: user.totalXP },
    { key: 'statTotalCoins',   value: user.totalCoins },
    { key: 'statLineupsCount', value: user.lineupsCount },
    { key: 'statPacksOpened',  value: user.packsOpened },
    { key: 'statActiveCards',  value: user.activeCards },
  ];

  const handleMenuTap = (item) => {
    if (item.key === 'logout') { onLogoutClose && onLogoutClose('open'); return; }
    onMenuTap && onMenuTap(item);
  };

  return (
    <div className="pf-desktop-wrap">
      <div className="pf-desktop-screen">
        {DT && <DT locale={locale} user={{
          ...(window.HH_USER || {}),
          level: user.level,
          coinBalance: user.totalCoins || 0,
          avatarInitial: typeof user.avatarInitial === 'object'
            ? (user.avatarInitial[locale] || user.avatarInitial.fa || '?')
            : (user.avatarInitial || '?'),
        }}/>}

        <div className="pf-desktop-scroll">
          <div className="pf-desktop">
            {/* ── Sidebar ── */}
            <aside className="pf-desktop-side">
              {PH && <PH user={user} locale={locale} variant="sidebar"/>}
              <div className="pf-stats-grid pf-stats-grid--sidebar">
                {SC && statDefs.map(({ key, value }) => (
                  <SC key={key}
                      label={ll[key] || key}
                      value={_pfaFmt(value, locale)}/>
                ))}
              </div>
            </aside>

            {/* ── Main ── */}
            <main className="pf-desktop-main">
              <div className="pf-menu-section">
                {SH && <SH title={ll.menuSection}/>}
                <div className="pf-menu-group pf-menu-group--desktop">
                  {MI.map((item) => (
                    MR && (
                      <MR key={item.key}
                          item={item}
                          label={ll[`menu${item.key.charAt(0).toUpperCase() + item.key.slice(1)}`]
                                 || item.key}
                          locale={locale}
                          onClick={handleMenuTap}/>
                    )
                  ))}
                </div>
              </div>
              <div className="pf-footer">
                <span className="pf-footer-version">
                  {ll.version?.(window.PROF_VERSION || '1.0.0')}
                </span>
              </div>
            </main>
          </div>
        </div>
      </div>

      {/* Logout confirm — inline so it stays inside the artboard frame */}
      <LogoutConfirmModal
        open={logoutOpen}
        onClose={onLogoutClose}
        onConfirm={() => { onLogoutClose && onLogoutClose(); }}
        locale={locale}
        inline={true}
      />
    </div>
  );
}


// ─── App shell ────────────────────────────────────────────────────────────
const PF_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "locale": "fa"
}/*EDITMODE-END*/;

function ProfileApp() {
  const [t, setTweak] = useTweaks(PF_TWEAK_DEFAULTS);

  // Artboard-level logout state — one per artboard that shows the modal
  const [mobileLogout,  setMobileLogout]  = pfaUseState(false);
  const [desktopLogout, setDesktopLogout] = pfaUseState(false);

  pfaUseEffect(() => {
    document.documentElement.lang = t.locale;
    document.documentElement.dir  = t.locale === 'en' ? 'ltr' : 'rtl';
  }, [t.locale]);

  return (
    <React.Fragment>
      <DesignCanvas>

        {/* ══ Section 1 — Mobile ══════════════════════════════════════════ */}
        <DCSection id="mobile-profile"
                   title="Mobile · پروفایل (موبایل ۴۲۰)"
                   subtitle="§S14 — AppBar back + hero + stat grid + menu + version footer">
          <DCArtboard id="m-default" label="A · Default" width={420} height={960}>
            <ProfilePhone w={420} h={960}>
              <ProfileMobile locale={t.locale} inline={false}/>
            </ProfilePhone>
          </DCArtboard>
        </DCSection>

        {/* ══ Section 2 — Desktop ═════════════════════════════════════════ */}
        <DCSection id="desktop-profile"
                   title="Desktop · پروفایل (دسکتاپ ۱۴۰۰)"
                   subtitle="DesktopTopbar + sidebar (hero + stats) + main (menu) — lb-desktop-wrap pattern">
          <DCArtboard id="d-default" label="A · Default" width={1400} height={900}>
            <div className="pf-desktop-frame">
              <ProfileDesktop locale={t.locale}
                              logoutOpen={desktopLogout}
                              onLogoutClose={() => setDesktopLogout(false)}/>
            </div>
          </DCArtboard>
        </DCSection>

        {/* ══ Section 3 — Edit Profile ════════════════════════════════════ */}
        <DCSection id="edit-profile"
                   title="Edit Profile · ویرایش پروفایل (§S38)"
                   subtitle="صفحه‌ی مستقل — back + ویرایش پروفایل + ذخیره + فرم read-only">
          <DCArtboard id="edit-default" label="A · Edit Profile" width={420} height={840}>
            <ProfilePhone w={420} h={840}>
              <EditProfileScreen locale={t.locale}/>
            </ProfilePhone>
          </DCArtboard>
        </DCSection>

        {/* ══ Section 4 — Logout Modal ════════════════════════════════════ */}
        <DCSection id="logout-modal"
                   title="Logout Modal · تأیید خروج (§S39)"
                   subtitle="MyCardsDetailModal layout='dialog' — backdrop + centered panel + danger CTA">
          <DCArtboard id="logout-default" label="A · Logout Confirm" width={420} height={900}>
            <ProfilePhone w={420} h={900}>
              {/* Show profile content dimmed behind modal */}
              <ProfileMobile locale={t.locale}
                             logoutOpen={true}
                             onLogoutClose={() => {}}
                             inline={true}/>
            </ProfilePhone>
          </DCArtboard>
        </DCSection>

        {/* ══ Section 5 — Locale ══════════════════════════════════════════ */}
        <DCSection id="locale-profile"
                   title="Locale · زبان‌ها (FA / EN / AR)"
                   subtitle="i18n parity — همان صفحه‌ی Default در سه زبان">
          <DCArtboard id="loc-fa" label="FA · فارسی" width={420} height={920}>
            <ProfilePhone w={420} h={920}>
              <ProfileMobile locale="fa" inline={false}/>
            </ProfilePhone>
          </DCArtboard>
          <DCArtboard id="loc-en" label="EN · English" width={420} height={920}>
            <ProfilePhone w={420} h={920}>
              <ProfileMobile locale="en" inline={false}/>
            </ProfilePhone>
          </DCArtboard>
          <DCArtboard id="loc-ar" label="AR · العربية" width={420} height={920}>
            <ProfilePhone w={420} h={920}>
              <ProfileMobile locale="ar" inline={false}/>
            </ProfilePhone>
          </DCArtboard>
        </DCSection>

      </DesignCanvas>

      <TweaksPanel title="Tweaks · Profile">
        <TweakSection label="نمایش">
          <TweakRadio label="زبان" value={t.locale}
            options={[
              { value: 'fa', label: 'فا' },
              { value: 'en', label: 'EN' },
              { value: 'ar', label: 'ع' },
            ]}
            onChange={(v) => setTweak('locale', v)}/>
        </TweakSection>
        <TweakSection label="حالت‌ها">
          <TweakToggle label="Logout Modal (desktop)" value={desktopLogout}
                       onChange={(v) => setDesktopLogout(v)}/>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}


// ─── Exports for unified app shell (v1.7 — index.html · Phase 1) ─────────────
// When this module runs inside the unified SPA (`index.html` sets
// `window.__APP_SHELL_MODE = true` before loading -app.jsx files), we skip
// the DesignCanvas mount and instead expose the screen components to window
// so `app-shell.jsx` can render them in the router.
Object.assign(window, {
  ProfileMobile, ProfileDesktop, ProfilePhone,
  EditProfileScreen, LogoutConfirmModal, PfPageBar,
});

// ─── Mount ─────────────────────────────────────────────────────────────────
// Solo mode only (Profile.html opens this file directly with #root).
// The unified shell uses #app-root and consumes the components above.
const __pfRoot = document.getElementById('root');
if (__pfRoot && !window.__APP_SHELL_MODE) {
  ReactDOM.createRoot(__pfRoot).render(<ProfileApp/>);
}


// ─── App-level CSS (pf- prefix · token-only) ───────────────────────────────
const PF_APP_CSS = `

/* ─── Phone frame ─────────────────────────────────────────────────────── */
.pf-phone {
  position: relative;
  border-radius: 32px;
  background: var(--bg-base, #0E0E16);
  box-shadow:
    0 24px 50px -20px rgba(0,0,0,0.55),
    0 0 0 1px var(--border-soft, rgba(255,255,255,0.06)) inset;
  overflow: hidden;
}
.pf-phone-inner {
  position: absolute; inset: 0;
  display: flex; flex-direction: column;
  overflow: hidden;
}

/* ─── Mobile screen shell ─────────────────────────────────────────────── */
.pf-screen {
  position: relative;
  display: flex; flex-direction: column;
  width: 100%; height: 100%;
  background:
    radial-gradient(ellipse 70% 50% at 20% 0%,  rgba(113,99,217,0.09) 0%, transparent 60%),
    radial-gradient(ellipse 60% 40% at 80% 100%, rgba(147,197,253,0.05) 0%, transparent 60%),
    var(--bg-deep, #07070C);
  color: var(--text-primary);
  font-family: var(--font-current);
  isolation: isolate;
}
.pf-screen-scroll {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
}
.pf-body {
  display: flex; flex-direction: column;
  gap: 14px;
  padding: 8px 0 32px;
}
.pf-body--edit {
  padding: 12px 0 40px;
  gap: 18px;
}

/* ─── PfPageBar ───────────────────────────────────────────────────────── */
/* Glass sticky app bar for secondary screens (Profile / Edit Profile).
   Follows §13.1 Surface Glass recipe. */
.pf-appbar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 14px;
  position: sticky;
  inset-block-start: 0;
  z-index: 20;
  background: linear-gradient(
    180deg,
    rgba(255,255,255,0.05) 0%,
    rgba(255,255,255,0.025) 100%
  );
  backdrop-filter: blur(20px) saturate(120%);
  -webkit-backdrop-filter: blur(20px) saturate(120%);
  border-block-end: 1px solid var(--border-soft, rgba(255,255,255,0.07));
  font-family: var(--font-current);
}
.pf-appbar-back {
  display: inline-flex; align-items: center; justify-content: center;
  width: 32px; height: 32px;
  border-radius: 50%;
  border: 1px solid var(--border-soft, rgba(255,255,255,0.08));
  background: var(--bg-elevated, rgba(255,255,255,0.04));
  color: var(--text-secondary);
  cursor: pointer;
  flex: 0 0 auto;
  transition: opacity 140ms ease;
}
.pf-appbar-back:hover { opacity: 0.75; }
.pf-appbar-title {
  flex: 1;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}
.pf-appbar-actions { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }

/* "ویرایش" accent glass pill */
.pf-appbar-pill {
  display: inline-flex; align-items: center;
  padding: 4px 11px;
  border-radius: 999px;
  border: 1px solid color-mix(in srgb, var(--accent-primary) 40%, transparent);
  background: color-mix(in srgb, var(--accent-primary) 12%, transparent);
  color: var(--accent-primary, #7163D9);
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  font-family: var(--font-current);
  transition: opacity 140ms ease;
}
.pf-appbar-pill:hover { opacity: 0.8; }

/* "ذخیره" accent solid button */
.pf-appbar-save {
  display: inline-flex; align-items: center;
  padding: 5px 14px;
  border-radius: 8px;
  border: none;
  background: linear-gradient(135deg, var(--accent-primary, #7163D9), var(--accent-primary-2, #534AB7));
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  cursor: pointer;
  font-family: var(--font-current);
  transition: opacity 140ms ease;
}
.pf-appbar-save:hover { opacity: 0.85; }

/* ─── Stats grid ──────────────────────────────────────────────────────── */
.pf-stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  padding-inline: 14px;
}
/* In the desktop sidebar the grid is also 2-col but constrained to the side panel */
.pf-stats-grid--sidebar { padding-inline: 0; }

/* ─── Menu section ────────────────────────────────────────────────────── */
.pf-menu-section {
  display: flex; flex-direction: column;
  gap: 4px;
}
.pf-menu-section > :first-child { padding-inline: 14px; }

.pf-menu-group {
  display: flex; flex-direction: column;
  border-radius: 14px;
  overflow: hidden;
  margin-inline: 14px;
  background: linear-gradient(
    180deg,
    rgba(255,255,255,0.04) 0%,
    rgba(255,255,255,0.02) 100%
  );
  border: 1px solid var(--border-soft, rgba(255,255,255,0.07));
}
/* Desktop menu group — matches card surface at wider layout */
.pf-menu-group--desktop {
  border-radius: 16px;
  margin-inline: 0;
}
/* Remove side margin on pf-menu-row when inside pf-menu-group */
.pf-menu-group .pf-menu-row {
  border-radius: 0;
  margin-inline: 0;
}
.pf-menu-group .pf-menu-row:first-child { border-block-start: none; }
.pf-menu-group .pf-menu-row:last-child  { border-block-end: none; }

/* ─── Version footer ──────────────────────────────────────────────────── */
.pf-footer {
  padding-block: 8px 4px;
  padding-inline: 14px;
  text-align: center;
}
.pf-footer-version {
  font-size: 11px;
  color: var(--text-tertiary);
}

/* ─── Edit Profile — avatar section ──────────────────────────────────── */
.pf-edit-avatar-section {
  display: flex; flex-direction: column;
  align-items: center;
  gap: 10px;
  padding-block: 8px;
  padding-inline: 14px;
}
.pf-edit-camera-btn {
  position: absolute;
  inset-block-end: 0;
  inset-inline-start: 0;        /* bottom-start (RTL: bottom-right) */
  width: 30px; height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--accent-primary, #7163D9), var(--accent-primary-2, #534AB7));
  color: #fff;
  border: 2px solid var(--bg-deep, #07070C);
  display: inline-flex; align-items: center; justify-content: center;
  cursor: pointer;
  transition: opacity 140ms ease;
}
.pf-edit-camera-btn:hover { opacity: 0.85; }
.pf-edit-change-link {
  font-size: 11px;
  font-weight: 600;
  color: var(--accent-primary, #7163D9);
  text-decoration: none;
  font-family: var(--font-current);
}
.pf-edit-change-link:hover { opacity: 0.8; }

/* ─── Edit Profile — form fields ─────────────────────────────────────── */
.pf-edit-fields {
  display: flex; flex-direction: column;
  gap: 12px;
  padding-inline: 14px;
}

/* ─── Edit Profile — danger zone ─────────────────────────────────────── */
.pf-edit-danger {
  padding-inline: 14px;
  padding-block-start: 4px;
}
.pf-edit-delete-btn {
  width: 100%;
  padding: 12px 16px;
  border-radius: 12px;
  border: 1px solid color-mix(in srgb, var(--danger, #FB7185) 40%, transparent);
  background: color-mix(in srgb, var(--danger, #FB7185) 6%, transparent);
  color: var(--danger, #FB7185);
  font-size: 13px;
  font-weight: 600;
  font-family: var(--font-current);
  cursor: pointer;
  transition: opacity 140ms ease;
  text-align: center;
}
.pf-edit-delete-btn:hover { opacity: 0.8; }

/* ─── Logout modal content ───────────────────────────────────────────── */
.pf-logout {
  display: flex; flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 0;
  font-family: var(--font-current);
}
.pf-logout-icon-wrap {
  width: 56px; height: 56px;
  border-radius: 50%;
  background: color-mix(in srgb, var(--danger, #FB7185) 14%, transparent);
  border: 1px solid color-mix(in srgb, var(--danger, #FB7185) 28%, transparent);
  display: inline-flex; align-items: center; justify-content: center;
  font-size: 26px;
  font-weight: 700;
  color: var(--danger, #FB7185);
  flex: 0 0 auto;
  margin-block-end: 14px;
}
.pf-logout-icon {
  line-height: 1;
  font-style: normal;
}
.pf-logout-title {
  font-size: 16px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px;
  font-family: var(--font-current);
}
.pf-logout-desc {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.65;
  margin: 0 0 18px;
  font-family: var(--font-current);
}
.pf-logout-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  width: 100%;
}
/* انصراف — accent gradient §13.9 */
.pf-logout-cancel {
  padding: 10px 8px;
  border-radius: 10px;
  border: none;
  background: linear-gradient(135deg, var(--accent-primary, #7163D9), var(--accent-primary-2, #534AB7));
  color: #fff;
  font-size: 13px; font-weight: 600;
  font-family: var(--font-current);
  cursor: pointer;
  transition: opacity 140ms ease;
}
.pf-logout-cancel:hover { opacity: 0.85; }
/* خروج — danger outline */
.pf-logout-confirm {
  padding: 10px 8px;
  border-radius: 10px;
  border: 1px solid color-mix(in srgb, var(--danger, #FB7185) 55%, transparent);
  background: transparent;
  color: var(--danger, #FB7185);
  font-size: 13px; font-weight: 600;
  font-family: var(--font-current);
  cursor: pointer;
  transition: opacity 140ms ease;
}
.pf-logout-confirm:hover { opacity: 0.8; }

/* ─── Desktop screen shell ────────────────────────────────────────────── */
/* pf-desktop-wrap — position:relative + height:100% so that
   mc-mb--inline (position:absolute; inset:0) covers exactly the artboard.
   Mirrors the lb-desktop-wrap pattern (Design Log §12.5 v1.6). */
.pf-desktop-wrap {
  position: relative;
  height: 100%;
  overflow: hidden;
}
.pf-desktop-screen {
  width: 100%; height: 100%;
  overflow: hidden;
  display: flex; flex-direction: column;
  background:
    radial-gradient(ellipse 80% 50% at 20% 10%, rgba(113,99,217,0.07) 0%, transparent 60%),
    radial-gradient(ellipse 70% 50% at 80% 90%, rgba(147,197,253,0.05) 0%, transparent 60%),
    var(--bg-deep, #07070C);
  color: var(--text-primary);
  font-family: var(--font-current);
}
.pf-desktop-frame {
  width: 100%; height: 100%;
  overflow: hidden;
  background: var(--bg-deep, #07070C);
}
.pf-desktop-scroll {
  flex: 1 1 auto;
  overflow-y: auto;
}
/* 2-column grid: sidebar (320px) + main */
.pf-desktop {
  display: grid;
  grid-template-columns: 320px minmax(0, 1fr);
  grid-template-areas: "side main";
  align-items: start;
  gap: 24px;
  max-width: 1140px;
  margin-inline: auto;
  padding: 28px 32px 56px;
}
.pf-desktop-side {
  grid-area: side;
  position: sticky;
  inset-block-start: 16px;
  align-self: start;
  max-height: calc(100vh - 32px);
  overflow-y: auto;
  display: flex; flex-direction: column;
  gap: 16px;
  padding-block-end: 4px;
}
.pf-desktop-main {
  grid-area: main;
  display: flex; flex-direction: column;
  gap: 18px;
}
.pf-desktop-main .pf-menu-section > :first-child { padding-inline: 0; }

/* ─── Reduced motion ──────────────────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
  .pf-appbar-back, .pf-appbar-pill, .pf-appbar-save,
  .pf-logout-cancel, .pf-logout-confirm,
  .pf-edit-delete-btn, .pf-edit-camera-btn { transition: none !important; }
}
`;

const __pfAppStyle = document.createElement('style');
__pfAppStyle.textContent = PF_APP_CSS;
document.head.appendChild(__pfAppStyle);
