// screen-settings.jsx + AddProductModal + MoreScreen
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

const MANUAL_MAX_IMAGES = 8;
const MANUAL_MAX_BYTES = 5 * 1024 * 1024;

function Section({ title, desc, children, action }) {
  return (
    <div className="card card-pad" style={{ marginBottom: 16 }}>
      <div className="between" style={{ marginBottom: 16 }}>
        <div><div className="t-h2">{title}</div>{desc && <div className="t-sm dim" style={{ marginTop: 3 }}>{desc}</div>}</div>
        {action}
      </div>
      {children}
    </div>
  );
}

const AI_MODELS = {
  text: [
    { v: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro', vendor: 'Google', cost: '$1.25/1M tok' },
    { v: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash', vendor: 'Google', cost: '$0.15/1M tok' },
    { v: 'gpt-4o', label: 'GPT-4o', vendor: 'OpenAI', cost: '$2.50/1M tok' },
    { v: 'gpt-4o-mini', label: 'GPT-4o mini', vendor: 'OpenAI', cost: '$0.15/1M tok' },
    { v: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', vendor: 'Anthropic', cost: '$3.00/1M tok' },
    { v: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', vendor: 'Anthropic', cost: '$0.80/1M tok' },
  ],
  image: [
    { v: 'banana-pro', label: 'Nano Banana Pro', vendor: 'Google', cost: '$0.05/ảnh' },
    { v: 'imagen-3', label: 'Imagen 3', vendor: 'Google', cost: '$0.04/ảnh' },
    { v: 'dall-e-3', label: 'DALL·E 3', vendor: 'OpenAI', cost: '$0.04/ảnh' },
    { v: 'flux-pro', label: 'FLUX Pro', vendor: 'Black Forest Labs', cost: '$0.05/ảnh' },
    { v: 'sd-3-large', label: 'Stable Diffusion 3 Large', vendor: 'Stability AI', cost: '$0.04/ảnh' },
  ],
  tts: [
    { v: 'elevenlabs-v2', label: 'ElevenLabs Multilingual v2', vendor: 'ElevenLabs', cost: '$0.18/1K ký tự' },
    { v: 'google-tts-neural', label: 'Google Cloud TTS Neural', vendor: 'Google', cost: '$0.016/1K ký tự' },
    { v: 'openai-tts-hd', label: 'OpenAI TTS HD', vendor: 'OpenAI', cost: '$0.030/1K ký tự' },
  ],
  translation: [
    { v: 'deepl-pro', label: 'DeepL Pro', vendor: 'DeepL', cost: '€5.49/1M ký tự' },
    { v: 'google-translate-v3', label: 'Google Translate v3', vendor: 'Google', cost: '$20/1M ký tự' },
    { v: 'gpt-4o-translate', label: 'GPT-4o (prompt)', vendor: 'OpenAI', cost: '$2.50/1M tok' },
  ],
};

const AI_DEFAULTS = {
  text: { model: 'gemini-2.5-pro', apiKey: '', temperature: 0.7, systemPrompt: 'Bạn là copywriter cho thương hiệu thời trang Zei JP. Viết caption ngắn gọn, vui tươi, đậm chất Nhật, tiếng Việt tự nhiên.' },
  image: { model: 'banana-pro', apiKey: '', aspectRatio: '4:5', stylePreset: 'studio-natural' },
  tts: { model: 'elevenlabs-v2', apiKey: '', voiceId: 'rachel', stability: 0.5 },
  translation: { model: 'deepl-pro', apiKey: '', sourceLang: 'ja', targetLang: 'vi' },
};

function AiApiPanel() {
  const app = useApp();
  const [cfg, setCfg] = useStateS(AI_DEFAULTS);
  const [show, setShow] = useStateS({ text: false, image: false, tts: false, translation: false });
  const update = (section, patch) => setCfg(c => ({ ...c, [section]: { ...c[section], ...patch } }));
  const toggleShow = (section) => setShow(s => ({ ...s, [section]: !s[section] }));
  const testConnection = (section, label) => {
    const c = cfg[section];
    if (!c.apiKey) { app.toast('Chưa nhập API key cho ' + label, 'alert', 'var(--yellow)'); return; }
    app.toast('Mock: key đã lưu trong session, không gọi API thật', 'check', 'var(--green)');
  };

  const keyRow = (section) => (
    <div className="row gap-sm">
      <input
        className="input mono"
        style={{ flex: 1 }}
        type={show[section] ? 'text' : 'password'}
        placeholder="dán API key của bạn (sk-… / AIza… / v.v.)"
        value={cfg[section].apiKey}
        onChange={e => update(section, { apiKey: e.target.value })}
      />
      <Button variant="ghost" size="sm" icon="eye" onClick={() => toggleShow(section)}>{show[section] ? 'Ẩn' : 'Hiện'}</Button>
    </div>
  );

  return (
    <>
      <div className="banner banner-info" style={{ marginBottom: 16 }}>
        <Icon name="key" size={16} style={{ color: 'var(--blue)' }} />
        <span className="t-xs">Demo UI · key chỉ lưu trong session trình duyệt, KHÔNG gửi đi đâu và KHÔNG gọi API thật. Khi qua P1 production sẽ wire qua n8n credentials.</span>
      </div>

      <Section title="Tạo caption / nội dung văn bản" desc="LLM sinh caption Zalo/Facebook, tiêu đề bài viết, mô tả sản phẩm">
        <Field label="Model">
          <select className="select" value={cfg.text.model} onChange={e => update('text', { model: e.target.value })}>
            {AI_MODELS.text.map(m => <option key={m.v} value={m.v}>{m.label} · {m.vendor} ({m.cost})</option>)}
          </select>
        </Field>
        <div style={{ height: 14 }}></div>
        <Field label="API key" hint="Lấy từ Google AI Studio / OpenAI Platform / Anthropic Console. Không gửi lên server.">{keyRow('text')}</Field>
        <div style={{ height: 14 }}></div>
        <div className="between" style={{ marginBottom: 6 }}>
          <span className="t-sm strong">Temperature (sáng tạo)</span>
          <span className="t-sm mono dimmer">{cfg.text.temperature.toFixed(2)}</span>
        </div>
        <input type="range" min="0" max="1" step="0.05" value={cfg.text.temperature} onChange={e => update('text', { temperature: +e.target.value })} style={{ width: '100%', accentColor: 'var(--accent)' }} />
        <div style={{ height: 14 }}></div>
        <Field label="System prompt" hint="Hướng dẫn LLM khi tạo nội dung. Áp dụng cho TẤT CẢ bài đăng.">
          <textarea className="textarea" value={cfg.text.systemPrompt} onChange={e => update('text', { systemPrompt: e.target.value })} />
        </Field>
        <div style={{ height: 12 }}></div>
        <Button variant="default" icon="check" onClick={() => testConnection('text', 'caption')}>Test kết nối</Button>
      </Section>

      <Section title="Tạo ảnh AI" desc="Image gen dựng ảnh sản phẩm, banner, lookbook">
        <Field label="Model">
          <select className="select" value={cfg.image.model} onChange={e => update('image', { model: e.target.value })}>
            {AI_MODELS.image.map(m => <option key={m.v} value={m.v}>{m.label} · {m.vendor} ({m.cost})</option>)}
          </select>
        </Field>
        <div style={{ height: 14 }}></div>
        <Field label="API key">{keyRow('image')}</Field>
        <div style={{ height: 14 }}></div>
        <div className="row-wrap" style={{ gap: 14 }}>
          <Field label="Tỉ lệ mặc định">
            <select className="select" value={cfg.image.aspectRatio} onChange={e => update('image', { aspectRatio: e.target.value })} style={{ width: 200 }}>
              <option value="1:1">1:1 Vuông</option>
              <option value="4:5">4:5 Instagram feed</option>
              <option value="9:16">9:16 Reels / Stories</option>
              <option value="16:9">16:9 Cover ngang</option>
              <option value="3:4">3:4 Portrait</option>
            </select>
          </Field>
          <Field label="Style preset">
            <select className="select" value={cfg.image.stylePreset} onChange={e => update('image', { stylePreset: e.target.value })} style={{ width: 240 }}>
              <option value="studio-natural">Studio · ánh sáng tự nhiên</option>
              <option value="outdoor-tokyo">Ngoài trời · phố Tokyo</option>
              <option value="minimal-white">Tối giản · nền trắng</option>
              <option value="vintage-film">Vintage · film màu</option>
              <option value="lookbook-editorial">Lookbook · editorial</option>
            </select>
          </Field>
        </div>
        <div style={{ height: 12 }}></div>
        <Button variant="default" icon="sparkle" onClick={() => testConnection('image', 'tạo ảnh')}>Tạo ảnh mẫu kiểm tra</Button>
      </Section>

      <Section title="TTS / Lồng tiếng" desc="Sinh giọng nói cho Reels / TikTok / video product demo">
        <Field label="Provider">
          <select className="select" value={cfg.tts.model} onChange={e => update('tts', { model: e.target.value })}>
            {AI_MODELS.tts.map(m => <option key={m.v} value={m.v}>{m.label} · {m.vendor} ({m.cost})</option>)}
          </select>
        </Field>
        <div style={{ height: 14 }}></div>
        <Field label="API key">{keyRow('tts')}</Field>
        <div style={{ height: 14 }}></div>
        <Field label="Voice">
          <select className="select" value={cfg.tts.voiceId} onChange={e => update('tts', { voiceId: e.target.value })}>
            <option value="rachel">Rachel · nữ Mỹ tự nhiên</option>
            <option value="vi-female-1">VN nữ · trẻ sôi nổi</option>
            <option value="vi-female-2">VN nữ · ấm trầm</option>
            <option value="vi-male-1">VN nam · MC</option>
            <option value="ja-female-1">JP nữ · genki</option>
          </select>
        </Field>
        <div style={{ height: 14 }}></div>
        <div className="between" style={{ marginBottom: 6 }}>
          <span className="t-sm strong">Độ ổn định giọng (stability)</span>
          <span className="t-sm mono dimmer">{cfg.tts.stability.toFixed(2)}</span>
        </div>
        <input type="range" min="0" max="1" step="0.05" value={cfg.tts.stability} onChange={e => update('tts', { stability: +e.target.value })} style={{ width: '100%', accentColor: 'var(--accent)' }} />
        <div style={{ height: 12 }}></div>
        <Button variant="default" icon="play" onClick={() => testConnection('tts', 'TTS')}>Phát thử mẫu</Button>
      </Section>

      <Section title="Dịch thuật" desc="Dịch JP → VI cho tên sản phẩm, mô tả, caption gốc tiếng Nhật">
        <Field label="Provider">
          <select className="select" value={cfg.translation.model} onChange={e => update('translation', { model: e.target.value })}>
            {AI_MODELS.translation.map(m => <option key={m.v} value={m.v}>{m.label} · {m.vendor} ({m.cost})</option>)}
          </select>
        </Field>
        <div style={{ height: 14 }}></div>
        <Field label="API key">{keyRow('translation')}</Field>
        <div style={{ height: 14 }}></div>
        <div className="row-wrap" style={{ gap: 14 }}>
          <Field label="Ngôn ngữ nguồn">
            <select className="select" value={cfg.translation.sourceLang} onChange={e => update('translation', { sourceLang: e.target.value })} style={{ width: 180 }}>
              <option value="ja">Tiếng Nhật</option>
              <option value="en">Tiếng Anh</option>
              <option value="auto">Tự nhận diện</option>
            </select>
          </Field>
          <Field label="Ngôn ngữ đích">
            <select className="select" value={cfg.translation.targetLang} onChange={e => update('translation', { targetLang: e.target.value })} style={{ width: 180 }}>
              <option value="vi">Tiếng Việt</option>
              <option value="en">Tiếng Anh</option>
            </select>
          </Field>
        </div>
        <div style={{ height: 12 }}></div>
        <Button variant="default" icon="globe" onClick={() => testConnection('translation', 'dịch')}>Test dịch mẫu</Button>
      </Section>
    </>
  );
}

function SettingsScreen({ forceTab }) {
  const app = useApp();
  const s = SETTINGS;
  const [innerTab, setInnerTab] = useStateS('fx');
  const tab = forceTab || innerTab;
  const setTab = forceTab ? (() => {}) : setInnerTab;
  const [scoring, setScoring] = useStateS(s.scoring);
  const [fb, setFb] = useStateS(s.fb), [ig, setIg] = useStateS(s.ig), [tk, setTk] = useStateS(s.tiktok);

  const tabs = [
    { value: 'fx', label: 'Tỉ giá' }, { value: 'ai', label: 'AI Model' }, { value: 'score', label: 'Chấm điểm' },
    { value: 'channel', label: 'Kênh đăng' }, { value: 'notif', label: 'Thông báo' }, { value: 'system', label: 'Hệ thống' },
  ];

  return (
    <div className="page-pad" style={{ maxWidth: 880 }}>
      {!forceTab && <>
        <div className="t-h1" style={{ marginBottom: 4 }}>Cài đặt</div>
        <div className="t-sm dim" style={{ marginBottom: 16 }}>Cấu hình hệ thống tự động · tỉ giá, AI, chấm điểm, kênh đăng</div>
        <div style={{ marginBottom: 18, overflowX: 'auto' }}><Tabs active={tab} onChange={setTab} tabs={tabs} /></div>
      </>}

      {tab === 'fx' && (
        <Section title="Tỉ giá JPY → VND" desc="Mỗi sản phẩm khóa tỉ giá tại thời điểm scrape" action={<Button variant="primary" size="sm" icon="refresh" onClick={() => app.toast('Đã cập nhật tỉ giá', 'check')}>Cập nhật rate</Button>}>
          <div className="panel" style={{ padding: 18, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
            <div><div className="t-2xs dimmer">TỈ GIÁ HIỆN TẠI</div><div className="t-display mono" style={{ fontSize: 28 }}>1 ¥ = {s.fx.rate} đ</div><div className="t-xs dimmer">Khóa {s.fx.lockedAgo}</div></div>
            <div className="topbar-spacer"></div>
            <div className="banner banner-warn" style={{ maxWidth: 320 }}><Icon name="alert" size={16} style={{ color: 'var(--yellow)' }} /><span className="t-xs">Rate live <span className="strong mono">{s.fx.live}đ</span> đang lệch <span className="strong">{s.fx.drift}%</span> so với rate khóa.</span></div>
          </div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>LỊCH SỬ 30 NGÀY</div>
          <table className="tbl"><thead><tr><th>Ngày</th><th style={{ textAlign: 'right' }}>Tỉ giá khóa</th></tr></thead><tbody>{s.fxHistory.map(h => <tr key={h.date} style={{ cursor: 'default' }}><td className="t-sm">{h.date}</td><td className="t-sm mono strong" style={{ textAlign: 'right' }}>{h.rate} đ</td></tr>)}</tbody></table>
        </Section>
      )}

      {tab === 'ai' && <AiApiPanel />}

      {tab === 'ai' && (
        <Section title="Định danh AI Model (persona ảnh)" desc="Người mẫu AI phải nhất quán giữa các bài đăng — riêng biệt với API key ở trên" action={<Button variant="primary" size="sm" icon="lock" onClick={() => app.toast('Đã khóa định danh AI model', 'check')}>Lock identity</Button>}>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>ẢNH THAM CHIẾU</div>
          <div className="row gap-sm" style={{ marginBottom: 16 }}>
            {['Front', 'Side', '3/4'].map(v => <Placeholder key={v} label={'model · ' + v} tag={<Badge variant="accent">{v}</Badge>} ratio="3/4" style={{ width: 110 }} />)}
            <div className="ph" style={{ width: 110, aspectRatio: '3/4', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><div className="col" style={{ alignItems: 'center', gap: 6, color: 'var(--text-3)' }}><Icon name="upload" size={20} /><span className="t-2xs">Tải thêm</span></div></div>
          </div>
          <Field label="Mô tả persona"><textarea className="textarea" defaultValue="Nữ, 22-25 tuổi, dáng người Á Đông cao 1m65, tóc đen dài, phong cách trẻ trung năng động, make-up tự nhiên." /></Field>
          <div style={{ height: 14 }}></div>
          <Field label="Định hướng phong cách"><textarea className="textarea" defaultValue="Phông nền studio tối giản, ánh sáng tự nhiên, tập trung vào sản phẩm, không quá nhiều phụ kiện gây nhiễu." /></Field>
          <div style={{ height: 14 }}></div>
          <Button variant="default" icon="sparkle" onClick={() => app.toast('Đang tạo ảnh mẫu để kiểm tra…', 'loader', 'var(--blue)')}>Tạo ảnh mẫu kiểm tra</Button>
        </Section>
      )}

      {tab === 'score' && (
        <Section title="Trọng số chấm điểm" desc="Điều chỉnh cách hệ thống xếp hạng sản phẩm đáng đăng (P1 deterministic)">
          {[{ k: 'discount', l: 'Mức giảm giá' }, { k: 'stock', l: 'Tồn kho' }, { k: 'image', l: 'Chất lượng ảnh' }].map(it => (
            <div key={it.k} style={{ marginBottom: 16 }}>
              <div className="between" style={{ marginBottom: 6 }}><span className="t-sm strong">{it.l}</span><span className="t-sm mono dimmer">{scoring[it.k]}%</span></div>
              <input type="range" min="0" max="100" value={scoring[it.k]} onChange={e => setScoring(sc => ({ ...sc, [it.k]: +e.target.value }))} style={{ width: '100%', accentColor: 'var(--accent)' }} />
            </div>
          ))}
          <div className="panel" style={{ padding: 14 }}><div className="row gap-sm"><Icon name="trending" size={16} style={{ color: 'var(--accent)' }} /><span className="t-sm strong">Preview top 3 sau khi đổi trọng số</span></div>
            <div className="col" style={{ gap: 6, marginTop: 10 }}>{[...PRODUCTS].sort((a, b) => b.score - a.score).slice(0, 3).map(p => <div key={p.id} className="row gap-sm"><Score value={p.score} /><span className="t-sm clip-1">{p.titleVn}</span></div>)}</div>
          </div>
        </Section>
      )}

      {tab === 'channel' && (
        <Section title="Kênh đăng mặc định" desc="Hồ sơ đăng bài qua API-Hub và các nền tảng đang bật">
          <Field label="Hồ sơ đăng bài"><select className="select"><option>ZEIJP</option></select></Field>
          <div className="divider"></div>
          {[{ l: 'Facebook Page', on: fb, set: setFb, p1: true }, { l: 'Instagram', on: ig, set: setIg }, { l: 'TikTok', on: tk, set: setTk }].map(c => (
            <div key={c.l} className="between" style={{ padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
              <div className="row gap-sm"><Icon name={c.l.includes('Face') ? 'facebook' : 'globe'} size={18} /><span className="t-sm strong">{c.l}</span>{!c.p1 && <Badge variant="neutral">P2</Badge>}</div>
              <Toggle on={c.on} onChange={c.set} />
            </div>
          ))}
        </Section>
      )}

      {tab === 'notif' && (
        <Section title="Thông báo" desc="Telegram (P1) · Web push (P2)">
          <Field label="Telegram bot token"><input className="input mono" defaultValue={SETTINGS.telegram.token} /></Field>
          <div style={{ height: 14 }}></div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>APPROVER TELEGRAM UID</div>
          <div className="row-wrap gap-sm" style={{ marginBottom: 10 }}>{SETTINGS.telegram.uids.map(u => <span key={u} className="badge badge-brand" style={{ height: 28 }}>{u}<Icon name="x" size={12} style={{ cursor: 'pointer' }} /></span>)}</div>
          <Button variant="default" size="sm" icon="plus">Thêm UID</Button>
          <div className="divider"></div>
          <div className="between" style={{ padding: '4px 0' }}><div className="row gap-sm"><Icon name="bell" size={18} /><span className="t-sm strong">Web push</span><Badge variant="neutral">P2</Badge></div><Toggle on={false} onChange={() => {}} /></div>
        </Section>
      )}

      {tab === 'system' && (
        <Section title="Hệ thống" desc="Trạng thái dịch vụ · chỉ admin">
          {[{ l: 'Supabase Database', ic: 'database', ok: true, v: 'Hoạt động' }, { l: 'n8n Workflows', ic: 'layers', ok: true, v: '6/6 active' }, { l: 'API-Hub quota', ic: 'upload', ok: true, v: '142 / 500 tháng này' }, { l: 'Banana API', ic: 'sparkle', ok: true, v: 'Hoạt động' }].map(r => (
            <div key={r.l} className="between" style={{ padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
              <div className="row gap-sm"><Icon name={r.ic} size={18} style={{ color: 'var(--text-2)' }} /><span className="t-sm strong">{r.l}</span></div>
              <div className="row gap-sm"><span className="t-xs dimmer mono">{r.v}</span><span style={{ width: 8, height: 8, borderRadius: 99, background: r.ok ? 'var(--green)' : 'var(--red)' }}></span></div>
            </div>
          ))}
          <div style={{ height: 16 }}></div>
          <Button variant="default" icon="download" onClick={() => app.toast('Đang export audit log…', 'download', 'var(--blue)')}>Export audit log (CSV)</Button>
        </Section>
      )}
    </div>
  );
}

/* ============ ADD PRODUCT MODAL ============ */
function AddProductModal({ onClose }) {
  const [mode, setMode] = useStateS('url');
  const Panel = mode === 'url' ? UrlPanel : ManualPanel;
  return <Panel onClose={onClose} mode={mode} setMode={setMode} />;
}

function AddModeSwitch({ mode, setMode }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <Seg value={mode} options={[{ value: 'url', label: 'Dán URL' }, { value: 'manual', label: 'Nhập tay' }]} onChange={setMode} />
    </div>
  );
}

function UrlPanel({ onClose, mode, setMode }) {
  const app = useApp();
  const [text, setText] = useStateS('');
  const [autoApprove, setAutoApprove] = useStateS(false);
  const urls = text.split('\n').map(s => s.trim()).filter(Boolean);
  const detected = {};
  urls.forEach(u => {
    const b = BRANDS.find(br => br.hosts.some(h => u.includes(h)));
    const key = b ? b.name : 'Không xác định';
    detected[key] = (detected[key] || 0) + 1;
  });
  const unknown = detected['Không xác định'] || 0;
  const submit = () => { app.toast(`${urls.length} sản phẩm đang được scrape`, 'check'); onClose(); app.go('products'); };

  return (
    <Modal title="Thêm sản phẩm" sub="Dán 1 hoặc nhiều URL sản phẩm Nhật, mỗi URL 1 dòng" onClose={onClose}
      foot={<><div className="topbar-spacer"></div><Button variant="ghost" onClick={onClose}>Hủy</Button><Button variant="primary" icon="plus" disabled={!urls.length || unknown > 0} onClick={submit}>Thêm {urls.length || ''} sản phẩm</Button></>}>
      <AddModeSwitch mode={mode} setMode={setMode} />
      <Field>
        <textarea className="textarea mono" style={{ minHeight: 140, fontSize: 13 }} autoFocus value={text} onChange={e => setText(e.target.value)}
                  placeholder={'https://www.uniqlo.com/jp/465185\nhttps://gu-global.com/jp/3391\nhttps://nike.com/jp/...'} />
      </Field>
      {urls.length > 0 && (
        <div className="row-wrap gap-sm" style={{ marginTop: 10 }}>
          <Badge variant="brand">{urls.length} URL</Badge>
          {Object.entries(detected).map(([k, n]) => <Badge key={k} variant={k === 'Không xác định' ? 'red' : 'green'}>{k} ({n})</Badge>)}
        </div>
      )}
      {unknown > 0 && <div className="banner banner-danger" style={{ marginTop: 12 }}><Icon name="alert" size={16} style={{ color: 'var(--red)' }} /><span className="t-xs">{unknown} URL không khớp brand nào đang bật. Thêm brand trong mục Nguồn brand trước.</span></div>}
      <div className="divider"></div>
      <div className="between" style={{ cursor: 'pointer' }} onClick={() => setAutoApprove(v => !v)}>
        <div><div className="t-sm strong">Tự động duyệt Stage-1</div><div className="t-xs dimmer">Bỏ qua duyệt sản phẩm, tạo nội dung luôn (nâng cao)</div></div>
        <Toggle on={autoApprove} onChange={setAutoApprove} />
      </div>
    </Modal>
  );
}

function ManualPanel({ onClose, mode, setMode }) {
  const app = useApp();
  const enabledBrands = BRANDS.filter(b => b.enabled);
  const [nameVn, setNameVn] = useStateS('');
  const [brandKey, setBrandKey] = useStateS(enabledBrands[0]?.key || '');
  const [priceJpy, setPriceJpy] = useStateS('');
  const [salePriceJpy, setSalePriceJpy] = useStateS('');
  const [desc, setDesc] = useStateS('');
  const [images, setImages] = useStateS([]);
  const [dragOver, setDragOver] = useStateS(false);
  const [dropErr, setDropErr] = useStateS('');
  const submittedRef = useRefS(false);
  const fileInputRef = useRefS(null);

  useEffectS(() => () => {
    if (submittedRef.current) return;
    images.forEach(im => URL.revokeObjectURL(im.url));
  }, []);

  const addFiles = (fileList) => {
    setDropErr('');
    const arr = Array.from(fileList || []);
    const accepted = [];
    const rejected = [];
    for (const f of arr) {
      if (!f.type.startsWith('image/')) { rejected.push(`${f.name}: không phải ảnh`); continue; }
      if (f.size > MANUAL_MAX_BYTES) { rejected.push(`${f.name}: > 5MB`); continue; }
      accepted.push(f);
    }
    setImages(prev => {
      const room = MANUAL_MAX_IMAGES - prev.length;
      const take = accepted.slice(0, room);
      const skipped = accepted.length - take.length;
      if (skipped > 0) rejected.push(`${skipped} ảnh bị bỏ (tối đa ${MANUAL_MAX_IMAGES})`);
      const next = take.map(f => ({ id: Math.random().toString(36).slice(2), file: f, url: URL.createObjectURL(f) }));
      return [...prev, ...next];
    });
    if (rejected.length) setDropErr(rejected.join(' · '));
  };

  const removeImage = (id) => {
    setImages(prev => {
      const target = prev.find(im => im.id === id);
      if (target) URL.revokeObjectURL(target.url);
      return prev.filter(im => im.id !== id);
    });
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    addFiles(e.dataTransfer.files);
  };

  const onDragOver = (e) => { e.preventDefault(); setDragOver(true); };
  const onDragLeave = () => setDragOver(false);

  const priceN = +priceJpy;
  const salePriceN = salePriceJpy === '' ? null : +salePriceJpy;
  const nameValid = nameVn.trim().length > 0;
  const priceValid = Number.isFinite(priceN) && priceN > 0;
  const salePriceValid = salePriceN === null || (Number.isFinite(salePriceN) && salePriceN > 0 && salePriceN <= priceN);
  const imagesValid = images.length >= 1;
  const formValid = nameValid && brandKey && priceValid && salePriceValid && imagesValid;

  const submit = () => {
    if (!formValid) return;
    const baseJpy = salePriceN || priceN;
    const jpyOld = salePriceN ? priceN : null;
    const p = P({
      sku: 'MAN-' + Date.now().toString(36).toUpperCase(),
      brand: brandKey,
      vn: nameVn.trim(),
      jp: '',
      jpy: baseJpy,
      jpyOld,
      status: 'eligible',
      source: 'manual',
      created: 'Vừa thêm',
      url: '',
      label: nameVn.trim(),
      desc: desc.trim() || ' ',
      mainImage: images[0]?.url || '',
      score: null,
    });
    p.kind = 'manual';
    p.imageUrls = images.map(im => im.url);
    submittedRef.current = true;
    app.addProduct(p);
    app.toast('Đã thêm sản phẩm thủ công', 'check', 'var(--green)');
    onClose();
    app.go('products');
  };

  return (
    <Modal title="Thêm sản phẩm" sub="Nhập thông tin sản phẩm thủ công · AI sẽ tạo nội dung sau" onClose={onClose} width={720}
      foot={<><div className="topbar-spacer"></div><Button variant="ghost" onClick={onClose}>Hủy</Button><Button variant="primary" icon="plus" disabled={!formValid} onClick={submit}>Thêm sản phẩm</Button></>}>
      <AddModeSwitch mode={mode} setMode={setMode} />
      <div className="manual-form">
        <Field label="Tên sản phẩm (VN)" hint="Bắt buộc · ngắn gọn, đúng chính tả">
          <input className="input" autoFocus value={nameVn} onChange={e => setNameVn(e.target.value)}
                 placeholder="vd: Áo thun nam AIRism Cotton cổ tròn" />
        </Field>
        <Field label="Brand" hint="Bắt buộc">
          <select className="select" value={brandKey} onChange={e => setBrandKey(e.target.value)}>
            {enabledBrands.map(b => <option key={b.key} value={b.key}>{b.name}</option>)}
          </select>
        </Field>
        <Field label="Giá JPY" hint="Bắt buộc · giá gốc trên nhãn">
          <input type="number" min="1" className="input mono" value={priceJpy}
                 onChange={e => setPriceJpy(e.target.value)} placeholder="vd: 2990" />
        </Field>
        <Field label="Giá sale JPY (tùy chọn)" hint={salePriceN !== null && !salePriceValid ? 'Phải ≤ giá gốc' : 'Để trống nếu không sale'}>
          <input type="number" min="1" className="input mono" value={salePriceJpy}
                 onChange={e => setSalePriceJpy(e.target.value)} placeholder="vd: 1990" />
        </Field>
        <div className="field--full">
          <Field label="Mô tả ngắn (tùy chọn)" hint={`${desc.length}/200`}>
            <textarea className="textarea" rows={3} maxLength={200} value={desc}
                      onChange={e => setDesc(e.target.value)} placeholder="Chất liệu, form, ghi chú nội bộ…" />
          </Field>
        </div>
        <div className="field--full">
          <Field label={`Ảnh sản phẩm (${images.length}/${MANUAL_MAX_IMAGES})`} hint="Bắt buộc ít nhất 1 ảnh · tối đa 8 · ≤5MB mỗi ảnh">
            <div className={'dropzone' + (dragOver ? ' is-active' : '')}
                 onDrop={onDrop} onDragOver={onDragOver} onDragLeave={onDragLeave}
                 onClick={() => fileInputRef.current?.click()}
                 role="button" tabIndex={0}>
              {images.length === 0 ? (
                <div className="col" style={{ alignItems: 'center', gap: 6, padding: '20px 8px' }}>
                  <Icon name="upload" size={22} />
                  <div className="t-sm strong">Kéo thả ảnh vào đây</div>
                  <div className="t-xs dimmer">hoặc nhấn để chọn từ máy</div>
                </div>
              ) : (
                <div className="dropzone-thumbs" onClick={e => e.stopPropagation()}>
                  {images.map((im, i) => (
                    <div key={im.id} className="thumb">
                      <img src={im.url} alt="" />
                      {i === 0 && <span className="thumb__main-badge">Chính</span>}
                      <button type="button" className="thumb__remove" aria-label="Xóa ảnh"
                              onClick={() => removeImage(im.id)}>
                        <Icon name="x" size={12} />
                      </button>
                    </div>
                  ))}
                  {images.length < MANUAL_MAX_IMAGES && (
                    <div className="thumb thumb--add" onClick={() => fileInputRef.current?.click()}>
                      <Icon name="plus" size={20} />
                    </div>
                  )}
                </div>
              )}
              <input ref={fileInputRef} type="file" accept="image/*" multiple
                     style={{ display: 'none' }}
                     onChange={e => { addFiles(e.target.files); e.target.value = ''; }} />
            </div>
          </Field>
          {dropErr && <div className="banner banner-warn" style={{ marginTop: 8 }}>
            <Icon name="alert" size={14} style={{ color: 'var(--yellow)' }} />
            <span className="t-xs">{dropErr}</span>
          </div>}
        </div>
      </div>
    </Modal>
  );
}

/* ============ MOBILE MORE ============ */
function MoreScreen() {
  const app = useApp();
  const items = [
    { id: 'sources',   label: 'Nguồn',     icon: 'store',    desc: 'Brand · crawl · KM · watchlist' },
    { id: 'analytics', label: 'Hiệu suất', icon: 'trending', desc: 'Channels · bài đăng · archive' },
    { id: 'settings',  label: 'Cài đặt',   icon: 'settings', desc: 'Toàn bộ tùy chỉnh hệ thống' },
  ];
  return (
    <div className="page-pad">
      <div className="t-h1" style={{ marginBottom: 14 }}>Thêm</div>
      <div className="card" style={{ overflow: 'hidden' }}>
        {items.map((it, i) => (
          <div key={it.id} className="row" style={{ gap: 12, padding: 16, borderBottom: i < items.length - 1 ? '1px solid var(--border)' : 'none', cursor: 'pointer' }} onClick={() => app.go(it.id)}>
            <Icon name={it.icon} size={20} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-sm strong">{it.label}</div>
              <div className="t-2xs dimmer clip-1">{it.desc}</div>
            </div>
            <Icon name="chevronR" size={16} style={{ color: 'var(--text-3)' }} />
          </div>
        ))}
      </div>
      <div className="card" style={{ overflow: 'hidden', marginTop: 12 }}>
        <div className="row" style={{ gap: 12, padding: 16 }}><div className="brand-logo" style={{ background: 'var(--surface-2)', color: 'var(--text)', border: '1px solid var(--border-2)' }}>A</div><div style={{ flex: 1 }}><div className="t-sm strong">Admin Zei</div><div className="t-2xs dimmer">admin@zei.com</div></div><Button variant="ghost" size="sm" icon="lock" /></div>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen, AddProductModal, MoreScreen, Section });
