/* Клиентские экраны: обзор, обновления, продукт, версия, профиль, поддержка. */
(function () {
  const { Button, Card, Tag, StatItem, Input } = window.DesignSystem_219642;
  const D = window.PortalData;
  const { StatusBadge, PageHeading } = window;

  // ---- Модалка редактирования профиля ----
  function ProfileEditModal({ user, onClose, onSaved }) {
    const [name, setName] = React.useState(user.display_name || '');
    const [org, setOrg] = React.useState(user.org || '');
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState('');
    const save = async () => {
      setBusy(true); setError('');
      try {
        await D.updateProfile({ display_name: name, org });
        if (onSaved) await onSaved();
        onClose();
      } catch (e) { setError('Не удалось сохранить. Попробуйте снова.'); setBusy(false); }
    };
    return ReactDOM.createPortal(
      <div style={{ position: 'fixed', inset: 0, zIndex: 80, display: 'grid', placeItems: 'center', padding: '24px' }}>
        <div onClick={busy ? undefined : onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(8,12,18,0.66)', backdropFilter: 'blur(3px)' }} />
        <div className="portal-modal" style={{ position: 'relative', width: '100%', maxWidth: '440px', maxHeight: 'calc(100vh - 48px)', display: 'flex', flexDirection: 'column', background: 'var(--surface-card)', border: '1px solid var(--border-light)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden' }}>
          <div style={{ padding: '20px 24px', borderTop: '2px solid var(--accent)', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h3 style={{ margin: 0, fontSize: '17px', fontWeight: 700, color: 'var(--text-primary)' }}>Изменить данные</h3>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer', fontSize: '16px' }}><i className="fas fa-xmark" /></button>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '24px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <Input label="ФИО / представитель" icon="fas fa-id-badge" value={name} onChange={(e) => setName(e.target.value)} placeholder="И. С. Орлов" fullWidth />
            <Input label="Организация" icon="fas fa-building" value={org} onChange={(e) => setOrg(e.target.value)} placeholder="Наименование организации" fullWidth />
            <div style={{ fontSize: '12px', color: 'var(--text-muted)' }}>Email и роль меняет администратор портала.</div>
            {error && (
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 12px', borderRadius: 'var(--radius)', background: 'rgba(239,68,68,0.10)', border: '1px solid rgba(239,68,68,0.3)', color: 'var(--red-500)', fontSize: '12.5px' }}>
                <i className="fas fa-triangle-exclamation" />{error}
              </div>
            )}
          </div>
          <div style={{ padding: '18px 24px', borderTop: '1px solid var(--border)', display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
            <Button variant="glass" size="sm" onClick={onClose} disabled={busy}>Отмена</Button>
            <Button variant="primary" size="sm" icon={busy ? undefined : 'fas fa-check'} onClick={save} disabled={busy}>{busy ? 'Сохранение…' : 'Сохранить'}</Button>
          </div>
        </div>
      </div>,
      document.body,
    );
  }

  // ---- Маленькая статистика ----
  function StatTile({ icon, value, label, tone }) {
    return (
      <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '20px 22px', display: 'flex', alignItems: 'center', gap: '16px' }}>
        <div style={{ width: '44px', height: '44px', borderRadius: 'var(--radius)', display: 'grid', placeItems: 'center', background: 'var(--accent-muted)', border: '1px solid var(--border-accent)', color: tone === 'green' ? 'var(--green-500)' : 'var(--accent-light)', fontSize: '18px' }}>
          <i className={icon} />
        </div>
        <div>
          <div style={{ fontSize: '26px', fontWeight: 800, color: 'var(--text-primary)', letterSpacing: '-0.02em', lineHeight: 1 }}>{value}</div>
          <div style={{ fontSize: '12.5px', color: 'var(--text-secondary)', marginTop: '5px' }}>{label}</div>
        </div>
      </div>
    );
  }

  // ---- Иконка продукта ----
  function ProductGlyph({ icon, size = 52 }) {
    return (
      <div style={{ width: size, height: size, flexShrink: 0, borderRadius: 'var(--radius)', display: 'grid', placeItems: 'center', background: 'linear-gradient(135deg, var(--navy-800), var(--navy-700))', border: '1px solid var(--border-accent)', color: 'var(--accent-light)', fontSize: size * 0.4, boxShadow: 'var(--inset-sheen)' }}>
        <i className={icon} />
      </div>
    );
  }

  // ---- Плитка продукта на дашборде ----
  function ProductTile({ product, nav }) {
    const lic = D.licenseFor(product.id);
    const st = D.updatesStatus(lic && lic.updates_until);
    const vers = D.versionsFor(product.id);
    const available = vers.filter((v) => D.versionAvailable(lic, v));
    const latest = vers[0];
    const latestAvailable = D.versionAvailable(lic, latest);
    return (
      <Card interactive cornerAccent padding="0" style={{ display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '22px 22px 18px', display: 'flex', gap: '16px' }}>
          <ProductGlyph icon={product.icon} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
              <h3 style={{ margin: 0, fontSize: '19px', fontWeight: 700, color: 'var(--text-primary)' }}>{product.name}</h3>
            </div>
            <p style={{ margin: '5px 0 0', fontSize: '13px', color: 'var(--text-secondary)', lineHeight: 1.5 }}>{product.tagline}</p>
          </div>
        </div>
        <div style={{ padding: '0 22px 18px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
          <StatusBadge tone={st.tone} dot icon={st.code === 'expired' ? 'fas fa-triangle-exclamation' : undefined}>{st.label}</StatusBadge>
        </div>
        <div style={{ marginTop: 'auto', borderTop: '1px solid var(--border)', padding: '14px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px' }}>
          <div style={{ display: 'flex', gap: '22px' }}>
            <div><div style={{ fontSize: '17px', fontWeight: 700, color: 'var(--text-primary)' }}>{latest.version}</div><div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>{latestAvailable ? 'актуальная' : 'недоступна'}</div></div>
            <div><div style={{ fontSize: '17px', fontWeight: 700, color: 'var(--text-primary)' }}>{available.length}<span style={{ color: 'var(--text-muted)', fontWeight: 500 }}>/{vers.length}</span></div><div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>версий доступно</div></div>
          </div>
          <Button variant="glass" size="sm" iconRight="fas fa-arrow-right" onClick={() => nav({ screen: 'product', params: { slug: product.slug } })}>Открыть</Button>
        </div>
      </Card>
    );
  }

  // ---- Строка версии в списке обновлений ----
  function VersionRow({ version, product, lic, nav, onDownload, compact }) {
    const available = D.versionAvailable(lic, version);
    const [h, setH] = React.useState(false);
    return (
      <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: 'flex', alignItems: 'center', gap: '16px', padding: '16px 20px', borderRadius: 'var(--radius)', border: '1px solid', borderColor: h ? 'var(--border-light)' : 'var(--border)', background: h ? 'var(--surface-card-hover)' : 'var(--surface-card)', transition: 'all var(--transition)' }}>
        <div style={{ width: '40px', height: '40px', flexShrink: 0, borderRadius: 'var(--radius)', display: 'grid', placeItems: 'center', background: available ? 'var(--accent-muted)' : 'var(--surface-overlay)', border: `1px solid ${available ? 'var(--border-accent)' : 'var(--border)'}`, color: available ? 'var(--accent-light)' : 'var(--text-muted)', fontSize: '15px' }}>
          <i className={available ? 'fas fa-cube' : 'fas fa-lock'} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
            {!compact && <span style={{ fontSize: '14px', fontWeight: 600, color: 'var(--text-secondary)' }}>{product.name}</span>}
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: '14px', fontWeight: 700, color: 'var(--text-primary)' }}>v{version.version}</span>
            {version.critical && <span style={{ fontSize: '10px', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--accent-light)', background: 'var(--accent-soft)', borderRadius: '4px', padding: '2px 7px' }}>важное</span>}
          </div>
          <div style={{ fontSize: '12.5px', color: 'var(--text-muted)', marginTop: '3px', display: 'flex', gap: '14px' }}>
            <span><i className="far fa-calendar" style={{ marginRight: '5px' }} />{D.formatDate(version.release_date)}</span>
            <span><i className="far fa-hard-drive" style={{ marginRight: '5px' }} />{version.size}</span>
          </div>
        </div>
        {available ? (
          <div style={{ display: 'flex', gap: '8px' }}>
            <Button variant="ghost" size="sm" onClick={() => nav({ screen: 'version', params: { id: version.id } })}>Подробнее</Button>
            <Button variant="primary" size="sm" icon="fas fa-download" onClick={() => onDownload(version, product)}>Скачать</Button>
          </div>
        ) : (
          <div style={{ textAlign: 'right' }}>
            <StatusBadge tone="warning" icon="fas fa-lock">Нужно продление</StatusBadge>
          </div>
        )}
      </div>
    );
  }

  // ---- Дашборд ----
  function Dashboard({ nav, onDownload, user }) {
    const allAvailable = [];
    D.products.forEach((p) => {
      const lic = D.licenseFor(p.id);
      D.versionsFor(p.id).forEach((v) => { if (D.versionAvailable(lic, v)) allAvailable.push({ v, p, lic }); });
    });
    allAvailable.sort((a, b) => D.parseDate(b.v.release_date) - D.parseDate(a.v.release_date));
    const recent = allAvailable.slice(0, 3);
    const expiring = D.licenses
      .map((l) => ({ l, s: D.updatesStatus(l.updates_until) }))
      .filter(({ s }) => s.code === 'soon' || s.code === 'expired');
    const ex0 = expiring[0];
    const exProd = ex0 ? D.productById(ex0.l.product_id) : null;
    const firstName = user && user.display_name ? user.display_name.split(' ')[0] : 'коллега';

    return (
      <div>
        <PageHeading eyebrow={`Здравствуйте, ${firstName}`} title="Обзор кабинета" subtitle="Ваши продукты, статус лицензий и доступные обновления. Доступ к версиям определяется правом на обновления в лицензии." />

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', marginBottom: '32px' }}>
          <StatTile icon="fas fa-cube" value={D.products.length} label="Продукта в кабинете" />
          <StatTile icon="fas fa-key" value={D.licenses.length} label="Активных лицензий" />
          <StatTile icon="fas fa-cloud-arrow-down" value={allAvailable.length} label="Версий доступно" tone="green" />
          <StatTile icon="fas fa-clock-rotate-left" value={D.downloadLog.length} label="Загрузок за период" />
        </div>

        {expiring.length > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '16px 20px', borderRadius: 'var(--radius-lg)', background: 'rgba(245,158,11,0.07)', border: '1px solid rgba(245,158,11,0.25)', marginBottom: '32px' }}>
            <i className="fas fa-triangle-exclamation" style={{ color: 'var(--amber-500)', fontSize: '18px' }} />
            <div style={{ flex: 1, fontSize: '13.5px', color: 'var(--text-secondary)' }}>
              По продукту <b style={{ color: 'var(--text-primary)' }}>{exProd ? exProd.name : '—'}</b>{' '}
              {ex0.s.code === 'expired'
                ? `право на обновления истекло ${D.formatDate(ex0.l.updates_until)} — новые версии недоступны до продления.`
                : `право на обновления заканчивается ${D.formatDate(ex0.l.updates_until)} — продлите, чтобы получать новые версии.`}
              {expiring.length > 1 ? ` И ещё лицензий с истекающим правом: ${expiring.length - 1}.` : ''}
            </div>
            <Button variant="outline" size="sm">Продлить</Button>
          </div>
        )}

        <div style={{ marginBottom: '14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: '18px', fontWeight: 700, color: 'var(--text-primary)' }}>Мои продукты</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '36px' }}>
          {D.products.map((p) => <ProductTile key={p.id} product={p} nav={nav} />)}
        </div>

        <div style={{ marginBottom: '14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: '18px', fontWeight: 700, color: 'var(--text-primary)' }}>Последние обновления</h2>
          <Button variant="ghost" size="sm" iconRight="fas fa-arrow-right" onClick={() => nav({ screen: 'updates' })}>Все обновления</Button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
          {recent.map(({ v, p, lic }) => <VersionRow key={v.id} version={v} product={p} lic={lic} nav={nav} onDownload={onDownload} />)}
        </div>
      </div>
    );
  }

  // ---- Лента обновлений ----
  function UpdatesFeed({ nav, onDownload }) {
    const [filter, setFilter] = React.useState('all'); // all | available | locked
    const rows = [];
    D.products.forEach((p) => {
      const lic = D.licenseFor(p.id);
      D.versionsFor(p.id).forEach((v) => rows.push({ v, p, lic, available: D.versionAvailable(lic, v) }));
    });
    rows.sort((a, b) => D.parseDate(b.v.release_date) - D.parseDate(a.v.release_date));
    const shown = rows.filter((r) => filter === 'all' || (filter === 'available' ? r.available : !r.available));
    const tabs = [['all', 'Все', rows.length], ['available', 'Доступные', rows.filter((r) => r.available).length], ['locked', 'Заблокированы', rows.filter((r) => !r.available).length]];
    return (
      <div>
        <PageHeading eyebrow="Обновления" title="Доступные версии" subtitle="Полный список релизов по вашим продуктам. Версия доступна для скачивания, если её дата выпуска покрыта правом на обновления в лицензии." />
        <div style={{ display: 'flex', gap: '8px', marginBottom: '20px' }}>
          {tabs.map(([v, l, n]) => (
            <button key={v} onClick={() => setFilter(v)} style={{
              display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 16px', borderRadius: 'var(--radius-pill)', cursor: 'pointer', font: 'inherit', fontSize: '13px', fontWeight: 600,
              background: filter === v ? 'var(--accent-muted)' : 'transparent', border: `1px solid ${filter === v ? 'var(--border-accent)' : 'var(--border)'}`, color: filter === v ? 'var(--accent-light)' : 'var(--text-secondary)', transition: 'all var(--transition)',
            }}>{l}<span style={{ fontSize: '11px', opacity: 0.8 }}>{n}</span></button>
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
          {shown.map(({ v, p, lic }) => <VersionRow key={v.id} version={v} product={p} lic={lic} nav={nav} onDownload={onDownload} />)}
        </div>
      </div>
    );
  }

  // ---- Карточка продукта ----
  function InfoRow({ label, children }) {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '16px', padding: '11px 0', borderBottom: '1px solid var(--border)' }}>
        <span style={{ fontSize: '13px', color: 'var(--text-muted)' }}>{label}</span>
        <span style={{ fontSize: '13.5px', color: 'var(--text-primary)', fontWeight: 600, textAlign: 'right' }}>{children}</span>
      </div>
    );
  }

  function ProductScreen({ slug, nav, onDownload }) {
    const product = D.productBySlug(slug);
    const lic = D.licenseFor(product.id);
    const st = D.updatesStatus(lic && lic.updates_until);
    const vers = D.versionsFor(product.id);
    return (
      <div>
        <div style={{ display: 'flex', gap: '18px', alignItems: 'flex-start', marginBottom: '28px' }}>
          <ProductGlyph icon={product.icon} size={64} />
          <div style={{ flex: 1 }}>
            <h1 style={{ margin: 0, fontSize: '30px', fontWeight: 800, letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>{product.name}</h1>
            <p style={{ margin: '8px 0 0', fontSize: '15px', color: 'var(--text-secondary)', maxWidth: '640px', lineHeight: 1.55 }}>{product.description}</p>
            <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginTop: '14px' }}>
              {product.tags.map((t) => <Tag key={t}>{t}</Tag>)}
            </div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: '24px', alignItems: 'start' }}>
          <div>
            <h2 style={{ margin: '0 0 14px', fontSize: '18px', fontWeight: 700, color: 'var(--text-primary)' }}>Версии и обновления</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
              {vers.map((v) => <VersionRow key={v.id} version={v} product={product} lic={lic} nav={nav} onDownload={onDownload} compact />)}
            </div>
          </div>

          <div style={{ position: 'sticky', top: '88px', background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', overflow: 'hidden' }}>
            <div style={{ borderTop: '2px solid var(--accent)', padding: '18px 20px 6px' }}>
              <div style={{ fontSize: '11px', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '4px' }}>Лицензия</div>
            </div>
            <div style={{ padding: '0 20px 18px' }}>
              <div style={{ marginBottom: '14px' }}><StatusBadge tone={st.tone} dot icon={st.code === 'expired' ? 'fas fa-triangle-exclamation' : undefined}>{st.label}</StatusBadge></div>
              <InfoRow label="Ключ лицензии"><span style={{ fontFamily: 'var(--font-mono)', fontSize: '12.5px' }}>{lic.license_key}</span></InfoRow>
              <InfoRow label="Срок действия">{lic.valid_until ? D.formatDate(lic.valid_until) : 'Бессрочно'}</InfoRow>
              <InfoRow label="Право на обновления">{lic.updates_until ? D.formatDate(lic.updates_until) : 'Без ограничения'}</InfoRow>
              <InfoRow label="Рабочих мест">{lic.seats}</InfoRow>
              <InfoRow label="Платформа">{product.platform}</InfoRow>
              {st.code === 'expired' && (
                <div style={{ marginTop: '16px' }}>
                  <Button variant="outline" size="sm" fullWidth icon="fas fa-rotate-right">Продлить обновления</Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ---- Страница версии ----
  function VersionScreen({ id, nav, onDownload }) {
    const version = D.versionById(id);
    const product = D.productById(version.product_id);
    const lic = D.licenseFor(product.id);
    const available = D.versionAvailable(lic, version);
    return (
      <div style={{ maxWidth: '860px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '14px', marginBottom: '8px' }}>
          <span style={{ fontSize: '14px', color: 'var(--text-secondary)', fontWeight: 600 }}>{product.name}</span>
          {version.critical && <span style={{ fontSize: '10px', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--accent-light)', background: 'var(--accent-soft)', borderRadius: '4px', padding: '3px 8px' }}>важное обновление</span>}
        </div>
        <h1 style={{ margin: 0, fontSize: '34px', fontWeight: 800, letterSpacing: '-0.02em', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)' }}>v{version.version}</h1>
        <div style={{ display: 'flex', gap: '20px', marginTop: '12px', color: 'var(--text-muted)', fontSize: '13.5px' }}>
          <span><i className="far fa-calendar" style={{ marginRight: '6px' }} />Выпуск {D.formatDate(version.release_date)}</span>
          <span><i className="far fa-hard-drive" style={{ marginRight: '6px' }} />{version.size}</span>
          <span><i className="fas fa-microchip" style={{ marginRight: '6px' }} />{product.platform}</span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '24px', marginTop: '28px', alignItems: 'start' }}>
          <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '24px 26px' }}>
            <h2 style={{ margin: '0 0 16px', fontSize: '16px', fontWeight: 700, color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '10px' }}>
              <i className="fas fa-list-ul" style={{ color: 'var(--accent-light)', fontSize: '14px' }} />Что нового
            </h2>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: '12px' }}>
              {version.changelog.map((c, i) => (
                <li key={i} style={{ display: 'flex', gap: '12px', fontSize: '14px', color: 'var(--text-secondary)', lineHeight: 1.55 }}>
                  <i className="fas fa-check" style={{ color: 'var(--green-500)', fontSize: '12px', marginTop: '4px', flexShrink: 0 }} />
                  <span>{c}</span>
                </li>
              ))}
            </ul>
          </div>

          <div style={{ position: 'sticky', top: '88px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <div style={{ background: 'var(--surface-card)', border: `1px solid ${available ? 'var(--border-accent)' : 'var(--border)'}`, borderRadius: 'var(--radius-lg)', padding: '22px', boxShadow: available ? 'var(--glow-accent)' : 'none' }}>
              {available ? (
                <React.Fragment>
                  <div style={{ marginBottom: '14px' }}><StatusBadge tone="online" dot>Доступно по лицензии</StatusBadge></div>
                  <Button variant="primary" fullWidth size="lg" icon="fas fa-download" onClick={() => onDownload(version, product)}>Скачать дистрибутив</Button>
                  <div style={{ display: 'flex', gap: '8px', marginTop: '14px', fontSize: '11.5px', color: 'var(--text-muted)', lineHeight: 1.5 }}>
                    <i className="fas fa-shield-halved" style={{ marginTop: '2px', color: 'var(--accent-light)' }} />
                    <span>Выдача ссылки фиксируется в журнале (дата, IP, лицензия) — доказуемая цепочка поставки.</span>
                  </div>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div style={{ marginBottom: '14px' }}><StatusBadge tone="warning" icon="fas fa-lock">Недоступно</StatusBadge></div>
                  <p style={{ margin: '0 0 16px', fontSize: '13px', color: 'var(--text-secondary)', lineHeight: 1.5 }}>
                    Дата выпуска версии ({D.formatDate(version.release_date)}) позже окончания права на обновления ({D.formatDate(lic.updates_until)}).
                  </p>
                  <Button variant="outline" fullWidth icon="fas fa-rotate-right">Продлить право на обновления</Button>
                </React.Fragment>
              )}
            </div>
            <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '18px 20px' }}>
              <InfoRow label="Ключ лицензии"><span style={{ fontFamily: 'var(--font-mono)', fontSize: '12px' }}>{lic.license_key}</span></InfoRow>
              <InfoRow label="Обновления до">{lic.updates_until ? D.formatDate(lic.updates_until) : 'Без ограничения'}</InfoRow>
              <div style={{ paddingTop: '11px' }}>
                <button onClick={() => nav({ screen: 'product', params: { slug: product.slug } })} style={{ background: 'none', border: 'none', color: 'var(--accent-light)', cursor: 'pointer', font: 'inherit', fontSize: '13px', padding: 0 }}>
                  <i className="fas fa-arrow-left" style={{ marginRight: '6px', fontSize: '11px' }} />К продукту
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ---- Профиль ----
  function ProfileScreen({ user, reload }) {
    const [edit, setEdit] = React.useState(false);
    return (
      <div>
        <PageHeading eyebrow="Профиль" title="Учётная запись" subtitle="Данные представителя организации, лицензии и история обращений к обновлениям." />
        <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: '24px', alignItems: 'start' }}>
          <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '26px', textAlign: 'center' }}>
            <div style={{ width: '72px', height: '72px', borderRadius: '50%', margin: '0 auto 16px', display: 'grid', placeItems: 'center', background: 'var(--accent-muted)', border: '1px solid var(--border-accent)', color: 'var(--accent-light)', fontSize: '26px', fontWeight: 700 }}>{(user && user.display_name ? user.display_name.trim().split(/\s+/).map((s) => s[0]).slice(0, 2).join('').toUpperCase() : '—')}</div>
            <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--text-primary)' }}>{user.display_name}</div>
            <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginTop: '4px' }}>{user.org}</div>
            <div style={{ marginTop: '16px', textAlign: 'left' }}>
              <InfoRow label="Email">{user.email}</InfoRow>
              <InfoRow label="Роль">Клиент</InfoRow>
              <InfoRow label="Лицензий">{D.licenses.length}</InfoRow>
            </div>
            <div style={{ marginTop: '18px' }}><Button variant="glass" size="sm" fullWidth icon="fas fa-pen" onClick={() => setEdit(true)}>Изменить данные</Button></div>
          </div>

          <div>
            <h2 style={{ margin: '0 0 14px', fontSize: '16px', fontWeight: 700, color: 'var(--text-primary)' }}>Мои лицензии</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '28px' }}>
              {D.licenses.map((l) => {
                const p = D.productById(l.product_id); const st = D.updatesStatus(l.updates_until);
                return (
                  <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: '16px', padding: '14px 18px', borderRadius: 'var(--radius)', background: 'var(--surface-card)', border: '1px solid var(--border)' }}>
                    <ProductGlyph icon={p.icon} size={40} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: '14px', fontWeight: 600, color: 'var(--text-primary)' }}>{p.name}</div>
                      <div style={{ fontSize: '12px', color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', marginTop: '2px' }}>{l.license_key}</div>
                    </div>
                    <StatusBadge tone={st.tone} dot>{st.label}</StatusBadge>
                  </div>
                );
              })}
            </div>

            <h2 style={{ margin: '0 0 14px', fontSize: '16px', fontWeight: 700, color: 'var(--text-primary)' }}>История загрузок</h2>
            <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '13px' }}>
                <thead><tr style={{ background: 'var(--surface-overlay)' }}>
                  {['Продукт', 'Версия', 'Дата и время', 'IP'].map((h) => <th key={h} style={{ textAlign: 'left', padding: '11px 18px', fontSize: '11px', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-muted)', fontWeight: 600 }}>{h}</th>)}
                </tr></thead>
                <tbody>
                  {D.downloadLog.map((r) => (
                    <tr key={r.id} style={{ borderTop: '1px solid var(--border)' }}>
                      <td style={{ padding: '12px 18px', color: 'var(--text-primary)', fontWeight: 500 }}>{r.product}</td>
                      <td style={{ padding: '12px 18px', fontFamily: 'var(--font-mono)', color: 'var(--text-secondary)' }}>v{r.version}</td>
                      <td style={{ padding: '12px 18px', color: 'var(--text-secondary)' }}>{r.created_at}</td>
                      <td style={{ padding: '12px 18px', fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{r.ip}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
        {edit && <ProfileEditModal user={user} onClose={() => setEdit(false)} onSaved={reload} />}
      </div>
    );
  }

  Object.assign(window, { Dashboard, UpdatesFeed, ProductScreen, VersionScreen, ProfileScreen });
})();
