// screens-theme.jsx — 主题装修：品牌 / 颜色 / 顶部公告 / 底部 tab + 实时预览
const { adminFetch: _thFetch } = window.NebulaAdmin;

const _TH_DEFAULTS_RAW = {
  id: 'default',
  name: 'Default',
  primary_color: '#7B5BFF',
  accent_color: '#FF6BB3',
  bg_color: '#0A0A0F',
  fg_color: '#FFFFFF',
  logo_url: '',
  brand_name: 'Nebula',
  font_family: 'system-ui, -apple-system, sans-serif',
  header_banner_text: '',
  header_banner_link: '',
};
function _ThDefaults(t) {
  const tx = (t && t.tx) ? t.tx : ((zh) => zh);
  return {
    ..._TH_DEFAULTS_RAW,
    bottom_tabs: [
      { key: 'home',    label: tx('首页', 'Home'),    icon: '🏠', route: 'home' },
      { key: 'lottery', label: tx('彩票', 'Lottery'), icon: '🎯', route: 'lottery' },
      { key: 'live',    label: tx('直播', 'Live'),    icon: '📺', route: 'live' },
      { key: 'me',      label: tx('我的', 'Me'),      icon: '👤', route: 'me' },
    ],
  };
}
const _TH_DEFAULTS = _ThDefaults(null);

const _TH_ROUTE_OPTIONS = [
  'home', 'lottery', 'live', 'drama', 'video', 'theater',
  'games', 'promos', 'agent', 'recharge', 'orders', 'me',
];

// ─── Field ──────────────────────────────────────────────────────────────────
function _ThField({ label, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <label style={{ fontSize: 11, color: 'var(--text-muted)' }}>{label}</label>
      {children}
      {hint && <div className="text-faint" style={{ fontSize: 10 }}>{hint}</div>}
    </div>
  );
}

// ─── Color row: text input + native picker ──────────────────────────────────
function _ThColorRow({ label, value, onChange }) {
  return (
    <_ThField label={label}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <input
          type="color"
          value={value || '#000000'}
          onChange={(e) => onChange(e.target.value)}
          style={{ width: 40, height: 32, border: '1px solid var(--border)', background: 'transparent', borderRadius: 6, padding: 0, cursor: 'pointer' }}
        />
        <input
          className="input"
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 12, textTransform: 'uppercase' }}
        />
      </div>
    </_ThField>
  );
}

