// screen-content.jsx — Content hub: Composer, Caption Lab, Visual Lab, Tone Library
// Granular intervention points so admin/content team can shape every step before publish.
const { useState: useStateC, useMemo: useMemoC, useEffect: useEffectC } = React;

/* Platform character limits (no-trim rule: generate correct length at LLM source) */
const PLATFORM_LIMITS = {
  facebook:    { cap: 63206, soft: 500,  label: 'Facebook',  icon: 'facebook' },
  instagram:   { cap: 2200,  soft: 300,  label: 'Instagram', icon: 'image' },
  tiktok:      { cap: 4000,  soft: 150,  label: 'TikTok',    icon: 'video' },
  threads:     { cap: 500,   soft: 300,  label: 'Threads',   icon: 'send' },
  x:           { cap: 280,   soft: 280,  label: 'X / Twitter', icon: 'x' },
  linkedin:    { cap: 3000,  soft: 700,  label: 'LinkedIn',  icon: 'briefcase' },
  reddit:      { cap: 10000, soft: 800,  label: 'Reddit',    icon: 'message' },
  youtube:     { cap: 5000,  soft: 300,  label: 'YouTube',   icon: 'video' },
  google_biz:  { cap: 1500,  soft: 300,  label: 'Google Biz',icon: 'store' },
};

const CONTENT_TYPES = [
  { id: 'single',    name: 'Single post',    desc: '1 ảnh + caption. Đơn giản, FB/IG/X dùng nhiều.', icon: 'image' },
  { id: 'carousel',  name: 'Carousel album', desc: '3-10 ảnh swipe. FB carousel hoặc IG album.',      icon: 'gallery' },
  { id: 'composite', name: 'AI composite',   desc: 'Nhiều SP ghép thành 1 lookbook image bằng Banana.', icon: 'sparkle' },
  { id: 'lookbook',  name: 'Lookbook story', desc: 'Story IG/FB 9:16. Multiple frames đan xen.',       icon: 'video' },
  { id: 'inbox_cta', name: 'Inbox CTA',      desc: 'Hook ngắn + nhấn vào inbox để chốt.',              icon: 'send' },
];

