// User menu — header chip + dropdown (pages rendered by app.jsx as real screens)

const _UM_REG_KEY = 'loij_accounts';

function _umGetProfile(username) {
  try { return (JSON.parse(localStorage.getItem(_UM_REG_KEY)) || []).find(a => a.user === username) || null; }
  catch { return null; }
}

// ── Shared page shell (rendered inside app-main, not a fixed overlay) ─────────

const UMPageShell = ({ children }) => (
  <div style={{
    flex: 1, overflowY: 'auto',
    padding: '36px 40px',
    boxSizing: 'border-box',
  }}>
    {children}
  </div>
);

// ── Password helpers ──────────────────────────────────────────────────────────

function _umIsBuiltIn(username) {
  // Built-in accounts are not in loij_accounts localStorage
  const registered = JSON.parse(localStorage.getItem(_UM_REG_KEY) || '[]');
  return !registered.some(a => a.user === username);
}

function _umVerifyAndChangePass(username, currentPass, newPass) {
  const registered = JSON.parse(localStorage.getItem(_UM_REG_KEY) || '[]');
  const idx = registered.findIndex(a => a.user === username);
  if (idx === -1) return 'builtin';
  if (registered[idx].pass !== currentPass) return 'wrong';
  registered[idx].pass = newPass;
  localStorage.setItem(_UM_REG_KEY, JSON.stringify(registered));
  return null;
}

function _umResetPass(username, newPass) {
  const registered = JSON.parse(localStorage.getItem(_UM_REG_KEY) || '[]');
  const idx = registered.findIndex(a => a.user === username);
  if (idx === -1) return 'builtin';
  registered[idx].pass = newPass;
  localStorage.setItem(_UM_REG_KEY, JSON.stringify(registered));
  return null;
}

// ── Password form (shared UI) ─────────────────────────────────────────────────

const PassInput = ({ label, value, onChange, placeholder }) => {
  const [show, setShow] = React.useState(false);
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ position: 'relative' }}>
        <input
          type={show ? 'text' : 'password'}
          value={value}
          placeholder={placeholder || '••••••••'}
          onChange={e => onChange(e.target.value)}
          style={{
            width: '100%', boxSizing: 'border-box',
            height: 40, padding: '0 38px 0 12px',
            background: 'var(--bg-elevated)',
            border: '1.5px solid var(--border)',
            borderRadius: 8, fontSize: 13, color: 'var(--fg-primary)',
            fontFamily: 'var(--font-body)', outline: 'none',
          }}
          onFocus={e  => e.target.style.borderColor = 'var(--accent-cyan)'}
          onBlur={e   => e.target.style.borderColor = 'var(--border)'}
        />
        <button type="button" onClick={() => setShow(v => !v)} style={{
          position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
          background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)',
          display: 'flex', alignItems: 'center', padding: 4,
        }}>
          <Icon name={show ? 'eye-off' : 'eye'} size={14} />
        </button>
      </div>
    </div>
  );
};

// ── Profile page ──────────────────────────────────────────────────────────────