// ─── Mini preview block ─────────────────────────────────────────────────────
function _ThColorPreview({ cfg, t }) {
  return (
    <div style={{ marginTop: 8, padding: 14, borderRadius: 10, background: cfg.bg_color, color: cfg.fg_color, border: '1px solid var(--border)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: 8, background: cfg.primary_color, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 14 }}>
          {(cfg.brand_name || 'N').slice(0, 1)}
        </div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{cfg.brand_name || 'Brand'}</div>
        <span style={{ marginLeft: 'auto', fontSize: 10, padding: '2px 8px', background: cfg.accent_color, color: '#fff', borderRadius: 100, fontWeight: 600 }}>HOT</span>
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        <button style={{ flex: 1, padding: '8px 10px', background: cfg.primary_color, border: 0, color: '#fff', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>{t.tx('主要按钮', 'Primary')}</button>
        <button style={{ flex: 1, padding: '8px 10px', background: cfg.accent_color, border: 0, color: '#fff', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>{t.tx('强调按钮', 'Accent')}</button>
      </div>
    </div>
  );
}

// ─── Tab row (with drag-to-reorder) ─────────────────────────────────────────
function _ThTabRow({ tab, idx, total, onChange, onDelete, onReorder, t }) {
  return (
    <div
      draggable
      onDragStart={(e) => { e.dataTransfer.setData('text/plain', String(idx)); e.dataTransfer.effectAllowed = 'move'; }}
      onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; }}
      onDrop={(e) => {
        e.preventDefault();
        const from = parseInt(e.dataTransfer.getData('text/plain'), 10);
        if (!Number.isNaN(from) && from !== idx) onReorder(from, idx);
      }}
      style={{ display: 'grid', gridTemplateColumns: '20px 70px 90px 60px 1fr 28px', gap: 8, alignItems: 'center', padding: 8, background: 'var(--bg-card)', borderRadius: 8, marginBottom: 6, cursor: 'grab' }}
    >
      <div style={{ color: 'var(--text-faint)', fontSize: 14, textAlign: 'center' }} title={t.tx('拖拽排序', 'Drag to reorder')}>⋮⋮</div>
      <input className="input" value={tab.key || ''} onChange={(e) => onChange({ ...tab, key: e.target.value })} placeholder="key" style={{ fontSize: 11, fontFamily: 'var(--font-mono)' }} />
      <input className="input" value={tab.label || ''} onChange={(e) => onChange({ ...tab, label: e.target.value })} placeholder={t.tx('文案', 'Label')} style={{ fontSize: 12 }} />
      <input className="input" value={tab.icon || ''} onChange={(e) => onChange({ ...tab, icon: e.target.value })} placeholder="emoji" style={{ fontSize: 16, textAlign: 'center' }} maxLength={4} />
      <select className="input" value={tab.route || ''} onChange={(e) => onChange({ ...tab, route: e.target.value })} style={{ fontSize: 11 }}>
        <option value="">—</option>
        {_TH_ROUTE_OPTIONS.map((r) => <option key={r} value={r}>{r}</option>)}
      </select>
      <button className="btn btn-sm" onClick={onDelete} title={t.tx('删除', 'Delete')} disabled={total <= 1} style={{ padding: 0, width: 28, height: 28, fontSize: 14, color: 'var(--danger)' }}>×</button>
    </div>
  );
}

// ─── ThemeScreen ────────────────────────────────────────────────────────────
function ThemeScreen({ t, push }) {
  push = push || ((m) => console.log('[theme]', m));
  const [cfg, setCfg] = React.useState(null);
  const [orig, setOrig] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try {
      const j = await _thFetch('/api/theme');
      const defs = _ThDefaults(t);
      const norm = { ...defs, ...j, bottom_tabs: (j.bottom_tabs && j.bottom_tabs.length) ? j.bottom_tabs : defs.bottom_tabs };
      setCfg(norm);
      setOrig(JSON.parse(JSON.stringify(norm)));
    } catch (e) {
      setErr(String((e && e.message) || e));
    } finally {
      setLoading(false);
    }
  }, [t]);
  React.useEffect(() => { load(); }, [load]);

  const dirty = React.useMemo(() => {
    if (!cfg || !orig) return false;
    return JSON.stringify(cfg) !== JSON.stringify(orig);
  }, [cfg, orig]);

  const patch = (k, v) => setCfg((c) => ({ ...c, [k]: v }));

  const save = async () => {
    if (!cfg || saving) return;
    setSaving(true);
    try {
      const body = {
        name: cfg.name,
        primary_color: cfg.primary_color,
        accent_color: cfg.accent_color,
        bg_color: cfg.bg_color,
        fg_color: cfg.fg_color,
        logo_url: cfg.logo_url,
        brand_name: cfg.brand_name,
        font_family: cfg.font_family,
        header_banner_text: cfg.header_banner_text,
        header_banner_link: cfg.header_banner_link,
        bottom_tabs: cfg.bottom_tabs,
      };
      const j = await _thFetch('/api/admin/theme', { method: 'PUT', body: JSON.stringify(body) });
      const defs = _ThDefaults(t);
      const norm = { ...defs, ...j, bottom_tabs: (j.bottom_tabs && j.bottom_tabs.length) ? j.bottom_tabs : defs.bottom_tabs };
      setCfg(norm);
      setOrig(JSON.parse(JSON.stringify(norm)));
      push(t.tx('主题已保存', 'Theme saved'));
    } catch (e) {
      push(t.tx('保存失败: ', 'Save failed: ') + ((e && e.message) || e));
    } finally {
      setSaving(false);
    }
  };

  const reset = () => {
    if (!confirm(t.tx('重置为系统默认值？保存后将影响所有 mobile 端启动配置。', 'Reset to system defaults? After saving this will affect all mobile-app boot configurations.'))) return;
    setCfg(JSON.parse(JSON.stringify(_TH_DEFAULTS)));
  };

  if (loading || !cfg) {
    return <div style={{ padding: 40, color: 'var(--text-muted)' }}>{err ? t.tx('加载失败: ', 'Load failed: ') + err : t.tx('加载中…', 'Loading…')}</div>;
  }

  // ─── tab list ops ──────────────────────────────────────────────────────────
  const tabs = cfg.bottom_tabs || [];
  const setTabs = (next) => setCfg((c) => ({ ...c, bottom_tabs: next }));
  const updateTab = (i, t2) => { const a = tabs.slice(); a[i] = t2; setTabs(a); };
  const deleteTab = (i) => { const a = tabs.slice(); a.splice(i, 1); setTabs(a); };
  const reorderTab = (from, to) => {
    const a = tabs.slice();
    const [m] = a.splice(from, 1);
    a.splice(to, 0, m);
    setTabs(a);
  };
  const addTab = () => setTabs([...tabs, { key: 'new_' + tabs.length, label: t.tx('新 Tab', 'New Tab'), icon: '✨', route: '' }]);

  return (
    <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 920 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 18, fontWeight: 700 }}>{t.tx('主题装修', 'Theme')}</div>
          <div className="text-muted" style={{ fontSize: 12 }}>{t.tx('调整品牌色、Logo、顶部公告条与底部 tab。mobile 端启动时拉取一次。', 'Adjust brand color, logo, top banner and bottom tabs. The mobile app fetches once on boot.')}</div>
        </div>
        <button className="btn btn-sm" onClick={reset}>{t.tx('重置默认', 'Reset')}</button>
        <button className="btn btn-pri" onClick={save} disabled={!dirty || saving}>
          {saving ? t.tx('保存中…', 'Saving…') : (dirty ? t.tx('保存', 'Save') : t.tx('已保存', 'Saved'))}
        </button>
      </div>

      {/* 1. 品牌 ────────────────────────────────────────────────────────── */}
      <section style={{ padding: 16, background: 'var(--bg-card)', borderRadius: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{t.tx('① 品牌', '① Brand')}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <_ThField label={t.tx('品牌名 (brand_name)', 'Brand name (brand_name)')} hint={t.tx('显示在头部 / 启动屏 / 标题栏', 'Shown in header / splash / title bar')}>
            <input className="input" value={cfg.brand_name || ''} onChange={(e) => patch('brand_name', e.target.value)} />
          </_ThField>
          <_ThField label={t.tx('主题名 (name)', 'Theme name (name)')} hint={t.tx('便于多套主题间识别 (春节版 / 国庆版…)', 'For distinguishing themes (Spring Festival / National Day…)')}>
            <input className="input" value={cfg.name || ''} onChange={(e) => patch('name', e.target.value)} />
          </_ThField>
          <_ThField label="Logo URL" hint={t.tx('https:// 或站内 /storage/... 路径。留空显示文字 logo', 'https:// or in-site /storage/… path. Empty shows text logo')}>
            <input className="input" value={cfg.logo_url || ''} onChange={(e) => patch('logo_url', e.target.value)} placeholder="https://cdn.example.com/logo.png" />
          </_ThField>
          <_ThField label={t.tx('字体族 (font_family)', 'Font family (font_family)')} hint={t.tx('CSS font-family 字符串', 'CSS font-family string')}>
            <input className="input" value={cfg.font_family || ''} onChange={(e) => patch('font_family', e.target.value)} style={{ fontSize: 11, fontFamily: 'var(--font-mono)' }} />
          </_ThField>
        </div>
        {cfg.logo_url && (
          <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
            <span className="text-muted" style={{ fontSize: 11 }}>{t.tx('Logo 预览:', 'Logo preview:')}</span>
            <img src={cfg.logo_url} alt="logo" style={{ height: 32, borderRadius: 4, background: '#222', padding: 2 }} onError={(e) => { e.target.style.opacity = 0.3; }} />
          </div>
        )}
      </section>

      {/* 2. 颜色 ────────────────────────────────────────────────────────── */}
      <section style={{ padding: 16, background: 'var(--bg-card)', borderRadius: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{t.tx('② 颜色', '② Colors')}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <_ThColorRow label={t.tx('主色 (primary)', 'Primary')} value={cfg.primary_color} onChange={(v) => patch('primary_color', v)} />
          <_ThColorRow label={t.tx('强调色 (accent)', 'Accent')} value={cfg.accent_color} onChange={(v) => patch('accent_color', v)} />
          <_ThColorRow label={t.tx('背景色 (bg)', 'Background')} value={cfg.bg_color} onChange={(v) => patch('bg_color', v)} />
          <_ThColorRow label={t.tx('前景 / 文字色 (fg)', 'Foreground / Text')} value={cfg.fg_color} onChange={(v) => patch('fg_color', v)} />
        </div>
        <_ThColorPreview cfg={cfg} t={t} />
      </section>

      {/* 3. 顶部公告 ──────────────────────────────────────────────────── */}
      <section style={{ padding: 16, background: 'var(--bg-card)', borderRadius: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{t.tx('③ 顶部公告条', '③ Top banner')}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <_ThField label={t.tx('公告文案', 'Banner text')} hint={t.tx('留空则不显示。出现在 mobile 首页顶部', 'Empty hides it. Shown at top of mobile home')}>
            <input className="input" value={cfg.header_banner_text || ''} onChange={(e) => patch('header_banner_text', e.target.value)} placeholder={t.tx('例：新春大促 限时返水 1.5%', 'e.g. Spring promo: 1.5% rebate limited time')} />
          </_ThField>
          <_ThField label={t.tx('跳转链接 (可选)', 'Link (optional)')}>
            <input className="input" value={cfg.header_banner_link || ''} onChange={(e) => patch('header_banner_link', e.target.value)} placeholder={t.tx('/promos 或 https://...', '/promos or https://...')} />
          </_ThField>
        </div>
        {cfg.header_banner_text && (
          <div style={{ marginTop: 10, padding: '8px 12px', background: cfg.primary_color, color: '#fff', borderRadius: 6, fontSize: 12, textAlign: 'center' }}>
            📣 {cfg.header_banner_text}
          </div>
        )}
      </section>

      {/* 4. 底部 tab ──────────────────────────────────────────────────── */}
      <section style={{ padding: 16, background: 'var(--bg-card)', borderRadius: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{t.tx('④ 底部 Tab', '④ Bottom Tabs')}</div>
          <div className="text-faint" style={{ fontSize: 10, marginRight: 8 }}>{t.tx('拖拽 ⋮⋮ 排序 · 至少保留 1 个', 'Drag ⋮⋮ to reorder · keep at least 1')}</div>
          <button className="btn btn-sm" onClick={addTab}>{t.tx('+ 新增 Tab', '+ Add Tab')}</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '20px 70px 90px 60px 1fr 28px', gap: 8, padding: '4px 8px', fontSize: 10, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.5 }}>
          <div></div><div>Key</div><div>{t.tx('文案', 'Label')}</div><div>Icon</div><div>{t.tx('路由', 'Route')}</div><div></div>
        </div>
        {tabs.map((tab, i) => (
          <_ThTabRow key={i} tab={tab} idx={i} total={tabs.length}
                     onChange={(t2) => updateTab(i, t2)}
                     onDelete={() => deleteTab(i)}
                     onReorder={reorderTab}
                     t={t} />
        ))}
        {/* mini visual preview */}
        <div style={{ marginTop: 12, padding: '8px 4px', background: cfg.bg_color, color: cfg.fg_color, borderRadius: 10, border: '1px solid var(--border)', display: 'flex', justifyContent: 'space-around' }}>
          {tabs.map((tab, i) => (
            <div key={i} style={{ textAlign: 'center', flex: 1, padding: '4px 0' }}>
              <div style={{ fontSize: 18 }}>{tab.icon || '·'}</div>
              <div style={{ fontSize: 10, color: i === 0 ? cfg.primary_color : 'inherit', opacity: i === 0 ? 1 : 0.7 }}>{tab.label || tab.key}</div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { ThemeScreen });