/* ========================= 1. COMPOSER (Tạo bài) ========================= */
function ComposeScreen() {
  const app = useApp();
  const composeIds = app.composeIds || [];
  const [step, setStep] = useStateC(1);
  const [channels, setChannels] = useStateC(['facebook', 'instagram']);
  const [toneId, setToneId] = useStateC('zei_youth');
  const [contentType, setContentType] = useStateC(composeIds.length >= 2 ? 'carousel' : 'single');
  const [caption, setCaption] = useStateC('');
  const [generating, setGenerating] = useStateC(false);

  const selected = composeIds.map(id => app.products.find(p => p.id === id)).filter(Boolean);
  const tone = TONE_PRESETS.find(t => t.id === toneId) || TONE_PRESETS[0];

  function toggleChannel(c) { setChannels(cs => cs.includes(c) ? cs.filter(x => x !== c) : [...cs, c]); }

  function generate() {
    setGenerating(true);
    const sample = selected[0] ? generateSampleCaption(selected[0], tone, contentType) : '';
    setTimeout(() => {
      setCaption(sample);
      setGenerating(false);
      setStep(4);
      app.toast && app.toast('Đã tạo caption + ảnh nháp', 'sparkle');
    }, 1100);
  }

  // Empty state — admin landed here without pre-selection (e.g. via direct URL or stale tab)
  if (selected.length === 0) {
    return (
      <div className="page-pad" style={{ maxWidth: 720 }}>
        <div className="t-h1">Tạo bài AI</div>
        <div className="t-sm dim" style={{ marginTop: 2, marginBottom: 18 }}>Mỗi bài bắt đầu từ ít nhất 1 sản phẩm đã duyệt.</div>
        <div className="card card-pad" style={{ textAlign: 'center', padding: '40px 24px' }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
            <Icon name="package" size={26} />
          </div>
          <div className="t-h2" style={{ marginBottom: 6 }}>Chưa có sản phẩm để tạo bài</div>
          <div className="t-sm dim" style={{ maxWidth: 440, margin: '0 auto 20px', lineHeight: 1.6 }}>
            Vào tab <strong>Sản phẩm</strong>, chọn 1 hoặc nhiều SP đã duyệt rồi bấm <strong>Tạo bài</strong>. Hệ thống sẽ mở wizard này với SP đã chọn sẵn.
          </div>
          <Button variant="primary" icon="package" onClick={() => app.go('products', 'pool')}>Đi qua tab Sản phẩm</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="page-pad" style={{ maxWidth: 1100 }}>
      <div className="row" style={{ marginBottom: 14, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div className="t-h1">Tạo bài AI</div>
          <div className="t-sm dim" style={{ marginTop: 2 }}>4 bước có thể can thiệp từng bước. Nháp lưu tự động.</div>
        </div>
        <div className="row gap-sm">
          <Button variant="ghost" size="sm" icon="package" onClick={() => app.go('products', 'pool')}>Quay về Sản phẩm</Button>
          <Button variant="ghost" size="sm" icon="rotate" onClick={() => { setStep(1); setCaption(''); }}>Reset bước</Button>
        </div>
      </div>

      {/* Selected products context bar */}
      <div className="card" style={{ padding: '10px 14px', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <Icon name="package" size={16} style={{ color: 'var(--accent)' }} />
        <span className="t-sm strong">Tạo bài cho {selected.length} sản phẩm:</span>
        <div className="row gap-sm" style={{ flexWrap: 'wrap', flex: 1, minWidth: 0 }}>
          {selected.slice(0, 4).map(p => {
            const b = brandOf(p.brand);
            return (
              <div key={p.id} className="row gap-sm" style={{ padding: '4px 8px', background: 'var(--surface-2)', borderRadius: 'var(--r-md)', maxWidth: 220 }}>
                <BrandLogo brand={b} size={14} />
                <span className="t-2xs clip-1 strong">{p.titleVn}</span>
                {p.kind === 'manual' && <Badge variant="neutral" icon="edit">Nhập tay</Badge>}
              </div>
            );
          })}
          {selected.length > 4 && <span className="t-2xs dimmer">+{selected.length - 4} sản phẩm</span>}
        </div>
      </div>

      {/* Stepper */}
      <Stepper step={step} setStep={setStep} steps={[
        { n: 1, label: 'Kênh đăng',    done: channels.length > 0 },
        { n: 2, label: 'Giọng văn',    done: !!toneId },
        { n: 3, label: 'Kiểu content', done: !!contentType },
        { n: 4, label: 'Tạo & Edit',   done: !!caption },
      ]} />

      {/* Step content */}
      <div className="card card-pad" style={{ marginTop: 14 }}>
        {step === 1 && <Step1Channels channels={channels} toggleChannel={toggleChannel} next={() => channels.length > 0 && setStep(2)} />}
        {step === 2 && <Step2Tone toneId={toneId} setToneId={setToneId} back={() => setStep(1)} next={() => setStep(3)} />}
        {step === 3 && <Step3Type contentType={contentType} setContentType={setContentType} back={() => setStep(2)} onGenerate={generate} generating={generating} multi={selected.length >= 2} />}
        {step === 4 && <Step4Edit selected={selected} channels={channels} tone={tone} contentType={contentType} caption={caption} setCaption={setCaption} back={() => setStep(3)} app={app} />}
      </div>
    </div>
  );
}

function Stepper({ step, setStep, steps }) {
  return (
    <div className="row" style={{ background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 6, gap: 0, overflowX: 'auto' }}>
      {steps.map((s, i) => (
        <React.Fragment key={s.n}>
          <button onClick={() => setStep(s.n)} className="row gap-sm" style={{
            padding: '8px 12px', borderRadius: 'var(--r-md)', cursor: 'pointer', whiteSpace: 'nowrap',
            background: step === s.n ? 'var(--accent)' : 'transparent',
            color: step === s.n ? 'var(--accent-text)' : s.done ? 'var(--text)' : 'var(--text-3)',
            border: 'none', fontWeight: 600, fontSize: 'calc(13px * var(--fs))',
          }}>
            <span style={{ width: 20, height: 20, borderRadius: '50%', background: step === s.n ? 'var(--accent-text)' : s.done ? 'var(--green)' : 'var(--border-2)', color: step === s.n ? 'var(--accent)' : s.done ? '#fff' : 'var(--text-3)', display: 'inline-grid', placeItems: 'center', fontSize: 11 }}>
              {s.done ? '✓' : s.n}
            </span>
            {s.label}
          </button>
          {i < steps.length - 1 && <div style={{ width: 18, height: 1, background: 'var(--border)', alignSelf: 'center' }}></div>}
        </React.Fragment>
      ))}
    </div>
  );
}

function Step1Channels({ channels, toggleChannel, next }) {
  return (
    <>
      <div className="between" style={{ marginBottom: 12 }}>
        <div>
          <div className="t-h2">Kênh đăng</div>
          <div className="t-2xs dimmer">Chọn nhiều kênh, hệ thống sinh caption đúng độ dài cho từng nền tảng.</div>
        </div>
        <Button variant="primary" size="sm" iconR="chevronR" onClick={next} disabled={channels.length === 0}>Tiếp · {channels.length} kênh</Button>
      </div>
      <div className="grid-3" style={{ gap: 10 }}>
        {SOCIAL_CHANNELS.map(c => {
          const on = channels.includes(c.key);
          const cap = PLATFORM_LIMITS[c.key];
          const disabled = c.enabled === false;
          return (
            <div key={c.key} className="card" onClick={() => !disabled && toggleChannel(c.key)} style={{
              padding: 12, cursor: disabled ? 'not-allowed' : 'pointer',
              opacity: disabled ? 0.55 : 1,
              border: '2px solid ' + (on ? c.color || 'var(--accent)' : 'var(--border)'),
              background: on ? 'var(--accent-soft)' : 'var(--surface)'
            }}>
              <div className="row gap-sm">
                <span style={{
                  display: 'grid', placeItems: 'center', width: 32, height: 32, borderRadius: 8,
                  background: c.color || 'var(--surface-2)', color: '#fff', flexShrink: 0
                }}>
                  <Icon name={c.icon || 'globe'} size={18} />
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="t-sm strong clip-1">{c.label}</div>
                  <div className="t-2xs dimmer clip-1">{c.handle}</div>
                </div>
                {on && <Icon name="check" size={16} style={{ color: 'var(--accent)' }} />}
              </div>
              <div className="row gap-sm" style={{ marginTop: 6 }}>
                {cap && <span className="t-2xs dimmer mono">≤ {cap.soft} ký tự</span>}
                {disabled && <span className="t-2xs" style={{ color: 'var(--yellow)' }}>Chưa kích hoạt</span>}
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

function Step2Tone({ toneId, setToneId, back, next }) {
  return (
    <>
      <div className="between" style={{ marginBottom: 12 }}>
        <div>
          <div className="t-h2">Giọng văn</div>
          <div className="t-2xs dimmer">Mỗi preset có persona, hashtag, ví dụ tham chiếu để AI bắt chước.</div>
        </div>
        <div className="row gap-sm">
          <Button variant="ghost" size="sm" icon="chevronL" onClick={back}>Quay lại</Button>
          <Button variant="primary" size="sm" iconR="chevronR" onClick={next}>Tiếp</Button>
        </div>
      </div>
      <div className="grid-3" style={{ gap: 10 }}>
        {TONE_PRESETS.map(t => {
          const on = toneId === t.id;
          return (
            <div key={t.id} className="card" onClick={() => setToneId(t.id)} style={{
              padding: 12, cursor: 'pointer',
              border: '2px solid ' + (on ? 'var(--accent)' : 'var(--border)'),
              background: on ? 'var(--accent-soft)' : 'var(--surface)'
            }}>
              <div className="row gap-sm" style={{ marginBottom: 6 }}>
                <span style={{ fontSize: 20 }}>{t.emoji.split('')[0]}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="t-sm strong">{t.name}</div>
                  <div className="t-2xs dimmer clip-1">{t.persona}</div>
                </div>
                {on && <Icon name="check" size={16} style={{ color: 'var(--accent)' }} />}
              </div>
              <div className="t-2xs" style={{ fontStyle: 'italic', lineHeight: 1.5, color: 'var(--text-2)' }}>"{t.sample.slice(0, 90)}{t.sample.length > 90 ? '…' : ''}"</div>
            </div>
          );
        })}
      </div>
    </>
  );
}

function Step3Type({ contentType, setContentType, back, onGenerate, generating, multi }) {
  return (
    <>
      <div className="between" style={{ marginBottom: 12 }}>
        <div>
          <div className="t-h2">Kiểu content</div>
          <div className="t-2xs dimmer">{multi ? 'Nhiều SP — gợi ý carousel hoặc lookbook composite.' : '1 SP — gợi ý single. Quyết định flow tạo ảnh và caption.'}</div>
        </div>
        <div className="row gap-sm">
          <Button variant="ghost" size="sm" icon="chevronL" onClick={back} disabled={generating}>Quay lại</Button>
          <Button variant="primary" size="sm" icon="sparkle" onClick={onGenerate} disabled={generating}>
            {generating ? 'Đang tạo…' : 'Tạo nháp'}
          </Button>
        </div>
      </div>
      <div className="grid-2" style={{ gap: 10 }}>
        {CONTENT_TYPES.map(ct => {
          const on = contentType === ct.id;
          return (
            <div key={ct.id} className="card card-pad" onClick={() => setContentType(ct.id)} style={{
              padding: 14, cursor: 'pointer',
              border: '2px solid ' + (on ? 'var(--accent)' : 'var(--border)'),
              background: on ? 'var(--accent-soft)' : 'var(--surface)'
            }}>
              <div className="row gap-sm">
                <div style={{ width: 36, height: 36, borderRadius: 'var(--r-sm)', background: on ? 'var(--accent)' : 'var(--surface-2)', color: on ? 'var(--accent-text)' : 'var(--text)', display: 'grid', placeItems: 'center' }}>
                  <Icon name={ct.icon} size={18} />
                </div>
                <div style={{ flex: 1 }}>
                  <div className="t-sm strong">{ct.name}</div>
                  <div className="t-2xs dim" style={{ marginTop: 2 }}>{ct.desc}</div>
                </div>
                {on && <Icon name="check" size={16} style={{ color: 'var(--accent)' }} />}
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

function Step4Edit({ selected, channels, tone, contentType, caption, setCaption, back, app }) {
  return (
    <>
      <div className="between" style={{ marginBottom: 12 }}>
        <div>
          <div className="t-h2">Edit & Preview</div>
          <div className="t-2xs dimmer">Sửa caption, xem độ dài theo từng kênh. Bấm "Vào hàng chờ duyệt" để gửi qua bước duyệt cuối.</div>
        </div>
        <div className="row gap-sm">
          <Button variant="ghost" size="sm" icon="chevronL" onClick={back}>Quay lại</Button>
          <Button variant="default" size="sm" icon="refresh" onClick={() => app.toast && app.toast('Đang tạo lại caption...', 'sparkle')}>Tạo lại</Button>
          <Button variant="primary" size="sm" icon="send" onClick={() => app.toast && app.toast('Đã chuyển bài qua bước duyệt', 'check')}>Vào hàng chờ duyệt</Button>
        </div>
      </div>
      <div className="grid-2" style={{ gap: 16, alignItems: 'start' }}>
        <div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>CAPTION</div>
          <textarea className="textarea" rows={10} value={caption} onChange={e => setCaption(e.target.value)} />
          <div className="row gap-sm" style={{ marginTop: 8, flexWrap: 'wrap' }}>
            {channels.map(ch => {
              const cap = PLATFORM_LIMITS[ch];
              if (!cap) return null;
              const len = caption.length;
              const okSoft = len <= cap.soft;
              const okHard = len <= cap.cap;
              return (
                <Badge key={ch} variant={okSoft ? 'green' : okHard ? 'yellow' : 'red'}>
                  {cap.label}: {len}/{cap.soft}
                </Badge>
              );
            })}
          </div>
          <div className="divider"></div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>HASHTAG SET (từ tone "{tone.name}")</div>
          <div className="row gap-sm" style={{ flexWrap: 'wrap' }}>
            {tone.hashtagSet.map(h => <Badge key={h} variant="neutral">{h}</Badge>)}
            <Button variant="ghost" size="sm" icon="plus">Thêm hashtag</Button>
          </div>
        </div>
        <div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>PREVIEW</div>
          <div className="card" style={{ padding: 12, background: 'var(--bg-2)' }}>
            {selected[0] && <Placeholder label={selected[0].label} brand={brandOf(selected[0].brand)} ratio="4/3" big style={{ marginBottom: 10 }} />}
            <div className="t-sm" style={{ whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>{caption || <span className="dimmer">(caption sẽ hiện ở đây)</span>}</div>
            <div className="divider"></div>
            <div className="row gap-sm" style={{ flexWrap: 'wrap' }}>
              {selected.slice(0, 3).map(p => (
                <div key={p.id} className="row gap-sm" style={{ padding: '4px 8px', background: 'var(--surface)', borderRadius: 'var(--r-md)' }}>
                  <BrandLogo brand={brandOf(p.brand)} size={16} />
                  <span className="t-2xs strong">{fmtVND(p.priceVnd || p.vnd)}</span>
                </div>
              ))}
              {selected.length > 3 && <span className="t-2xs dimmer">+{selected.length - 3}</span>}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function generateSampleCaption(p, tone, contentType) {
  const price = fmtVND(p.priceVnd || p.vnd);
  const discPart = p.disc > 0 ? `Giảm ${p.disc}% ` : '';
  const coupon = p.couponPercent > 0 ? ` (+ coupon ${p.couponPercent}% từ ${brandOf(p.brand).name})` : '';
  const cta = tone.id === 'inbox_cta' ? '\nInbox shop chốt đơn ngay!' : tone.id === 'lifestyle' ? '\nĐặt qua Zei JP, ship 7-10 ngày từ Nhật.' : '\nLink trong bio · Zei JP';
  const hashtags = tone.hashtagSet.join(' ');
  return `${tone.emoji.split('')[0]} ${discPart}${p.titleVn}\n${p.desc.slice(0, 100)}…\nGiá Zei JP: ${price}${coupon}.${cta}\n\n${hashtags}`;
}

/* ========================= 2. CAPTION LAB ========================= */
function CaptionLabScreen() {
  const app = useApp();
  const queue = useMemoC(() => POSTS.filter(po => po.status === 'text_pending'), []);
  const [openId, setOpenId] = useStateC(queue[0] ? queue[0].id : null);
  const openPost = queue.find(p => p.id === openId) || queue[0];
  const [variantA, setVariantA] = useStateC(openPost ? openPost.caption : '');
  const [variantB, setVariantB] = useStateC('');
  const [activeVariant, setActiveVariant] = useStateC('A');
  const [platforms, setPlatforms] = useStateC(['facebook', 'instagram']);

  useEffectC(() => {
    if (openPost) {
      setVariantA(openPost.caption || '');
      setVariantB('');
    }
  }, [openId]);

  function regenVariantB() {
    if (!openPost) return;
    const p = app.products.find(x => x.id === openPost.productId);
    if (!p) return;
    const tone = TONE_PRESETS[Math.floor(Math.random() * TONE_PRESETS.length)];
    setVariantB(generateSampleCaption(p, tone, 'single'));
    app.toast && app.toast('Đã gen variant B với tone "' + tone.name + '"', 'sparkle');
  }

  if (!openPost) {
    return <div className="page-pad"><Empty icon="sparkle" title="Không có caption đang chờ" desc="Caption Lab chỉ hiện khi có bài đang ở trạng thái chờ duyệt text." /></div>;
  }

  const p = app.products.find(x => x.id === openPost.productId);
  const active = activeVariant === 'A' ? variantA : variantB;
  const setActive = activeVariant === 'A' ? setVariantA : setVariantB;

  return (
    <div className="page-pad wide">
      <div className="row" style={{ marginBottom: 14, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div className="t-h1">Caption Lab</div>
          <div className="t-sm dim" style={{ marginTop: 2 }}>{queue.length} caption đang chờ · A/B variant · regen từng dòng · spell-check · length per platform.</div>
        </div>
        <Button variant="primary" size="sm" icon="check" onClick={() => app.toast && app.toast('Đã commit variant ' + activeVariant, 'check')}>Commit variant {activeVariant}</Button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 14, alignItems: 'start' }}>
        {/* Queue list */}
        <div className="card" style={{ overflow: 'hidden', maxHeight: 600, overflowY: 'auto' }}>
          {queue.map(po => {
            const product = app.products.find(x => x.id === po.productId);
            const b = product ? brandOf(product.brand) : null;
            return (
              <div key={po.id} onClick={() => setOpenId(po.id)} style={{
                padding: 10, cursor: 'pointer', borderBottom: '1px solid var(--border)',
                background: openId === po.id ? 'var(--accent-soft)' : 'transparent'
              }}>
                <div className="row gap-sm">
                  {b && <BrandLogo brand={b} size={20} />}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="t-xs strong clip-1">{product ? product.titleVn : '(unknown)'}</div>
                    <div className="t-2xs dimmer mono clip-1">{po.id}</div>
                  </div>
                  <StatusPill status={po.status} />
                </div>
              </div>
            );
          })}
        </div>

        {/* Editor */}
        <div>
          {/* Platforms selector */}
          <div className="card card-pad" style={{ marginBottom: 12 }}>
            <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>HIỂN THỊ COUNT THEO</div>
            <div className="row gap-sm" style={{ flexWrap: 'wrap' }}>
              {Object.entries(PLATFORM_LIMITS).map(([k, c]) => (
                <button key={k} className={'badge ' + (platforms.includes(k) ? 'badge-accent' : 'badge-neutral')}
                  style={{ cursor: 'pointer' }}
                  onClick={() => setPlatforms(ps => ps.includes(k) ? ps.filter(x => x !== k) : [...ps, k])}>
                  {c.label}
                </button>
              ))}
            </div>
          </div>

          {/* Variant tabs */}
          <div className="row" style={{ marginBottom: 10, gap: 8 }}>
            {['A', 'B'].map(v => (
              <button key={v} onClick={() => setActiveVariant(v)} className={'btn ' + (activeVariant === v ? 'btn-primary' : 'btn-default') + ' btn-sm'}>
                Variant {v}{v === 'B' && !variantB && ' (chưa gen)'}
              </button>
            ))}
            <div className="topbar-spacer"></div>
            <Button variant="ghost" size="sm" icon="sparkle" onClick={regenVariantB}>Re-gen variant B (random tone)</Button>
          </div>

          {/* Editor */}
          <div className="card card-pad">
            <textarea className="textarea" rows={10} value={active} onChange={e => setActive(e.target.value)} />
            <div className="row gap-sm" style={{ marginTop: 8, flexWrap: 'wrap' }}>
              {platforms.map(plt => {
                const cap = PLATFORM_LIMITS[plt];
                const len = active.length;
                const okSoft = len <= cap.soft;
                const okHard = len <= cap.cap;
                return (
                  <Badge key={plt} variant={okSoft ? 'green' : okHard ? 'yellow' : 'red'}>
                    {cap.label}: {len}/{cap.soft}
                  </Badge>
                );
              })}
            </div>
            <div className="divider"></div>
            <div className="row gap-sm" style={{ flexWrap: 'wrap' }}>
              <Button variant="ghost" size="sm" icon="sparkle" onClick={() => app.toast && app.toast('Regen dòng đầu', 'sparkle')}>Regen dòng 1</Button>
              <Button variant="ghost" size="sm" icon="sparkle" onClick={() => app.toast && app.toast('Regen CTA', 'sparkle')}>Regen CTA</Button>
              <Button variant="ghost" size="sm" icon="check">Spell-check</Button>
              <Button variant="ghost" size="sm" icon="palette">Emoji set</Button>
              <Button variant="ghost" size="sm" icon="filter">Lọc hashtag spam</Button>
            </div>
          </div>

          {/* Side-by-side compare */}
          {variantB && (
            <div className="grid-2" style={{ marginTop: 14, gap: 12 }}>
              {['A', 'B'].map(v => {
                const text = v === 'A' ? variantA : variantB;
                return (
                  <div key={v} className="card card-pad" style={{ background: activeVariant === v ? 'var(--accent-soft)' : 'var(--bg-2)' }}>
                    <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>VARIANT {v}</div>
                    <div className="t-xs" style={{ whiteSpace: 'pre-wrap', lineHeight: 1.6, maxHeight: 200, overflowY: 'auto' }}>{text || '(empty)'}</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ========================= 3. VISUAL LAB ========================= */
function VisualLabScreen() {
  const app = useApp();
  const queue = useMemoC(() => POSTS.filter(po => ['text_pending', 'image_pending'].includes(po.status)), []);
  const [openId, setOpenId] = useStateC(queue[0] ? queue[0].id : null);
  const openPost = queue.find(p => p.id === openId) || queue[0];
  const product = openPost ? app.products.find(x => x.id === openPost.productId) : null;
  const [frame, setFrame] = useStateC('zei_main');
  const [overlayPrice, setOverlayPrice] = useStateC(true);
  const [overlayDisc, setOverlayDisc] = useStateC(true);
  const [overlayLogo, setOverlayLogo] = useStateC(true);
  const [model, setModel] = useStateC('asian_22');
  const [prompt, setPrompt] = useStateC('');
  const [variants, setVariants] = useStateC(3);

  useEffectC(() => {
    if (product) {
      setPrompt(`Cô gái Á Đông 22-25 tuổi, mặc ${product.titleVn.toLowerCase()}, phong cách trẻ trung, ánh sáng studio mềm, phông nền tối giản, focus vào sản phẩm. Aspect 4:3. Style ${brandOf(product.brand).name} lookbook.`);
    }
  }, [openId, product]);

  if (!openPost || !product) {
    return <div className="page-pad"><Empty icon="sparkle" title="Không có bài cần làm visual" desc="Visual Lab chỉ hiện khi có post ở trạng thái chờ duyệt text hoặc chờ duyệt ảnh." /></div>;
  }

  const frames = [
    { id: 'zei_main',    name: 'Zei JP main',     desc: 'Frame chính Zei JP — logo + brand color' },
    { id: 'zei_sale',    name: 'Zei JP sale',     desc: 'Badge giảm giá to + giá VND' },
    { id: 'zei_lookbook',name: 'Lookbook',        desc: 'Magazine style, không nhiều text' },
    { id: 'zei_story',   name: '9:16 Story',      desc: 'Dọc cho IG/FB story' },
    { id: 'zei_carousel',name: 'Carousel cover',  desc: 'Cover ảnh đầu carousel' },
    { id: 'zei_none',    name: 'Không frame',     desc: 'Raw image, không overlay text' },
  ];
  const models = [
    { id: 'asian_22',  name: 'Nữ Á 22-25',     desc: 'Tóc đen dài, 1m65, trẻ năng động' },
    { id: 'asian_27',  name: 'Nữ Á 27-30',     desc: 'Sang trọng, business casual' },
    { id: 'asian_m',   name: 'Nam Á 25-28',    desc: 'Streetwear, atletic' },
    { id: 'flatlay',   name: 'Flat-lay (no model)', desc: 'Chỉ sản phẩm — phù hợp basics' },
  ];

  return (
    <div className="page-pad wide">
      <div className="row" style={{ marginBottom: 14, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div className="t-h1">Visual Lab</div>
          <div className="t-sm dim" style={{ marginTop: 2 }}>Studio ảnh AI · model lock, frame brand, overlay price · batch 3-5 variants từ Banana Pro.</div>
        </div>
        <Button variant="primary" size="sm" icon="sparkle" onClick={() => app.toast && app.toast('Đang gen ' + variants + ' variant bằng Banana Pro…', 'sparkle')}>Gen {variants} variant</Button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr 320px', gap: 14, alignItems: 'start' }}>
        {/* Queue */}
        <div className="card" style={{ overflow: 'hidden', maxHeight: 600, overflowY: 'auto' }}>
          {queue.map(po => {
            const pr = app.products.find(x => x.id === po.productId);
            if (!pr) return null;
            const b = brandOf(pr.brand);
            return (
              <div key={po.id} onClick={() => setOpenId(po.id)} style={{
                padding: 10, cursor: 'pointer', borderBottom: '1px solid var(--border)',
                background: openId === po.id ? 'var(--accent-soft)' : 'transparent'
              }}>
                <div className="row gap-sm">
                  <Placeholder label="" brand={b} ratio="3/4" style={{ width: 30, height: 40, borderRadius: 4 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="t-xs strong clip-1">{pr.titleVn}</div>
                    <div className="t-2xs dimmer mono">{pr.sku}</div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Preview */}
        <div>
          <div className="grid-2" style={{ gap: 10 }}>
            {Array.from({ length: variants }).map((_, i) => (
              <div key={i} className="card" style={{ padding: 8, position: 'relative' }}>
                <Placeholder label={'Variant ' + (i + 1)} brand={brandOf(product.brand)} ratio="4/3" big style={{ borderRadius: 'var(--r-md)' }} />
                {overlayPrice && (
                  <div style={{ position: 'absolute', bottom: 14, left: 14, background: 'rgba(0,0,0,0.7)', color: '#fff', padding: '4px 10px', borderRadius: 'var(--r-sm)', fontFamily: 'JetBrains Mono, monospace', fontSize: 13, fontWeight: 700 }}>
                    {fmtVND(product.priceVnd || product.vnd)}
                  </div>
                )}
                {overlayDisc && product.disc > 0 && (
                  <div style={{ position: 'absolute', top: 14, right: 14, background: 'var(--red)', color: '#fff', padding: '6px 10px', borderRadius: '50%', width: 50, height: 50, display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 14 }}>
                    -{product.disc}%
                  </div>
                )}
                {overlayLogo && (
                  <div style={{ position: 'absolute', top: 14, left: 14, background: 'rgba(255,255,255,0.9)', padding: '4px 8px', borderRadius: 'var(--r-sm)', fontSize: 11, fontWeight: 700, color: 'var(--accent)' }}>Zei JP</div>
                )}
                <div className="row gap-sm" style={{ marginTop: 8 }}>
                  <Button variant="ghost" size="sm" icon="check" onClick={() => app.toast && app.toast('Đã chọn variant ' + (i + 1), 'check')}>Chọn</Button>
                  <Button variant="ghost" size="sm" icon="rotate" onClick={() => app.toast && app.toast('Đang regen variant ' + (i + 1), 'sparkle')}>Regen</Button>
                  <Button variant="ghost" size="sm" icon="external"></Button>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Controls */}
        <div className="card card-pad">
          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>FRAME BRAND</div>
          <div className="col" style={{ gap: 6, marginBottom: 14 }}>
            {frames.map(f => (
              <button key={f.id} onClick={() => setFrame(f.id)} style={{
                padding: '8px 10px', borderRadius: 'var(--r-md)', cursor: 'pointer', textAlign: 'left',
                background: frame === f.id ? 'var(--accent-soft)' : 'var(--bg-2)',
                border: '1px solid ' + (frame === f.id ? 'var(--accent)' : 'var(--border)'),
                color: 'var(--text)',
              }}>
                <div className="t-xs strong">{f.name}</div>
                <div className="t-2xs dimmer">{f.desc}</div>
              </button>
            ))}
          </div>

          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>OVERLAY</div>
          <div className="col" style={{ gap: 8, marginBottom: 14 }}>
            <div className="between"><span className="t-xs">Giá VND</span><Toggle on={overlayPrice} onChange={setOverlayPrice} /></div>
            <div className="between"><span className="t-xs">Badge % giảm</span><Toggle on={overlayDisc} onChange={setOverlayDisc} /></div>
            <div className="between"><span className="t-xs">Logo Zei JP</span><Toggle on={overlayLogo} onChange={setOverlayLogo} /></div>
          </div>

          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>MODEL</div>
          <select className="select" value={model} onChange={e => setModel(e.target.value)} style={{ marginBottom: 14 }}>
            {models.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
          </select>

          <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>SỐ VARIANT</div>
          <Seg value={String(variants)} options={[{ value: '1', label: '1' }, { value: '3', label: '3' }, { value: '5', label: '5' }]} onChange={v => setVariants(+v)} />

          <div className="divider"></div>
          <div className="t-2xs strong dimmer" style={{ marginBottom: 6 }}>PROMPT BANANA PRO</div>
          <textarea className="textarea mono t-2xs" rows={6} value={prompt} onChange={e => setPrompt(e.target.value)} />
          <div className="t-2xs dimmer" style={{ marginTop: 6 }}>Tuân nano-banana-pro-prompts-recommend-skill</div>
        </div>
      </div>
    </div>
  );
}

/* ========================= 4. TONE LIBRARY ========================= */
function ToneLibraryScreen() {
  const app = useApp();
  const [openId, setOpenId] = useStateC(null);
  const openTone = TONE_PRESETS.find(t => t.id === openId);

  return (
    <div className="page-pad wide">
      <div className="row" style={{ marginBottom: 14, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div className="t-h1">Tone Library</div>
          <div className="t-sm dim" style={{ marginTop: 2 }}>{TONE_PRESETS.length} tone presets · click "Use this tone" → mở Composer với tone đã chọn sẵn.</div>
        </div>
        <Button variant="primary" size="sm" icon="plus" onClick={() => app.toast && app.toast('Tạo tone mới — clone từ preset gần nhất', 'plus')}>Tone mới</Button>
      </div>

      <div className="grid-3" style={{ gap: 16, alignItems: 'start' }}>
        {TONE_PRESETS.map(t => (
          <div key={t.id} className="card card-pad">
            <div className="row gap-sm" style={{ marginBottom: 10 }}>
              <div style={{ width: 44, height: 44, borderRadius: 'var(--r-md)', background: 'var(--bg-2)', display: 'grid', placeItems: 'center', fontSize: 24 }}>
                {t.emoji.split('')[0]}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="t-h2 clip-1">{t.name}</div>
                <div className="t-2xs dimmer clip-1">{t.persona}</div>
              </div>
            </div>
            <div className="panel" style={{ padding: 12, marginBottom: 12, background: 'var(--bg-2)' }}>
              <div className="t-2xs strong dimmer" style={{ marginBottom: 4 }}>CAPTION MẪU</div>
              <div className="t-xs" style={{ lineHeight: 1.6 }}>"{t.sample}"</div>
            </div>
            <div className="t-2xs strong dimmer" style={{ marginBottom: 4 }}>HASHTAG</div>
            <div className="row gap-sm" style={{ flexWrap: 'wrap', marginBottom: 12 }}>
              {t.hashtagSet.map(h => <Badge key={h} variant="neutral">{h}</Badge>)}
            </div>
            <div className="row gap-sm">
              <Button variant="primary" size="sm" icon="sparkle" className="btn-block" onClick={() => app.toast && app.toast('Mở Composer với tone "' + t.name + '"', 'sparkle')}>Dùng tone này</Button>
              <Button variant="ghost" size="sm" icon="edit" onClick={() => setOpenId(t.id)}></Button>
            </div>
          </div>
        ))}
      </div>

      {openTone && (
        <Drawer title={'Chi tiết tone · ' + openTone.name} sub={openTone.persona} onClose={() => setOpenId(null)}
          foot={<>
            <Button variant="ghost" onClick={() => setOpenId(null)}>Đóng</Button>
            <Button variant="primary" icon="sparkle" onClick={() => { app.toast && app.toast('Mở Composer với tone "' + openTone.name + '"', 'sparkle'); setOpenId(null); }}>Dùng tone này</Button>
          </>}>
          <Field label="Persona"><textarea className="textarea" rows={2} defaultValue={openTone.persona} /></Field>
          <div style={{ height: 10 }}></div>
          <Field label="Emoji set"><input className="input" defaultValue={openTone.emoji} /></Field>
          <div style={{ height: 10 }}></div>
          <Field label="Caption mẫu"><textarea className="textarea" rows={3} defaultValue={openTone.sample} /></Field>
          <div className="divider"></div>
          <div className="grid-2" style={{ gap: 12 }}>
            <Field label="DO"><textarea className="textarea" rows={4} defaultValue={openTone.do.join('\n')} /></Field>
            <Field label="DON'T"><textarea className="textarea" rows={4} defaultValue={openTone.dont.join('\n')} /></Field>
          </div>
        </Drawer>
      )}
    </div>
  );
}

Object.assign(window, {
  ComposeScreen, CaptionLabScreen, VisualLabScreen, ToneLibraryScreen,
  PLATFORM_LIMITS, CONTENT_TYPES,
});