const UMProfilePage = ({ currentUser, lang }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;
  const profile   = _umGetProfile(currentUser);
  const isBuiltIn = _umIsBuiltIn(currentUser);

  const createdLabel = profile?.createdAt
    ? new Date(profile.createdAt).toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric' })
    : T('Tài khoản gốc', 'Built-in account');

  const rows = [
    { label: T('Tên đăng nhập', 'Username'),   value: currentUser,                       icon: 'user'     },
    { label: T('Email', 'Email'),               value: profile?.email || '—',             icon: 'mail'     },
    { label: T('Ngày tạo', 'Member since'),     value: createdLabel,                      icon: 'calendar' },
    { label: T('Gói hiện tại', 'Current plan'), value: T('Basic · Free', 'Basic · Free'), icon: 'package'  },
  ];

  // ── Change password state
  const [showChange, setShowChange]   = React.useState(false);
  const [chgForm, setChgForm]         = React.useState({ current: '', newPass: '', confirm: '' });
  const [chgError, setChgError]       = React.useState('');
  const [chgSuccess, setChgSuccess]   = React.useState(false);

  const submitChange = () => {
    setChgError('');
    if (!chgForm.current)                             { setChgError(T('Nhập mật khẩu hiện tại', 'Enter current password')); return; }
    if (chgForm.newPass.length < 6)                   { setChgError(T('Mật khẩu mới tối thiểu 6 ký tự', 'Minimum 6 characters')); return; }
    if (chgForm.newPass !== chgForm.confirm)           { setChgError(T('Mật khẩu xác nhận không khớp', 'Passwords do not match')); return; }
    const err = _umVerifyAndChangePass(currentUser, chgForm.current, chgForm.newPass);
    if (err === 'builtin') { setChgError(T('Tài khoản gốc — liên hệ admin để thay đổi', 'Built-in account — contact admin to change')); return; }
    if (err === 'wrong')   { setChgError(T('Mật khẩu hiện tại không đúng', 'Current password is incorrect')); return; }
    setChgSuccess(true);
    setChgForm({ current: '', newPass: '', confirm: '' });
    setTimeout(() => { setChgSuccess(false); setShowChange(false); }, 2200);
  };

  // ── Reset password state
  const [showReset, setShowReset]     = React.useState(false);
  const [rstForm, setRstForm]         = React.useState({ newPass: '', confirm: '' });
  const [rstError, setRstError]       = React.useState('');
  const [rstSuccess, setRstSuccess]   = React.useState(false);

  const submitReset = () => {
    setRstError('');
    if (rstForm.newPass.length < 6)             { setRstError(T('Mật khẩu tối thiểu 6 ký tự', 'Minimum 6 characters')); return; }
    if (rstForm.newPass !== rstForm.confirm)     { setRstError(T('Mật khẩu xác nhận không khớp', 'Passwords do not match')); return; }
    const err = _umResetPass(currentUser, rstForm.newPass);
    if (err === 'builtin') { setRstError(T('Tài khoản gốc — liên hệ admin để thay đổi', 'Built-in account — contact admin')); return; }
    setRstSuccess(true);
    setRstForm({ newPass: '', confirm: '' });
    setTimeout(() => { setRstSuccess(false); setShowReset(false); }, 2200);
  };

  const SectionLabel = ({ children }) => (
    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', letterSpacing: '0.09em', textTransform: 'uppercase', margin: '28px 0 12px' }}>
      {children}
    </div>
  );

  const ActionCard = ({ icon, color, title, sub, open, onToggle, children }) => (
    <div style={{ border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden', marginBottom: 10 }}>
      <button onClick={onToggle} style={{
        display: 'flex', alignItems: 'center', gap: 12, width: '100%',
        padding: '14px 16px', background: 'var(--bg-surface)', border: 'none',
        cursor: 'pointer', textAlign: 'left',
        transition: 'background 0.12s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elevated)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-surface)'}
      >
        <div style={{ width: 34, height: 34, borderRadius: 8, background: `${color}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={icon} size={16} color={color} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)' }}>{title}</div>
          <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{sub}</div>
        </div>
        <Icon name={open ? 'chevron-up' : 'chevron-down'} size={14} color="var(--fg-muted)" />
      </button>
      {open && (
        <div style={{ padding: '16px', borderTop: '1px solid var(--border)', background: 'var(--bg-base)' }}>
          {children}
        </div>
      )}
    </div>
  );

  return (
    <UMPageShell>
      <div style={{ maxWidth: 520 }}>
        {/* Avatar */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
          <div style={{
            width: 90, height: 90, borderRadius: '50%',
            background: 'rgba(102,252,241,0.10)',
            border: '2.5px solid rgba(102,252,241,0.28)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{ fontSize: 38, fontWeight: 800, color: 'var(--accent-cyan)', fontFamily: 'var(--font-display)', lineHeight: 1 }}>
              {currentUser[0].toUpperCase()}
            </span>
          </div>
        </div>

        {/* Info rows */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map((row, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 18px',
              background: 'var(--bg-surface)', border: '1px solid var(--border)', borderRadius: 11,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 9, flexShrink: 0, background: 'var(--bg-elevated)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={row.icon} size={16} color="var(--fg-muted)" />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 3 }}>{row.label}</div>
                <div style={{ fontSize: 14, color: 'var(--fg-primary)', fontWeight: 500 }}>{row.value}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Password section */}
        <SectionLabel>{T('Bảo mật', 'Security')}</SectionLabel>

        {isBuiltIn && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 9, padding: '11px 14px', marginBottom: 14,
            background: 'rgba(251,191,36,0.07)', border: '1px solid rgba(251,191,36,0.22)', borderRadius: 9,
            fontSize: 12.5, color: 'var(--fg-secondary)',
          }}>
            <Icon name="info" size={13} color="#fbbf24" />
            {T('Tài khoản gốc — liên hệ admin để thay đổi mật khẩu.', 'Built-in account — contact admin to change password.')}
          </div>
        )}

        {/* Change password */}
        <ActionCard
          icon="key-round" color="var(--accent-cyan)"
          title={T('Thay đổi mật khẩu', 'Change password')}
          sub={T('Nhập mật khẩu hiện tại và mật khẩu mới', 'Enter your current and new password')}
          open={showChange}
          onToggle={() => { setShowChange(v => !v); setShowReset(false); setChgError(''); setChgSuccess(false); }}
        >
          {chgSuccess ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', background: 'rgba(74,222,128,0.08)', border: '1px solid rgba(74,222,128,0.25)', borderRadius: 9, fontSize: 13, color: '#4ADE80' }}>
              <Icon name="check-circle" size={15} color="#4ADE80" />
              {T('Đổi mật khẩu thành công!', 'Password changed successfully!')}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <PassInput label={T('Mật khẩu hiện tại', 'Current password')} value={chgForm.current}  onChange={v => setChgForm(f => ({ ...f, current:  v }))} />
              <PassInput label={T('Mật khẩu mới', 'New password')}          value={chgForm.newPass}  onChange={v => setChgForm(f => ({ ...f, newPass:  v }))} placeholder={T('Tối thiểu 6 ký tự', 'Min 6 chars')} />
              <PassInput label={T('Xác nhận mật khẩu mới', 'Confirm new')}  value={chgForm.confirm}  onChange={v => setChgForm(f => ({ ...f, confirm:  v }))} />
              {chgError && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--error, #f87171)' }}>
                  <Icon name="alert-circle" size={13} color="var(--error, #f87171)" />{chgError}
                </div>
              )}
              <button onClick={submitChange} style={{
                height: 38, borderRadius: 8, marginTop: 2,
                background: 'var(--accent-cyan)', color: '#000',
                border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 13,
                fontFamily: 'var(--font-body)',
              }}>
                {T('Lưu mật khẩu mới', 'Save new password')}
              </button>
            </div>
          )}
        </ActionCard>

        {/* Reset password */}
        <ActionCard
          icon="refresh-cw" color="#a78bfa"
          title={T('Reset mật khẩu', 'Reset password')}
          sub={T('Đặt lại mật khẩu mới không cần mật khẩu cũ', 'Set a new password without the current one')}
          open={showReset}
          onToggle={() => { setShowReset(v => !v); setShowChange(false); setRstError(''); setRstSuccess(false); }}
        >
          {rstSuccess ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', background: 'rgba(74,222,128,0.08)', border: '1px solid rgba(74,222,128,0.25)', borderRadius: 9, fontSize: 13, color: '#4ADE80' }}>
              <Icon name="check-circle" size={15} color="#4ADE80" />
              {T('Reset mật khẩu thành công!', 'Password reset successfully!')}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '9px 12px', background: 'rgba(167,139,250,0.07)', border: '1px solid rgba(167,139,250,0.20)', borderRadius: 8, fontSize: 12, color: 'var(--fg-muted)' }}>
                <Icon name="alert-triangle" size={13} color="#a78bfa" />
                {T('Dùng khi quên mật khẩu cũ. Mật khẩu sẽ được ghi đè ngay lập tức.', 'Use when you forgot your old password. The password will be overwritten immediately.')}
              </div>
              <PassInput label={T('Mật khẩu mới', 'New password')}           value={rstForm.newPass}  onChange={v => setRstForm(f => ({ ...f, newPass:  v }))} placeholder={T('Tối thiểu 6 ký tự', 'Min 6 chars')} />
              <PassInput label={T('Xác nhận mật khẩu mới', 'Confirm new')}   value={rstForm.confirm}  onChange={v => setRstForm(f => ({ ...f, confirm:  v }))} />
              {rstError && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--error, #f87171)' }}>
                  <Icon name="alert-circle" size={13} color="var(--error, #f87171)" />{rstError}
                </div>
              )}
              <button onClick={submitReset} style={{
                height: 38, borderRadius: 8, marginTop: 2,
                background: '#a78bfa', color: '#000',
                border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 13,
                fontFamily: 'var(--font-body)',
              }}>
                {T('Reset mật khẩu', 'Reset password')}
              </button>
            </div>
          )}
        </ActionCard>
      </div>
    </UMPageShell>
  );
};

// ── Plans page ────────────────────────────────────────────────────────────────

const _PLANS = [
  {
    id: 'basic', name: 'Basic', icon: 'package', color: '#94a3b8',
    price: { vi: 'Miễn phí', en: 'Free' },
    current: true,
    features: [
      { vi: 'Tối đa 3 pipeline / tháng',    en: 'Up to 3 pipelines / month'  },
      { vi: '5 AI generation / ngày',         en: '5 AI generations / day'     },
      { vi: 'Screen: Product + Persona',      en: 'Screens: Product + Persona' },
      { vi: 'Lưu lịch sử 7 ngày',            en: '7-day history'               },
    ],
  },
  {
    id: 'pro', name: 'Pro', icon: 'zap', color: '#66FCF1', badge: 'Popular',
    price: { vi: '299,000 ₫ / tháng', en: '$12 / month' },
    features: [
      { vi: 'Pipeline không giới hạn',       en: 'Unlimited pipelines'         },
      { vi: 'AI generation không giới hạn',  en: 'Unlimited AI generations'    },
      { vi: 'Tất cả 5 screen + Map canvas',  en: 'All 5 screens + Map canvas'  },
      { vi: 'Lưu lịch sử 90 ngày',           en: '90-day history'              },
      { vi: 'Export PDF / CSV',               en: 'PDF / CSV export'            },
    ],
  },
  {
    id: 'premium', name: 'Premium', icon: 'crown', color: '#a78bfa',
    price: { vi: '699,000 ₫ / tháng', en: '$28 / month' },
    features: [
      { vi: 'Tất cả tính năng Pro',           en: 'Everything in Pro'          },
      { vi: 'AI agent chuyên sâu',            en: 'Deep AI agent (Pro model)'  },
      { vi: 'Multi-workspace',                en: 'Multi-workspace support'    },
      { vi: 'Priority support 24/7',          en: '24/7 priority support'      },
      { vi: 'White-label export',             en: 'White-label export'         },
      { vi: 'Lịch sử không giới hạn',         en: 'Unlimited history'          },
    ],
  },
];

const UMPlansPage = ({ lang }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;
  return (
    <UMPageShell>
      <p style={{ fontSize: 14, color: 'var(--fg-secondary)', marginBottom: 32, textAlign: 'center' }}>
        {T('Chọn gói phù hợp với nhu cầu. Nâng cấp bất kỳ lúc nào, hủy được ngay.', 'Choose the plan that fits your needs. Upgrade anytime, cancel anytime.')}
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20, maxWidth: 860, margin: '0 auto' }}>
        {_PLANS.map(plan => (
          <div key={plan.id} style={{
            position: 'relative',
            padding: '28px 22px 22px',
            background: plan.current ? `${plan.color}0d` : 'var(--bg-surface)',
            border: `2px solid ${plan.current ? plan.color : 'var(--border)'}`,
            borderRadius: 16,
          }}>
            {plan.badge && (
              <div style={{
                position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%)',
                background: plan.color, color: '#000',
                padding: '3px 14px', borderRadius: 99,
                fontSize: 10.5, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase',
                whiteSpace: 'nowrap',
              }}>{plan.badge}</div>
            )}

            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 9,
                background: `${plan.color}18`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name={plan.icon} size={18} color={plan.color} />
              </div>
              <span style={{ fontWeight: 700, fontSize: 18, color: 'var(--fg-primary)', fontFamily: 'var(--font-display)' }}>
                {plan.name}
              </span>
              {plan.current && (
                <span style={{
                  marginLeft: 'auto', fontSize: 10, padding: '2px 8px',
                  background: `${plan.color}22`, color: plan.color,
                  borderRadius: 99, fontWeight: 600,
                }}>{T('Hiện tại', 'Current')}</span>
              )}
            </div>

            <div style={{ fontSize: 22, fontWeight: 700, color: plan.color, marginBottom: 22, letterSpacing: '-0.01em' }}>
              {plan.price[lang === 'en' ? 'en' : 'vi']}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 26 }}>
              {plan.features.map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 9, fontSize: 13, color: 'var(--fg-secondary)' }}>
                  <div style={{ marginTop: 3, flexShrink: 0 }}>
                    <Icon name="check" size={13} color={plan.color} />
                  </div>
                  <span>{f[lang === 'en' ? 'en' : 'vi']}</span>
                </div>
              ))}
            </div>

            <button style={{
              width: '100%', padding: '11px 0',
              background: plan.current ? 'transparent' : plan.color,
              color: plan.current ? plan.color : '#000',
              border: plan.current ? `2px solid ${plan.color}` : 'none',
              borderRadius: 10, fontWeight: 700, fontSize: 13.5,
              cursor: plan.current ? 'default' : 'pointer',
              fontFamily: 'var(--font-body)',
            }}>
              {plan.current ? T('Gói hiện tại', 'Current plan') : T('Nâng cấp', 'Upgrade')}
            </button>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: 24, padding: '12px 16px', borderRadius: 10,
        background: 'rgba(102,252,241,0.04)', border: '1px solid rgba(102,252,241,0.10)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        fontSize: 13, color: 'var(--fg-muted)', maxWidth: 860, margin: '24px auto 0',
      }}>
        <Icon name="info" size={14} color="var(--accent-cyan)" />
        {T('Thanh toán qua chuyển khoản ngân hàng hoặc Momo. Liên hệ admin để nâng cấp.',
           'Payment via bank transfer or Momo. Contact admin to upgrade.')}
      </div>
    </UMPageShell>
  );
};

// ── Help page ─────────────────────────────────────────────────────────────────

const _HELP_ITEMS = [
  {
    icon: 'package', color: '#66FCF1',
    title: { vi: 'Sản phẩm', en: 'Product brief' },
    desc: {
      vi: 'Nhập thông tin sản phẩm: tên, mô tả, USP, giá. Chọn model + style → nhấn Generate. AI phân tích chiến lược và tạo nền tảng cho toàn pipeline. Kết quả được link sang Persona, Content, Ads.',
      en: 'Enter product details: name, description, USP, price. Choose model + style → Generate. AI analyzes strategy and feeds the full pipeline. Results link to Persona, Content, and Ads.',
    },
    tips: [
      { vi: 'Nhập đầy đủ USP để AI tạo ra phân tích sắc bén hơn',         en: 'Fill in the USP field for sharper AI analysis'          },
      { vi: 'Dùng Style "Analytical" cho kết quả có số liệu và benchmark', en: 'Use "Analytical" style for data-backed results'         },
      { vi: 'Lưu nhiều version để so sánh các góc tiếp cận khác nhau',     en: 'Save multiple versions to compare different angles'     },
    ],
  },
  {
    icon: 'users', color: '#a78bfa',
    title: { vi: 'Chân dung khách hàng', en: 'Customer persona' },
    desc: {
      vi: 'Xây dựng chân dung khách hàng từ dữ liệu sản phẩm. AI tạo persona chi tiết: demographics, pain points, hành vi mua, kênh tiếp cận. Link nguồn "Sản phẩm" để kết quả chính xác hơn.',
      en: 'Build customer personas from product data. AI creates detailed personas with demographics, pain points, purchase behavior, and channels. Link the "Product" source for better accuracy.',
    },
    tips: [
      { vi: 'Luôn link mục Sản phẩm trước khi Generate',                   en: 'Always link the Product section before generating'      },
      { vi: 'Style "Analytical" cho persona với insight data-driven',       en: 'Use "Analytical" style for data-driven persona'         },
      { vi: 'Tạo 2–3 version với prompt khác nhau để phủ nhiều segment',    en: 'Create 2–3 versions to cover multiple segments'         },
    ],
  },
  {
    icon: 'file-text', color: '#fbbf24',
    title: { vi: 'Content & Plans', en: 'Content & Plans' },
    desc: {
      vi: 'Tạo 5 option content đại diện 5 góc: Pain Point, Desire, Trust, Compare, Trend. 1 mẫu mỗi góc. Muốn thêm biến thể → dùng Purchase. Link sản phẩm + persona để nội dung phù hợp target.',
      en: 'Generate 5 content options for 5 angles: Pain Point, Desire, Trust, Compare, Trend. One sample per angle. For more variants → use Purchase. Link product + persona for targeted content.',
    },
    tips: [
      { vi: 'Link cả Sản phẩm và Persona để nội dung đúng tone và đúng người', en: 'Link both Product and Persona for on-brand content'   },
      { vi: 'Style "Creative" cho hook mạnh, "Formal" cho content B2B',         en: 'Use "Creative" for strong hooks, "Formal" for B2B'    },
      { vi: 'Purchase thêm để có biến thể A/B test cho cùng 1 góc',             en: 'Purchase variants to A/B test within the same angle'  },
    ],
  },
  {
    icon: 'megaphone', color: '#f87171',
    title: { vi: 'Digital Ads · Meta', en: 'Digital Ads · Meta' },
    desc: {
      vi: '3 tab: Overview — tổng quan chiến dịch, nhóm QC, bài QC. Setting — hướng dẫn setup theo thứ tự Campaign → Nhóm quảng cáo → Bài quảng cáo. Analytics — ước tính CPM, CPL, CPC, ROAS theo ngân sách.',
      en: '3 tabs: Overview — campaign/ad set/creative summary. Setting — step-by-step Campaign → Ad Set → Ad Creative setup guide. Analytics — estimated CPM, CPL, CPC, ROAS based on budget.',
    },
    tips: [
      { vi: 'Link tất cả 3 nguồn (Sản phẩm, Persona, Content) để có Ads setup chính xác', en: 'Link all 3 sources for the most accurate Ads setup'       },
      { vi: 'Tab Analytics chỉ là ước tính — dùng để lên kế hoạch ngân sách ban đầu',     en: 'Analytics tab shows estimates — use for initial planning' },
      { vi: 'Export kết quả Setting rồi copy vào Meta Ads Manager theo từng mục',         en: 'Export Setting results and paste into Meta Ads Manager'   },
    ],
  },
  {
    icon: 'bar-chart-2', color: '#34d399',
    title: { vi: 'Ads Data · CSV', en: 'Ads Data · CSV' },
    desc: {
      vi: 'Upload file CSV báo cáo ads từ Meta Ads Manager. AI phân tích ROAS, CPL, chỉ ra campaign hiệu quả và đưa gợi ý tối ưu ngân sách. Link section Ads để có thêm context chiến lược.',
      en: 'Upload a CSV report from Meta Ads Manager. AI analyzes ROAS, CPL, identifies top campaigns, and suggests budget optimization. Link the Ads section for strategic context.',
    },
    tips: [
      { vi: 'Export báo cáo từ Meta dạng CSV để AI đọc được đúng format',           en: 'Export reports from Meta as CSV for correct AI parsing'        },
      { vi: 'Link mục Ads để AI đối chiếu chiến lược đã plan với thực tế',           en: 'Link the Ads section for strategy vs. reality comparison'      },
      { vi: 'Chạy phân tích theo từng giai đoạn để track hiệu quả theo thời gian', en: 'Run analysis per period to track performance over time'         },
    ],
  },
  {
    icon: 'git-fork', color: '#60a5fa',
    title: { vi: 'Map canvas', en: 'Map canvas' },
    desc: {
      vi: 'Hiển thị toàn bộ pipeline dưới dạng sơ đồ node kết nối. Click vào node để xem output tương ứng. Truy cập từ nút "Map" hoặc icon git-fork trên thanh header.',
      en: 'Displays the full pipeline as a connected node diagram. Click a node to preview its output. Access via the "Map" button or git-fork icon in the header.',
    },
    tips: [
      { vi: 'Dùng Map để kiểm tra toàn bộ pipeline trước khi export',    en: 'Use Map to review the full pipeline before exporting'   },
      { vi: 'Click vào node để jump thẳng vào output của section đó',    en: 'Click a node to jump directly to that section output'  },
      { vi: 'Node sáng = có output · Node mờ = chưa generate',           en: 'Bright node = has output · Dim node = not generated yet' },
    ],
  },
];

const UMHelpPage = ({ lang }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;
  const [active, setActive] = React.useState(0);
  const s = _HELP_ITEMS[active];

  return (
    <UMPageShell>
      <div style={{ display: 'flex', gap: 28, maxWidth: 900 }}>
        {/* Left nav */}
        <div style={{ width: 200, flexShrink: 0 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--fg-muted)', letterSpacing: '0.10em', textTransform: 'uppercase', marginBottom: 10 }}>
            {T('Tính năng', 'Features')}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            {_HELP_ITEMS.map((item, i) => (
              <button key={i} onClick={() => setActive(i)} style={{
                display: 'flex', alignItems: 'center', gap: 9,
                padding: '9px 12px',
                background: active === i ? 'rgba(102,252,241,0.08)' : 'transparent',
                border: `1px solid ${active === i ? 'rgba(102,252,241,0.25)' : 'transparent'}`,
                borderRadius: 9, cursor: 'pointer', textAlign: 'left',
                color: active === i ? 'var(--fg-primary)' : 'var(--fg-secondary)',
                fontSize: 13, fontWeight: active === i ? 600 : 400,
                transition: 'background 0.1s',
              }}>
                <Icon name={item.icon} size={14} color={active === i ? item.color : 'var(--fg-muted)'} />
                <span>{item.title[lang === 'en' ? 'en' : 'vi']}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Right content */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
            <div style={{
              width: 46, height: 46, borderRadius: 12, flexShrink: 0,
              background: `${s.color}18`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={s.icon} size={22} color={s.color} />
            </div>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>
              {s.title[lang === 'en' ? 'en' : 'vi']}
            </div>
          </div>

          <p style={{ fontSize: 14, color: 'var(--fg-secondary)', lineHeight: 1.75, marginBottom: 28 }}>
            {s.desc[lang === 'en' ? 'en' : 'vi']}
          </p>

          <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--fg-muted)', letterSpacing: '0.09em', textTransform: 'uppercase', marginBottom: 12 }}>
            {T('Mẹo sử dụng', 'Tips')}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {s.tips.map((tip, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'flex-start', gap: 12,
                padding: '12px 16px',
                background: 'var(--bg-surface)',
                border: '1px solid var(--border)',
                borderRadius: 10,
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 6, flexShrink: 0, marginTop: 1,
                  background: `${s.color}18`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <span style={{ fontSize: 11, fontWeight: 700, color: s.color }}>{i + 1}</span>
                </div>
                <span style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                  {tip[lang === 'en' ? 'en' : 'vi']}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </UMPageShell>
  );
};

// ── Settings page ─────────────────────────────────────────────────────────────

const UMSettingsPage = ({ lang, onLangChange, tweaks, setTweak, onOpenAdvanced }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;

  const SectionHead = ({ label }) => (
    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', letterSpacing: '0.09em', textTransform: 'uppercase', marginBottom: 12, marginTop: 28 }}>
      {label}
    </div>
  );

  const Row = ({ icon, label, sub, right }) => (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '14px 18px',
      background: 'var(--bg-surface)',
      border: '1px solid var(--border)',
      borderRadius: 11, marginBottom: 8,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 9, flexShrink: 0,
        background: 'var(--bg-elevated)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={16} color="var(--fg-muted)" />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--fg-primary)' }}>{label}</div>
        {sub && <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );

  const Toggle = ({ value, onChange }) => (
    <button onClick={() => onChange(!value)} style={{
      width: 40, height: 22, borderRadius: 11, flexShrink: 0,
      background: value ? 'var(--accent-cyan)' : 'var(--bg-elevated)',
      border: `1.5px solid ${value ? 'var(--accent-cyan)' : 'var(--border)'}`,
      cursor: 'pointer', position: 'relative', transition: 'background 0.2s, border-color 0.2s',
      padding: 0,
    }}>
      <div style={{
        position: 'absolute', top: 2,
        left: value ? 20 : 2,
        width: 14, height: 14, borderRadius: '50%',
        background: value ? '#000' : 'var(--fg-muted)',
        transition: 'left 0.2s',
      }} />
    </button>
  );

  return (
    <UMPageShell>
      <div style={{ maxWidth: 600 }}>
        <SectionHead label={T('Giao diện', 'Appearance')} />

        <Row icon="moon" label={T('Chế độ tối', 'Dark mode')}
          sub={T('Bật/tắt giao diện dark / light', 'Toggle dark / light theme')}
          right={<Toggle value={tweaks?.dark ?? true} onChange={v => setTweak('dark', v)} />}
        />
        <Row icon="layout-dashboard" label={T('Style chip', 'Style chip')}
          sub={T('Hiển thị chip style ở đầu mỗi section', 'Show style chip at top of each section')}
          right={<Toggle value={tweaks?.showStyleChip ?? true} onChange={v => setTweak('showStyleChip', v)} />}
        />
        <Row icon="activity" label={T('Trạng thái topbar', 'Header status')}
          sub={T('Hiển thị badge trạng thái trên header', 'Show status badge in header')}
          right={<Toggle value={tweaks?.headerStatus ?? true} onChange={v => setTweak('headerStatus', v)} />}
        />

        <SectionHead label={T('Ngôn ngữ', 'Language')} />

        <div style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
          {[{ value: 'vi', label: 'Tiếng Việt' }, { value: 'en', label: 'English' }].map(opt => (
            <button key={opt.value} onClick={() => onLangChange(opt.value)} style={{
              flex: 1, padding: '12px 0',
              background: lang === opt.value ? 'rgba(102,252,241,0.09)' : 'var(--bg-surface)',
              border: `1.5px solid ${lang === opt.value ? 'var(--accent-cyan)' : 'var(--border)'}`,
              borderRadius: 10, cursor: 'pointer',
              fontSize: 13.5, fontWeight: 600,
              color: lang === opt.value ? 'var(--accent-cyan)' : 'var(--fg-secondary)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              transition: 'border-color 0.15s, color 0.15s',
            }}>
              {lang === opt.value && <Icon name="check" size={13} color="var(--accent-cyan)" />}
              {opt.label}
            </button>
          ))}
        </div>

        <SectionHead label={T('Nâng cao', 'Advanced')} />

        <button onClick={onOpenAdvanced} style={{
          width: '100%', padding: '14px 18px',
          display: 'flex', alignItems: 'center', gap: 14,
          background: 'var(--bg-surface)', border: '1px solid var(--border)',
          borderRadius: 11, cursor: 'pointer', textAlign: 'left',
          transition: 'border-color 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--accent-cyan)'}
        onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}
        >
          <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--bg-elevated)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="key-round" size={16} color="var(--fg-muted)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--fg-primary)' }}>
              {T('API & Style presets', 'API & Style presets')}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2 }}>
              {T('Quản lý API providers, style templates, workspace', 'Manage API providers, style templates, workspace')}
            </div>
          </div>
          <Icon name="chevron-right" size={15} color="var(--fg-muted)" />
        </button>
      </div>
    </UMPageShell>
  );
};

// ── UserMenu chip + dropdown ──────────────────────────────────────────────────

const UserMenu = ({ currentUser, onLogout, lang, onLangChange, onNavigate, onOpenSettings }) => {
  const [open, setOpen]         = React.useState(false);
  const [langHover, setLangHover] = React.useState(false);
  const ref = React.useRef(null);
  const T = (vi, en) => lang === 'en' ? en : vi;

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) { setOpen(false); setLangHover(false); } };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const go = (id) => { setOpen(false); onNavigate(id); };

  const menuItems = [
    { id: 'user-settings', icon: 'settings',   label: T('Cài đặt', 'Settings')  },
    { id: 'user-plans',    icon: 'crown',       label: T('Gói đăng ký', 'Plans') },
    { id: 'user-profile',  icon: 'circle-user', label: T('Thông tin', 'Profile') },
    { id: 'user-help',     icon: 'help-circle', label: T('Trợ giúp', 'Help')     },
  ];

  const LANG_OPTIONS = [
    { value: 'vi', label: 'Tiếng Việt' },
    { value: 'en', label: 'English'    },
  ];

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
      {/* Chip */}
      <button
        onClick={() => { setOpen(o => !o); setLangHover(false); }}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 7,
          padding: '0 10px', height: 28,
          background: open ? 'rgba(102,252,241,0.09)' : 'var(--bg-elevated)',
          border: `1px solid ${open ? 'rgba(102,252,241,0.40)' : 'var(--border)'}`,
          borderRadius: 7, fontSize: 12, cursor: 'pointer',
          transition: 'border-color 0.15s, background 0.15s',
        }}
      >
        <Icon name="user" size={12} color="var(--accent-cyan)" />
        <span style={{ fontWeight: 500, color: 'var(--fg-primary)' }}>{currentUser}</span>
        <Icon name={open ? 'chevron-up' : 'chevron-down'} size={11} color="var(--fg-muted)" />
      </button>

      {/* Dropdown */}
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 7px)', right: 0, zIndex: 300,
          background: 'var(--bg-surface)', border: '1px solid var(--border)',
          borderRadius: 12, padding: '6px',
          boxShadow: '0 10px 40px rgba(0,0,0,0.50)',
          minWidth: 200,
        }}>
          {/* User header */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 9,
            padding: '9px 10px 10px',
            borderBottom: '1px solid var(--border)',
            marginBottom: 5,
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
              background: 'rgba(102,252,241,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, fontWeight: 700, color: 'var(--accent-cyan)',
              fontFamily: 'var(--font-display)',
            }}>
              {currentUser[0].toUpperCase()}
            </div>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--fg-primary)' }}>{currentUser}</div>
              <div style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>Basic · Free</div>
            </div>
          </div>

          {/* Items */}
          {menuItems.map(item => (
            <button key={item.id} onClick={() => go(item.id)} style={{
              display: 'flex', alignItems: 'center', gap: 9,
              width: '100%', padding: '8px 10px',
              background: 'transparent', border: 'none',
              borderRadius: 7, cursor: 'pointer', textAlign: 'left',
              color: 'var(--fg-secondary)', fontSize: 13,
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-elevated)'; e.currentTarget.style.color = 'var(--fg-primary)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'transparent';        e.currentTarget.style.color = 'var(--fg-secondary)'; }}
            >
              <Icon name={item.icon} size={14} color="var(--fg-muted)" />
              <span>{item.label}</span>
            </button>
          ))}

          {/* Language flyout */}
          <div
            style={{ position: 'relative' }}
            onMouseEnter={() => setLangHover(true)}
            onMouseLeave={() => setLangHover(false)}
          >
            <button style={{
              display: 'flex', alignItems: 'center', gap: 9,
              width: '100%', padding: '8px 10px',
              background: langHover ? 'var(--bg-elevated)' : 'transparent', border: 'none',
              borderRadius: 7, cursor: 'pointer', textAlign: 'left',
              color: langHover ? 'var(--fg-primary)' : 'var(--fg-secondary)', fontSize: 13,
            }}>
              <Icon name="globe" size={14} color="var(--fg-muted)" />
              <span style={{ flex: 1 }}>{T('Ngôn ngữ', 'Language')}</span>
              <Icon name="chevron-right" size={12} color="var(--fg-muted)" />
            </button>

            {langHover && (
              <div style={{
                position: 'absolute', right: 'calc(100% + 6px)', top: 0,
                background: 'var(--bg-surface)', border: '1px solid var(--border)',
                borderRadius: 10, padding: '5px',
                boxShadow: '0 10px 40px rgba(0,0,0,0.50)',
                minWidth: 160, zIndex: 301,
              }}>
                {LANG_OPTIONS.map(opt => (
                  <button key={opt.value} onClick={() => { onLangChange(opt.value); setOpen(false); }} style={{
                    display: 'flex', alignItems: 'center', gap: 9,
                    width: '100%', padding: '9px 12px',
                    background: lang === opt.value ? 'rgba(102,252,241,0.08)' : 'transparent',
                    border: 'none', borderRadius: 7, cursor: 'pointer', textAlign: 'left',
                    color: lang === opt.value ? 'var(--accent-cyan)' : 'var(--fg-secondary)',
                    fontSize: 13, fontWeight: lang === opt.value ? 600 : 400,
                  }}
                  onMouseEnter={e => { if (lang !== opt.value) { e.currentTarget.style.background = 'var(--bg-elevated)'; e.currentTarget.style.color = 'var(--fg-primary)'; } }}
                  onMouseLeave={e => { if (lang !== opt.value) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-secondary)'; } }}
                  >
                    <span style={{ flex: 1 }}>{opt.label}</span>
                    {lang === opt.value && <Icon name="check" size={13} color="var(--accent-cyan)" />}
                  </button>
                ))}
              </div>
            )}
          </div>

          <div style={{ height: 1, background: 'var(--border)', margin: '5px 6px' }} />

          <button onClick={() => { setOpen(false); onLogout(); }} style={{
            display: 'flex', alignItems: 'center', gap: 9,
            width: '100%', padding: '8px 10px',
            background: 'transparent', border: 'none',
            borderRadius: 7, cursor: 'pointer', textAlign: 'left',
            color: '#f87171', fontSize: 13,
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(248,113,113,0.08)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
          >
            <Icon name="log-out" size={14} color="#f87171" />
            <span>{T('Đăng xuất', 'Log out')}</span>
          </button>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { UserMenu, UMProfilePage, UMPlansPage, UMHelpPage, UMSettingsPage });
