// Screen: CONTENT & PLANS (v3 — Purchase tabs + FB post UI + inline chat)

// ── Purchase categories ───────────────────────────────────────

const PURCHASE_CATEGORIES = [
  {
    id: 'sale',
    icon: 'tag',
    label: 'Sale & Ưu đãi',
    sub: 'Khuyến mãi · Deal hot · Flash sale',
    color: '#F87171',
    angle: 'GÓC CONTENT YÊU CẦU — SALE & ƯU ĐÃI: Viết 1 option đại diện, tập trung vào khuyến mãi, giảm giá, deal không thể bỏ lỡ, tạo urgency "mua ngay kẻo hết". Hook mạnh, cảm xúc cao, CTA rõ.',
  },
  {
    id: 'pain',
    icon: 'activity',
    label: 'Nỗi đau',
    sub: 'Pain points · Vấn đề · Giải pháp',
    color: '#F472B6',
    angle: 'GÓC CONTENT YÊU CẦU — NỖI ĐAU: Viết 1 option đại diện, đánh trúng vấn đề/frustration/nỗi sợ lớn nhất của khách hàng rồi dẫn đến sản phẩm như giải pháp. Hook cảm xúc mạnh.',
  },
  {
    id: 'feature',
    icon: 'zap',
    label: 'Tính năng',
    sub: 'USP · Chức năng · So sánh',
    color: '#66FCF1',
    angle: 'GÓC CONTENT YÊU CẦU — TÍNH NĂNG VƯỢT TRỘI: Viết 1 option đại diện, tập trung vào USP độc đáo nhất, so sánh trước/sau hoặc showcase tính năng nổi bật nhất của sản phẩm.',
  },
  {
    id: 'event',
    icon: 'gift',
    label: 'Sự kiện',
    sub: 'Sinh nhật · Khai trương · Holiday',
    color: '#FBBF24',
    angle: 'GÓC CONTENT YÊU CẦU — SỰ KIỆN ĐẶC BIỆT: Viết 1 option đại diện kết hợp dịp đặc biệt phù hợp nhất (lễ tết, khai trương, Black Friday...) với ưu đãi và cảm xúc của sự kiện đó.',
  },
  {
    id: 'trending',
    icon: 'trending-up',
    label: 'Trending',
    sub: 'Content viral · Format thị trường',
    color: '#A78BFA',
    angle: 'GÓC CONTENT YÊU CẦU — TRENDING & VIRAL: Viết 1 option đại diện dùng style content đang scale mạnh nhất trên Facebook/TikTok — hook viral, storytelling trend, review authentic hoặc POV format.',
  },
];

// ── Parsers ───────────────────────────────────────────────────

function parseContentPurchase(text) {
  const results = [];
  const lines = text.split('\n');
  let current = null;
  const contentLines = [];

  const flush = () => {
    if (!current) return;
    const raw = cleanText(contentLines.join('\n').trim());
    const firstLine = raw.split('\n').find(l => l.trim()) || '';
    current.content = raw;
    current.hook    = firstLine.trim().slice(0, 140);
    results.push({ ...current });
    current = null;
    contentLines.length = 0;
  };

  for (const line of lines) {
    const optM = line.match(/^##\s+OPTION\s+(\d+)\s*[—\-]?\s*(.*)/i);
    if (optM) {
      flush();
      current = {
        key: `opt-${results.length}`,
        idx: parseInt(optM[1]),
        name: optM[2].trim() || `Option ${parseInt(optM[1])}`,
        content: '', hook: '',
      };
      continue;
    }
    if (current) contentLines.push(line);
  }
  flush();
  return results;
}

function parseBrandCampaign(text) {
  const days = [];
  const lines = text.split('\n');
  let currentDay  = null;
  let currentPost = null;
  let inContent   = false;
  const contentLines = [];

  const flushPost = () => {
    if (!currentPost || !currentDay) return;
    currentPost.content = cleanText(contentLines.join('\n').trim());
    const firstLine = contentLines.find(l => l.trim()) || '';
    if (!currentPost.hook && firstLine) currentPost.hook = cleanText(firstLine.trim()).slice(0, 140);
    currentDay.posts.push({ ...currentPost });
    currentPost = null;
    inContent = false;
    contentLines.length = 0;
  };

  for (const line of lines) {
    const dayM     = line.match(/^##\s+DAY\s+(\d+)\s*[—\-]?\s*(.*)/i);
    const postM    = line.match(/^###\s+POST\s+([\d.]+)\s*[—\-]?\s*(.*)/i);
    const contentM = line.match(/^###\s+CONTENT:?\s*$/i);

    if (dayM) {
      flushPost();
      const idx = parseInt(dayM[1]);
      currentDay = { idx, label: dayM[2].trim() || `Ngày ${idx}`, posts: [] };
      days.push(currentDay);
      inContent = false;
      continue;
    }
    if (postM && currentDay) {
      flushPost();
      currentPost = {
        key: `day-${currentDay.idx}-post-${postM[1]}`,
        dayIdx: currentDay.idx, postIdx: postM[1],
        type: postM[2].trim(),
        stage: '', goal: '', psychology: '', emotionalTrigger: '', perceptionIntent: '',
        content: '', hook: '',
      };
      inContent = false;
      continue;
    }
    if (contentM && currentPost) { inContent = true; continue; }
    if (!currentPost) continue;

    if (inContent) {
      contentLines.push(line);
    } else {
      const funnelM = line.match(/[-•*]\s*(?:Funnel stage|Tầng funnel)[:\s]+(.+)/i);
      const goalM   = line.match(/[-•*]\s*Mục tiêu[:\s]+(.+)/i);
      const psychM  = line.match(/[-•*]\s*Tâm lý[:\s]+(.+)/i);
      const trigM   = line.match(/[-•*]\s*Emotional trigger[:\s]+(.+)/i);
      const percM   = line.match(/[-•*]\s*Perception intention[:\s]+(.+)/i);
      if (funnelM) currentPost.stage            = funnelM[1].trim();
      if (goalM)   currentPost.goal             = goalM[1].trim();
      if (psychM)  currentPost.psychology       = psychM[1].trim();
      if (trigM)   currentPost.emotionalTrigger = trigM[1].trim();
      if (percM)   currentPost.perceptionIntent = percM[1].trim();
    }
  }
  flushPost();
  return days;
}

// ── Text cleaner (strips markdown formatting) ─────────────────

function cleanText(t) {
  if (!t) return t;
  return t
    .replace(/\*\*\*(.+?)\*\*\*/gs, '$1')
    .replace(/\*\*(.+?)\*\*/gs, '$1')
    .replace(/\*(.+?)\*/gs, '$1')
    .replace(/\*/g, '')
    .replace(/_{2}(.+?)_{2}/gs, '$1')
    .replace(/_(.+?)_/gs, '$1');
}

// ── Optimization options parser ──────────────────────────────

function parseOptimizationOptions(text) {
  const results = [];
  const lines   = text.split('\n');
  let current   = null;
  const buf     = [];

  const flush = () => {
    if (!current) return;
    current.content = cleanText(buf.join('\n').trim());
    results.push({ ...current });
    current = null;
    buf.length = 0;
  };

  for (const line of lines) {
    const m = line.match(/^##\s+OPTION\s+(\d+)\s*[—\-]?\s*(.*)/i);
    if (m) {
      flush();
      current = { idx: parseInt(m[1]), angle: m[2].trim() || `Option ${parseInt(m[1])}`, content: '' };
      continue;
    }
    if (current) buf.push(line);
  }
  flush();
  return results;
}

// ── Category helpers ──────────────────────────────────────────

function matchCategory(name) {
  const n = (name || '').toLowerCase();
  if (n.includes('sale') || n.includes('ưu đãi') || n.includes('uu dai')) return 'sale';
  if (n.includes('nỗi đau') || n.includes('noi dau')) return 'pain';
  if (n.includes('tính năng') || n.includes('tinh nang') || n.includes('chức năng')) return 'feature';
  if (n.includes('sự kiện') || n.includes('su kien')) return 'event';
  if (n.includes('trending') || n.includes('viral')) return 'trending';
  return null;
}

function groupByCategory(options) {
  const groups = {};
  PURCHASE_CATEGORIES.forEach(cat => { groups[cat.id] = []; });
  const unmatched = [];
  options.forEach(opt => {
    const catId = matchCategory(opt.name);
    if (catId && groups[catId]) {
      groups[catId].push(opt);
    } else {
      unmatched.push(opt);
    }
  });
  unmatched.forEach((opt, i) => {
    const catId = PURCHASE_CATEGORIES[i % PURCHASE_CATEGORIES.length].id;
    groups[catId].push(opt);
  });
  return groups;
}

// ── Color / icon helpers ──────────────────────────────────────

function getFunnelColor(stage) {
  const s = (stage || '').toLowerCase();
  if (s.includes('aware') || s.includes('attention') || s.includes('nhận thức')) return '#2E9DF7';
  if (s.includes('engage') || s.includes('curiosity') || s.includes('educati') || s.includes('pain')) return '#F472B6';
  if (s.includes('conver') || s.includes('offer') || s.includes('trust') || s.includes('authority')) return '#4ADE80';
  if (s.includes('retent') || s.includes('loyal') || s.includes('bonding') || s.includes('social')) return '#FBBF24';
  return '#66FCF1';
}

function getFunnelIcon(stage) {
  const s = (stage || '').toLowerCase();
  if (s.includes('aware') || s.includes('attention')) return 'eye';
  if (s.includes('engage') || s.includes('curiosity')) return 'heart';
  if (s.includes('conver') || s.includes('offer'))    return 'zap';
  if (s.includes('retent') || s.includes('loyal'))    return 'repeat';
  if (s.includes('trust')  || s.includes('authority')) return 'shield';
  if (s.includes('educati') || s.includes('pain'))    return 'book-open';
  return 'circle';
}

// ── Single optimization option card ──────────────────────────

const OPT_COLORS = ['#66FCF1', '#4ADE80', '#F472B6', '#FBBF24', '#A78BFA'];

const OptResultCard = ({ opt }) => {
  const color = OPT_COLORS[(opt.idx - 1) % OPT_COLORS.length];
  return (
    <div style={{
      borderRadius: 10,
      border: `1px solid ${color}28`,
      background: 'var(--bg-surface)',
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 12px',
        background: `${color}08`,
        borderBottom: `1px solid ${color}18`,
      }}>
        <span style={{
          fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 700,
          background: `${color}22`, color,
          borderRadius: 4, padding: '2px 7px', flexShrink: 0,
        }}>
          {String(opt.idx).padStart(2, '0')}
        </span>
        <span style={{
          fontSize: 12, fontWeight: 600,
          color: 'var(--fg-primary)', fontFamily: 'var(--font-display)',
          flex: 1, lineHeight: 1.3,
          letterSpacing: '-0.01em',
        }}>
          {opt.angle}
        </span>
        <button
          onClick={() => navigator.clipboard && navigator.clipboard.writeText(opt.content)}
          title="Copy"
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 4, borderRadius: 5, color: 'var(--fg-muted)',
          }}
        >
          <Icon name="copy" size={12} color="var(--fg-muted)" />
        </button>
      </div>
      <div style={{
        padding: '10px 13px',
        fontSize: 13, color: 'var(--fg-primary)',
        lineHeight: 1.82, whiteSpace: 'pre-wrap',
      }}>
        {opt.content}
      </div>
    </div>
  );
};

// ── Inline chat panel (per-post AI optimization) ──────────────

const InlineChatPanel = ({ history, running, onSend }) => {
  const [chatDraft, setChatDraft] = React.useState('');

  const handleSend = () => {
    if (!chatDraft.trim() || running) return;
    onSend(chatDraft.trim());
    setChatDraft('');
  };

  return (
    <div style={{ paddingTop: 10 }}>
      {/* Chat history */}
      {history && history.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 12 }}>
          {[...history].reverse().map((entry, i) => (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {/* User instruction bubble */}
              {entry.instruction && (
                <div style={{
                  alignSelf: 'flex-end',
                  background: 'rgba(102,252,241,0.1)',
                  border: '1px solid rgba(102,252,241,0.3)',
                  borderRadius: '10px 10px 3px 10px',
                  padding: '7px 12px',
                  fontSize: 12.5, color: '#66FCF1',
                  maxWidth: '85%', lineHeight: 1.5,
                }}>
                  {entry.instruction}
                </div>
              )}
              {/* AI response — option cards or plain text fallback */}
              {entry.options && entry.options.length > 0 ? (
                <div>
                  <div style={{
                    fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)',
                    letterSpacing: '0.07em', marginBottom: 8,
                  }}>
                    AI AGENT · {entry.options.length} OPTIONS · {entry.ts}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {entry.options.map(opt => (
                      <OptResultCard key={opt.idx} opt={opt} />
                    ))}
                  </div>
                </div>
              ) : (
                <div style={{
                  background: 'var(--bg-card)',
                  border: '1px solid var(--border)',
                  borderRadius: '3px 10px 10px 10px',
                  padding: '10px 13px',
                  fontSize: 13, color: 'var(--fg-primary)',
                  lineHeight: 1.8, whiteSpace: 'pre-wrap',
                }}>
                  {cleanText(entry.text)}
                  <div style={{ fontSize: 10.5, color: 'var(--fg-muted)', marginTop: 6, fontFamily: 'var(--font-mono)' }}>
                    AI Agent · {entry.ts}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Input row */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
        <textarea
          value={chatDraft}
          onChange={e => setChatDraft(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
          placeholder="Tối ưu content này… vd: hook mạnh hơn, thêm urgency, ngắn gọn hơn, đổi sang góc cảm xúc…"
          rows={1}
          style={{
            flex: 1, resize: 'none',
            background: 'var(--bg-base)',
            border: '1px solid var(--border)',
            borderRadius: 8,
            padding: '8px 11px',
            fontSize: 12.5,
            color: 'var(--fg-primary)',
            lineHeight: 1.5,
            minHeight: 38,
            maxHeight: 96,
            fontFamily: 'var(--font-body)',
            outline: 'none',
          }}
        />
        <button
          onClick={handleSend}
          disabled={!chatDraft.trim() || running}
          style={{
            width: 36, height: 36, borderRadius: 8, flexShrink: 0,
            background: (!chatDraft.trim() || running) ? 'var(--bg-card)' : '#66FCF1',
            border: `1px solid ${(!chatDraft.trim() || running) ? 'var(--border)' : '#66FCF1'}`,
            color: (!chatDraft.trim() || running) ? 'var(--fg-muted)' : '#0B0F1A',
            cursor: (!chatDraft.trim() || running) ? 'default' : 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.15s',
          }}
        >
          <Icon name={running ? 'loader' : 'send'} size={14} />
        </button>
      </div>
    </div>
  );
};

// ── Facebook post card (purchase output) ──────────────────────

const FacebookPostCard = ({ post, catColor, chatHistory, chatRunning, onChat }) => {
  const color = catColor || '#66FCF1';
  const [chatOpen, setChatOpen] = React.useState(false);
  const chatCount = chatHistory ? chatHistory.length : 0;

  return (
    <div style={{
      borderRadius: 12,
      border: '1px solid var(--border)',
      background: 'var(--bg-surface)',
      overflow: 'hidden',
      marginBottom: 12,
    }}>
      {/* Post header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px 8px' }}>
        <div style={{
          width: 38, height: 38, borderRadius: '50%', flexShrink: 0,
          background: `${color}18`,
          border: `1.5px solid ${color}30`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="user" size={16} color={color} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', lineHeight: 1.3 }}>
            Trang của bạn
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
            <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Vừa xong</span>
            <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>·</span>
            <Icon name="globe" size={10} color="var(--fg-muted)" />
          </div>
        </div>
        <div style={{
          fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
          color: color, background: `${color}15`,
          border: `1px solid ${color}30`,
          borderRadius: 5, padding: '2px 8px', flexShrink: 0,
        }}>
          {String(post.idx).padStart(2, '0')}
        </div>
      </div>

      {/* Post content */}
      <div style={{ padding: '2px 14px 14px' }}>
        <div style={{ fontSize: 13.5, color: 'var(--fg-primary)', lineHeight: 1.85, whiteSpace: 'pre-wrap' }}>
          {post.content}
        </div>
      </div>

      {/* Post actions bar */}
      <div style={{
        borderTop: '1px solid var(--border)',
        padding: '4px 6px',
        display: 'flex', alignItems: 'center', gap: 2,
      }}>
        {[
          { icon: 'thumbs-up',      label: 'Thích'     },
          { icon: 'message-circle', label: 'Bình luận' },
          { icon: 'share-2',        label: 'Chia sẻ'   },
        ].map(action => (
          <div key={action.label} style={{
            display: 'flex', alignItems: 'center', gap: 5,
            color: 'var(--fg-muted)', fontSize: 12,
            padding: '5px 10px', borderRadius: 6,
          }}>
            <Icon name={action.icon} size={13} color="var(--fg-muted)" />
            {action.label}
          </div>
        ))}
        <div style={{ flex: 1 }} />
        <button
          onClick={() => setChatOpen(v => !v)}
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            background: chatOpen ? 'rgba(102,252,241,0.08)' : 'none',
            border: `1px solid ${chatOpen ? 'rgba(102,252,241,0.3)' : 'transparent'}`,
            cursor: 'pointer',
            color: chatOpen ? '#66FCF1' : 'var(--fg-muted)',
            fontSize: 12, padding: '5px 10px', borderRadius: 7,
            transition: 'all 0.15s',
          }}
        >
          <Icon name="message-square" size={13} color={chatOpen ? '#66FCF1' : 'var(--fg-muted)'} />
          Tối ưu AI
          {chatCount > 0 && (
            <span style={{
              fontSize: 9.5, background: '#66FCF1', color: '#0B0F1A',
              borderRadius: 10, padding: '0 5px', fontFamily: 'var(--font-mono)', fontWeight: 700,
              lineHeight: '16px', display: 'inline-block',
            }}>
              {chatCount}
            </span>
          )}
        </button>
        <button
          onClick={() => {
            if (navigator.clipboard) navigator.clipboard.writeText(post.content);
          }}
          style={{
            display: 'flex', alignItems: 'center', gap: 5,
            background: 'none', border: '1px solid transparent',
            cursor: 'pointer', color: 'var(--fg-muted)',
            fontSize: 12, padding: '5px 10px', borderRadius: 7,
          }}
        >
          <Icon name="copy" size={13} color="var(--fg-muted)" />
          Copy
        </button>
      </div>

      {/* Inline chat */}
      {chatOpen && (
        <div style={{
          padding: '10px 14px 14px',
          borderTop: '1px solid rgba(102,252,241,0.12)',
          background: 'rgba(102,252,241,0.02)',
        }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: '#66FCF1', letterSpacing: '0.07em', marginBottom: 10, opacity: 0.7 }}>
            AI OPTIMIZATION CHAT
          </div>
          <InlineChatPanel
            history={chatHistory}
            running={chatRunning}
            onSend={onChat}
          />
        </div>
      )}
    </div>
  );
};

// ── Purchase display (tabbed) ──────────────────────────────────

const PurchaseDisplay = ({ options, activeTab, onTabChange, chatHistory, chatRunning, onChat }) => {
  const groups     = React.useMemo(() => groupByCategory(options), [options]);
  const activeCat  = PURCHASE_CATEGORIES.find(c => c.id === activeTab);
  const activeGroup = groups[activeTab] || [];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Category tabs */}
      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
        {PURCHASE_CATEGORIES.map(cat => {
          const isActive = activeTab === cat.id;
          const count    = groups[cat.id] ? groups[cat.id].length : 0;
          return (
            <button
              key={cat.id}
              onClick={() => onTabChange(cat.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 7,
                padding: '7px 12px', borderRadius: 8, cursor: 'pointer', flexShrink: 0,
                border: `1.5px solid ${isActive ? cat.color : 'var(--border)'}`,
                background: isActive ? `${cat.color}10` : 'var(--bg-surface)',
                transition: 'all 0.15s',
              }}
            >
              <Icon name={cat.icon} size={13} color={isActive ? cat.color : 'var(--fg-muted)'} />
              <span style={{
                fontSize: 12, fontWeight: 600,
                color: isActive ? 'var(--fg-primary)' : 'var(--fg-secondary)',
                fontFamily: 'var(--font-display)', letterSpacing: '-0.01em',
              }}>
                {cat.label}
              </span>
              {count > 0 && (
                <span style={{
                  fontSize: 9.5, fontFamily: 'var(--font-mono)',
                  background: isActive ? `${cat.color}22` : 'var(--bg-card)',
                  color: isActive ? cat.color : 'var(--fg-muted)',
                  borderRadius: 4, padding: '1px 6px',
                }}>
                  {count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* Posts in active tab */}
      {activeGroup.length === 0 ? (
        <div style={{
          textAlign: 'center', padding: '36px 16px',
          color: 'var(--fg-muted)', fontSize: 13, lineHeight: 1.6,
        }}>
          <Icon name="inbox" size={24} color="var(--fg-muted)" />
          <div style={{ marginTop: 10 }}>Không có content cho góc này.</div>
          <div style={{ fontSize: 11.5, marginTop: 4 }}>Generate lại để AI tạo content đầy đủ cho cả 5 góc.</div>
        </div>
      ) : (
        <div>
          {activeGroup.map(post => (
            <FacebookPostCard
              key={post.key}
              post={post}
              catColor={activeCat ? activeCat.color : null}
              chatHistory={chatHistory[post.key]}
              chatRunning={chatRunning === post.key}
              onChat={(instruction) => onChat(post, instruction)}
            />
          ))}
        </div>
      )}
    </div>
  );
};

// ── Brand post card ───────────────────────────────────────────

const BrandPostCard = ({ post, selected, onSelect }) => {
  const fc = getFunnelColor(post.stage);
  const fi = getFunnelIcon(post.stage);
  return (
    <div
      onClick={onSelect}
      style={{
        cursor: 'pointer', padding: '10px 11px', borderRadius: 6,
        border: `1px solid ${selected ? fc : 'transparent'}`,
        background: selected ? `${fc}0E` : 'transparent',
        transition: 'border-color 0.15s, background 0.15s',
        display: 'flex', flexDirection: 'column', gap: 6,
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name={fi} size={12} color={fc} />
        <span style={{ fontSize: 11, color: fc, fontWeight: 600, flex: 1, lineHeight: 1.3 }}>
          {post.stage || post.type || 'Content'}
        </span>
        {selected && <div style={{ width: 6, height: 6, borderRadius: '50%', background: fc, flexShrink: 0 }} />}
      </div>
      {post.goal && (
        <div style={{ fontSize: 10.5, color: 'var(--fg-muted)', lineHeight: 1.35 }}>
          {post.goal.slice(0, 58)}{post.goal.length > 58 ? '…' : ''}
        </div>
      )}
      {post.hook && (
        <div style={{
          fontSize: 11.5, color: 'var(--fg-primary)', lineHeight: 1.4,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>
          {post.hook}
        </div>
      )}
    </div>
  );
};

// ── Brand detail panel ────────────────────────────────────────

const PostDetailPanel = ({ post, varHistory, varRunning, onGenerateVar }) => {
  const color = getFunnelColor(post.stage);
  const vars  = varHistory || [];

  const metaRows = [
    post.goal             && { icon: 'target',   label: 'Mục tiêu',   val: post.goal },
    post.stage            && { icon: 'layers',   label: 'Funnel',     val: post.stage },
    post.psychology       && { icon: 'activity', label: 'Tâm lý',     val: post.psychology },
    post.emotionalTrigger && { icon: 'zap',      label: 'Emotional',  val: post.emotionalTrigger },
    post.perceptionIntent && { icon: 'eye',      label: 'Perception', val: post.perceptionIntent },
  ].filter(Boolean);

  return (
    <div style={{ border: `1px solid ${color}30`, borderRadius: 12, background: `${color}05`, overflow: 'hidden', marginTop: 4 }}>
      <div style={{ padding: '12px 16px', background: `${color}10`, borderBottom: `1px solid ${color}18`, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: 8, background: `${color}22`, color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="edit-3" size={14} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 13.5, fontWeight: 700, color: 'var(--fg-primary)', letterSpacing: '-0.01em' }}>
            {post.type || `Post ${post.postIdx}`}
          </div>
          {post.stage && (
            <div style={{ fontSize: 11, color, marginTop: 2, fontWeight: 500 }}>{post.stage}</div>
          )}
        </div>
      </div>

      {metaRows.length > 0 && (
        <div style={{ padding: '10px 16px 8px', borderBottom: `1px solid ${color}10`, display: 'flex', flexDirection: 'column', gap: 7 }}>
          {metaRows.map((row, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 9 }}>
              <div style={{ color: 'var(--fg-muted)', flexShrink: 0, marginTop: 1 }}><Icon name={row.icon} size={11} /></div>
              <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', flexShrink: 0, minWidth: 70, paddingTop: 1 }}>{row.label}</span>
              <span style={{ fontSize: 11.5, color: 'var(--fg-secondary)', flex: 1, lineHeight: 1.5 }}>{row.val}</span>
            </div>
          ))}
        </div>
      )}

      <div style={{ padding: '14px 16px' }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', marginBottom: 10, letterSpacing: '0.08em' }}>CONTENT</div>
        <div style={{ fontSize: 13.5, color: 'var(--fg-primary)', lineHeight: 1.82, whiteSpace: 'pre-wrap' }}>
          {post.content || <span style={{ color: 'var(--fg-muted)', fontStyle: 'italic' }}>—</span>}
        </div>
      </div>

      <div style={{ padding: '12px 16px', borderTop: `1px solid ${color}15`, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <Btn
          variant="primary" size="sm"
          icon={varRunning ? 'loader' : 'git-branch'}
          onClick={varRunning ? undefined : onGenerateVar}
        >
          {varRunning ? 'Đang tạo…' : 'Tạo variation'}
        </Btn>
        <Btn variant="ghost" size="sm" icon="copy">Copy</Btn>
        {vars.length > 0 && (
          <React.Fragment>
            <div style={{ flex: 1 }} />
            <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>
              {vars.length} variation{vars.length > 1 ? 's' : ''}
            </span>
          </React.Fragment>
        )}
      </div>

      {vars.length > 0 && (
        <div style={{ padding: '0 16px 16px' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', marginBottom: 10, letterSpacing: '0.08em' }}>
            VARIATION HISTORY
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {vars.map((v, i) => (
              <div key={i} style={{ borderRadius: 8, border: '1px solid var(--border)', background: 'var(--bg-card)', padding: '10px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 7 }}>
                  <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)' }}>
                    Var {String(vars.length - i).padStart(2, '0')} · {v.ts}
                  </span>
                  <Btn variant="ghost" size="sm" icon="copy" />
                </div>
                <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.75, whiteSpace: 'pre-wrap' }}>{cleanText(v.text)}</div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// ── Brand display ─────────────────────────────────────────────

const BrandDisplay = ({ days, selectedKey, onSelect, varHistory, varRunning, onGenerateVar }) => {
  const allPosts = days.flatMap(d => d.posts);
  const selected = allPosts.find(p => p.key === selectedKey);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ overflowX: 'auto', paddingBottom: 4 }}>
        <div style={{ display: 'flex', gap: 8, minWidth: 'max-content', paddingBottom: 2 }}>
          {days.map(day => (
            <div key={day.idx} style={{ width: 200, flexShrink: 0, display: 'flex', flexDirection: 'column' }}>
              <div style={{
                padding: '8px 12px 7px',
                background: 'var(--bg-card)',
                border: '1px solid var(--border)',
                borderRadius: '8px 8px 0 0',
                borderBottom: 'none',
              }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--fg-muted)', letterSpacing: '0.07em', marginBottom: 3 }}>
                  DAY {String(day.idx).padStart(2, '0')}
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', lineHeight: 1.3 }}>
                  {day.label}
                </div>
              </div>
              <div style={{
                border: '1px solid var(--border)', borderRadius: '0 0 8px 8px',
                flex: 1, display: 'flex', flexDirection: 'column',
                background: 'var(--bg-surface)', overflow: 'hidden',
              }}>
                {day.posts.map((post, pi) => (
                  <React.Fragment key={post.key}>
                    {pi > 0 && <div style={{ height: 1, background: 'var(--border)', margin: '0 10px' }} />}
                    <BrandPostCard
                      post={post}
                      selected={post.key === selectedKey}
                      onSelect={() => onSelect(post.key === selectedKey ? null : post.key)}
                    />
                  </React.Fragment>
                ))}
                {day.posts.length === 0 && (
                  <div style={{ padding: 12, fontSize: 11, color: 'var(--fg-muted)', textAlign: 'center' }}>—</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
      {selected && (
        <PostDetailPanel
          post={selected}
          varHistory={varHistory[selected.key]}
          varRunning={varRunning === selected.key}
          onGenerateVar={() => onGenerateVar(selected)}
        />
      )}
    </div>
  );
};

// ── Content questionnaire ─────────────────────────────────────

const CONTENT_QUESTIONS = [
  {
    id: 'category', type: 'single',
    question: 'Ngành hàng / loại sản phẩm?',
    options: ['Thời trang & phụ kiện', 'Mỹ phẩm & làm đẹp', 'Thực phẩm & đồ uống', 'Sức khỏe & wellness', 'Giáo dục & khoá học', 'Công nghệ & phần mềm', 'Nội thất & gia dụng'],
    hasOther: true,
  },
  {
    id: 'audience', type: 'multi',
    question: 'Đối tượng khách hàng mục tiêu?',
    options: ['Phụ nữ 18–25', 'Phụ nữ 25–40', 'Nam giới 25–40', 'Người đi làm', 'Người kinh doanh / SME', 'Học sinh / sinh viên', 'Cha mẹ có con nhỏ'],
    hasOther: true,
  },
  {
    id: 'goal', type: 'single',
    question: 'Mục tiêu chính của content?',
    options: ['Tăng inbox / leads', 'Tăng nhận diện thương hiệu', 'Chốt đơn trực tiếp', 'Giữ chân khách hàng cũ', 'Viral / tăng reach organic'],
    hasOther: true,
  },
  {
    id: 'platform', type: 'multi',
    question: 'Platform sẽ đăng content?',
    options: ['Facebook', 'Instagram', 'TikTok', 'YouTube', 'Zalo'],
    hasOther: false,
  },
  {
    id: 'usp', type: 'multi',
    question: 'Điểm mạnh nổi bật của sản phẩm?',
    options: ['Giá tốt / tiết kiệm chi phí', 'Chất lượng cao cấp', 'Giao hàng nhanh', 'Có bảo hành / hoàn tiền', 'Thương hiệu uy tín', 'Hiệu quả nhanh / rõ ràng'],
    hasOther: true,
  },
];

const QUESTION_LABELS = { category: 'Ngành hàng', audience: 'Đối tượng', goal: 'Mục tiêu', platform: 'Platform', usp: 'Điểm mạnh' };

function compileSurvey(draft) {
  const lines = [];
  CONTENT_QUESTIONS.forEach(q => {
    const val = draft[q.id];
    if (!val) return;
    const picked = Array.isArray(val.picked) ? val.picked : (val.picked ? [val.picked] : []);
    const parts  = [...picked];
    if (val.other && val.other.trim()) parts.push(val.other.trim());
    if (parts.length > 0) lines.push(`- ${QUESTION_LABELS[q.id]}: ${parts.join(', ')}`);
  });
  return lines.join('\n');
}

const ContentSurvey = ({ open, onToggle, draft, onChange, onApply, applied }) => {
  const handlePick = (qId, option, isMulti) => {
    const cur = draft[qId] || {};
    if (isMulti) {
      const picked = cur.picked || [];
      const next   = picked.includes(option) ? picked.filter(x => x !== option) : [...picked, option];
      onChange({ ...draft, [qId]: { ...cur, picked: next } });
    } else {
      const next = cur.picked === option ? null : option;
      onChange({ ...draft, [qId]: { ...cur, picked: next } });
    }
  };

  const handleOther = (qId, val) => {
    const cur = draft[qId] || {};
    onChange({ ...draft, [qId]: { ...cur, other: val } });
  };

  const hasAny = CONTENT_QUESTIONS.some(q => {
    const v = draft[q.id];
    if (!v) return false;
    const picked = Array.isArray(v.picked) ? v.picked : (v.picked ? [v.picked] : []);
    return picked.length > 0 || (v.other && v.other.trim());
  });

  return (
    <div style={{ marginTop: 14, border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
      {/* Header */}
      <button
        onClick={onToggle}
        style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 10,
          padding: '10px 14px', background: 'var(--bg-surface)',
          border: 'none', cursor: 'pointer', textAlign: 'left',
        }}
      >
        <div style={{ width: 28, height: 28, borderRadius: 8, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: applied ? 'rgba(74,222,128,0.15)' : 'var(--bg-card)' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={applied ? '#4ADE80' : 'var(--fg-muted)'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>
          </svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: applied ? '#4ADE80' : 'var(--fg-primary)', fontFamily: 'var(--font-display)', lineHeight: 1.3 }}>
            Thông tin bổ sung cho AI
            {applied && <span style={{ fontSize: 10, fontWeight: 400, marginLeft: 7, color: '#4ADE80', background: 'rgba(74,222,128,0.12)', padding: '1px 7px', borderRadius: 4 }}>Đã áp dụng</span>}
          </div>
          <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 1 }}>
            Trả lời để AI hiểu đúng ngữ cảnh · tick chọn + điền Other
          </div>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--fg-muted)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>

      {open && (
        <div style={{ padding: '0 14px 14px', background: 'var(--bg-base)' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 12 }}>
            {CONTENT_QUESTIONS.map(q => {
              const val    = draft[q.id] || {};
              const picked = Array.isArray(val.picked) ? val.picked : (val.picked ? [val.picked] : []);
              return (
                <div key={q.id}>
                  <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-secondary)', marginBottom: 7, fontFamily: 'var(--font-display)' }}>
                    {q.question}
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {q.options.map(opt => {
                      const isActive = picked.includes(opt);
                      return (
                        <button
                          key={opt}
                          onClick={() => handlePick(q.id, opt, q.type === 'multi')}
                          style={{
                            display: 'flex', alignItems: 'center', gap: 6,
                            padding: '5px 10px', borderRadius: 20, cursor: 'pointer',
                            border: `1.5px solid ${isActive ? '#66FCF1' : 'var(--border)'}`,
                            background: isActive ? 'rgba(102,252,241,0.1)' : 'var(--bg-surface)',
                            transition: 'all 0.12s',
                          }}
                        >
                          <span style={{
                            width: 13, height: 13, borderRadius: q.type === 'multi' ? 3 : '50%',
                            border: `1.5px solid ${isActive ? '#66FCF1' : 'var(--border)'}`,
                            background: isActive ? '#66FCF1' : 'transparent',
                            flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.12s',
                          }}>
                            {isActive && (
                              <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="#0B0F1A" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round">
                                <polyline points="20 6 9 17 4 12"/>
                              </svg>
                            )}
                          </span>
                          <span style={{ fontSize: 11.5, color: isActive ? '#66FCF1' : 'var(--fg-secondary)' }}>{opt}</span>
                        </button>
                      );
                    })}
                    {q.hasOther && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5, flex: '1 1 160px', minWidth: 140 }}>
                        <span style={{ fontSize: 11.5, color: 'var(--fg-muted)', flexShrink: 0 }}>Khác:</span>
                        <input
                          type="text"
                          value={val.other || ''}
                          onChange={e => handleOther(q.id, e.target.value)}
                          placeholder="Điền vào đây…"
                          style={{
                            flex: 1, minWidth: 0,
                            background: 'var(--bg-card)', border: '1px solid var(--border)',
                            borderRadius: 20, padding: '4px 10px',
                            fontSize: 11.5, color: 'var(--fg-primary)',
                            outline: 'none', fontFamily: 'var(--font-body)',
                          }}
                        />
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14 }}>
            <button
              onClick={() => onApply(compileSurvey(draft))}
              disabled={!hasAny}
              style={{
                padding: '7px 16px', borderRadius: 8, cursor: hasAny ? 'pointer' : 'default',
                background: hasAny ? '#66FCF1' : 'var(--bg-card)',
                border: `1px solid ${hasAny ? '#66FCF1' : 'var(--border)'}`,
                color: hasAny ? '#0B0F1A' : 'var(--fg-muted)',
                fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600,
                display: 'flex', alignItems: 'center', gap: 6, transition: 'all 0.15s',
              }}
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 11l3 3L22 4"/>
              </svg>
              Áp dụng cho AI
            </button>
            {applied && (
              <button
                onClick={() => onApply(null)}
                style={{
                  padding: '7px 12px', borderRadius: 8, cursor: 'pointer',
                  background: 'none', border: '1px solid var(--border)',
                  color: 'var(--fg-muted)', fontSize: 12, fontFamily: 'var(--font-display)',
                }}
              >
                Xoá bỏ
              </button>
            )}
            {applied && (
              <span style={{ fontSize: 11, color: '#4ADE80', fontFamily: 'var(--font-mono)' }}>
                ✓ Đã áp dụng vào context AI
              </span>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

// ── Main screen ───────────────────────────────────────────────

const ScreenContent = ({ section, onUpdateSection, allSections = {}, lang = 'vi' }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;
  const [mode, setMode]               = React.useState('purchase');
  const [draft, setDraft]             = React.useState('');
  const [running, setRunning]         = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [purchaseTab, setPurchaseTab] = React.useState(PURCHASE_CATEGORIES[0].id);
  const [chatHistory, setChatHistory] = React.useState({});
  const [chatRunning, setChatRunning] = React.useState(null);
  const [selectedKey, setSelectedKey] = React.useState(null);
  const [varHistory, setVarHistory]   = React.useState({});
  const [varRunning, setVarRunning]   = React.useState(null);
  const [linkedVersionOverrides, setLinkedVersionOverrides] = React.useState({});
  const [surveyOpen, setSurveyOpen]   = React.useState(true);
  const [surveyDraft, setSurveyDraft] = React.useState({});
  const [surveyApplied, setSurveyApplied] = React.useState(null);

  const active      = section.versions.find(v => v.id === section.activeId) || section.versions[0];
  const data        = active && active.output;
  const contentMode = data && data._mode ? data._mode : null;

  const purchaseOptions = React.useMemo(
    () => (data && data._text && contentMode === 'purchase') ? parseContentPurchase(data._text) : [],
    [data, contentMode]
  );
  const brandDays = React.useMemo(
    () => (data && data._text && contentMode === 'brand') ? parseBrandCampaign(data._text) : [],
    [data, contentMode]
  );

  React.useEffect(() => { setSelectedKey(null); }, [section.activeId]);

  const toggleSource = (k) => {
    const cur = section.linkedSources || [];
    onUpdateSection({ linkedSources: cur.includes(k) ? cur.filter(x => x !== k) : [...cur, k] });
  };

  const submit = async (attachments = []) => {
    if (!draft.trim()) return;
    setRunning(true);
    setSubmitError(null);
    try {
      const kind      = mode === 'purchase' ? 'content_purchase' : 'content_brand';
      const linkedCtx = window.buildLinkedContext(section.linkedSources, allSections, linkedVersionOverrides);
      const attCtx    = window.buildAttachmentContext(attachments);
      const surveyCtx = surveyApplied ? `\n\nThông tin bổ sung từ người dùng:\n${surveyApplied}` : '';
      const result    = await window._aiCall(draft, kind, section.styleId, linkedCtx + attCtx + surveyCtx);
      const ts     = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      const newVer = {
        id: `c-ai-${Date.now()}`,
        ts,
        label: draft.slice(0, 28) + (draft.length > 28 ? '…' : ''),
        output: { _text: result, _mode: mode },
      };
      onUpdateSection({ versions: [...section.versions, newVer], activeId: newVer.id });
    } catch (e) {
      console.error(e);
      setSubmitError(e.message || 'Lỗi kết nối AI Agent');
    } finally {
      setRunning(false);
      setDraft('');
    }
  };

  const handlePostChat = async (post, instruction) => {
    const key = post.key;
    setChatRunning(key);
    try {
      const ctx = [
        'Content Facebook Ads gốc:',
        post.name ? `Góc: ${post.name}` : '',
        '',
        post.content,
        '',
        '---',
        `Yêu cầu tối ưu: ${instruction}`,
        '',
        'Viết ĐÚNG 5 option, mỗi option xoay quanh yêu cầu trên nhưng có 1 điểm đặc biệt riêng biệt (angle khác, hook khác, cảm xúc khác, cấu trúc khác). Tối đa 5 option.',
        '',
        'FORMAT OUTPUT (bắt buộc):',
        '## OPTION 1 — [Tên điểm đặc biệt / angle riêng của option này]',
        '[Content hoàn chỉnh — 6-10 dòng, giữ style Facebook Ads]',
        '',
        '## OPTION 2 — [Điểm đặc biệt]',
        '[Content]',
        '',
        '...đến OPTION 5',
        '',
        'QUAN TRỌNG: Mỗi option phải thực sự khác nhau — hook khác, góc cảm xúc khác, cấu trúc khác. Không chỉ đổi vài từ.',
      ].join('\n');
      const result  = await window._aiCall(instruction, 'content_purchase', section.styleId, ctx);
      const options = parseOptimizationOptions(result);
      const ts      = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      setChatHistory(prev => ({
        ...prev,
        [key]: [{ options, text: result, ts, instruction }, ...(prev[key] || [])],
      }));
    } catch (e) {
      console.error(e);
    } finally {
      setChatRunning(null);
    }
  };

  const generateVariation = async (post) => {
    const key = post.key;
    setVarRunning(key);
    try {
      const ctx = [
        'Bài gốc cần tạo variation:',
        post.type  ? `Loại content: ${post.type}`  : '',
        post.stage ? `Funnel: ${post.stage}`        : '',
        post.goal  ? `Mục tiêu: ${post.goal}`       : '',
        `\nContent gốc:\n${post.content}`,
        '\nYêu cầu: Viết 1 variation mới — giữ đúng angle/mục tiêu nhưng THAY ĐỔI HOÀN TOÀN cách viết: hook mới, cấu trúc mới, góc cảm xúc mới. CHỈ trả về content, không cần heading hay metadata.',
      ].filter(Boolean).join('\n');
      const result = await window._aiCall('Tạo 1 variation mới cho bài này', 'content_brand', section.styleId, ctx);
      const ts     = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      setVarHistory(prev => ({
        ...prev,
        [key]: [{ text: result, ts }, ...(prev[key] || [])],
      }));
    } catch (e) {
      console.error(e);
    } finally {
      setVarRunning(null);
    }
  };

  const MODES = {
    purchase: {
      hero: { vi: ['Viết ', 'Facebook Ads', ' chuyển đổi cao'], en: 'AI tạo 5 option ads đại diện 5 góc · tối ưu thêm với chat AI' },
      placeholder: 'Nhập thông tin sản phẩm: ngành, tên SP, nỗi đau KH, USP, ưu đãi, đối tượng mục tiêu, platform…',
      suggestions: [
        { icon: 'zap',         label: '5 góc ads sản phẩm mới'  },
        { icon: 'trending-up', label: 'SP muốn scale mạnh'       },
        { icon: 'users',       label: 'Social proof · review KH' },
        { icon: 'target',      label: 'Retargeting BOFU'         },
      ],
      runLabel: 'Generate',
    },
    brand: {
      hero: { vi: ['Xây dựng ', 'Campaign', ' thương hiệu'], en: 'AI tạo brand strategy + kế hoạch content theo ngày — awareness, trust & conversion' },
      placeholder: 'Nhập: ngành, sản phẩm, KH mục tiêu, mục tiêu campaign, số ngày, số bài/ngày, platform…',
      suggestions: [
        { icon: 'calendar',   label: 'Campaign launch 7 ngày'  },
        { icon: 'flame',      label: 'Event / holiday campaign' },
        { icon: 'star',       label: 'Trust-building campaign'  },
        { icon: 'refresh-cw', label: 'Retargeting campaign'     },
      ],
      runLabel: 'Generate',
    },
  };
  const mc = MODES[mode];

  const hasAiText    = data && data._text;
  const showPurchase = hasAiText && contentMode === 'purchase' && purchaseOptions.length > 0;
  const showBrand    = hasAiText && contentMode === 'brand'    && brandDays.length > 0;
  const showRaw      = hasAiText && !showPurchase && !showBrand;

  return (
    <div className="screen-body" data-screen-label="03 Content plans">
      <div className="screen-canvas">
        <div className="screen-section-label">{T('CONTENT & PLANS', 'CONTENT & PLANS')}</div>

        <PromptInput
          placeholder={mc.placeholder}
          value={draft}
          onChange={setDraft}
          onSubmit={submit}
          running={running}
          runLabel={mc.runLabel}
          currentKind="content"
          model={section.model}     onModelChange={(v) => onUpdateSection({ model: v })}
          styleId={section.styleId} onStyleChange={(v) => onUpdateSection({ styleId: v })}
          linkedSources={section.linkedSources || []} onToggleSource={toggleSource}
          suggestions={mc.suggestions}
        />

        <ContextSourceBar
          linkedSources={section.linkedSources || []}
          allSections={allSections}
          overrides={linkedVersionOverrides}
          onOverrideChange={(key, id) => setLinkedVersionOverrides(prev => ({ ...prev, [key]: id }))}
        />

        {/* Mode switcher */}
        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          {[
            { id: 'purchase', icon: 'shopping-cart', label: 'Content Purchase', sub: '5 option ads · 1 per góc · tối ưu thêm với AI chat' },
            { id: 'brand',    icon: 'layout-grid',   label: 'Content Brand',    sub: 'Campaign theo ngày · brand strategy & perception' },
          ].map(m => {
            const isActive = mode === m.id;
            return (
              <button
                key={m.id}
                onClick={() => setMode(m.id)}
                style={{
                  flex: 1, padding: '10px 13px', borderRadius: 10, cursor: 'pointer',
                  border: `1.5px solid ${isActive ? '#66FCF1' : 'var(--border)'}`,
                  background: isActive ? 'rgba(102,252,241,0.07)' : 'var(--bg-surface)',
                  display: 'flex', alignItems: 'center', gap: 10,
                  transition: 'border-color 0.15s, background 0.15s',
                  textAlign: 'left',
                }}
              >
                <div style={{
                  width: 32, height: 32, borderRadius: 8, flexShrink: 0,
                  background: isActive ? 'rgba(102,252,241,0.15)' : 'var(--bg-card)',
                  color: isActive ? '#66FCF1' : 'var(--fg-muted)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'all 0.15s',
                }}>
                  <Icon name={m.icon} size={15} />
                </div>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: isActive ? 'var(--fg-primary)' : 'var(--fg-secondary)', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em', lineHeight: 1.3, transition: 'color 0.15s' }}>
                    {m.label}
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--fg-muted)', marginTop: 2, lineHeight: 1.3 }}>{m.sub}</div>
                </div>
              </button>
            );
          })}
        </div>

        <ContentSurvey
          open={surveyOpen}
          onToggle={() => setSurveyOpen(v => !v)}
          draft={surveyDraft}
          onChange={setSurveyDraft}
          onApply={(ctx) => { setSurveyApplied(ctx); if (ctx) setSurveyOpen(false); }}
          applied={surveyApplied}
        />

        <div style={{ height: 20 }} />

        {submitError && (
          <div style={{
            display: 'flex', alignItems: 'flex-start', gap: 10,
            padding: '12px 16px', borderRadius: 10, marginBottom: 16,
            background: 'rgba(248,113,113,0.08)',
            border: '1px solid rgba(248,113,113,0.3)',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#F87171" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
              <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
            </svg>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: '#F87171', marginBottom: 3 }}>Lỗi khi gọi AI Agent</div>
              <div style={{ fontSize: 12, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>{submitError}</div>
            </div>
            <button onClick={() => setSubmitError(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 2, color: 'var(--fg-muted)', flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>
        )}

        {running ? (
          <LoadingSkeleton
            label={mode === 'purchase'
              ? 'Đang viết 5 option Facebook Ads (1 đại diện mỗi góc)…'
              : 'Đang tạo brand campaign strategy & content plan…'}
            lines={7}
          />
        ) : showPurchase ? (
          <React.Fragment>
            <OutputCard
              icon="shopping-cart"
              title="Content Purchase · Facebook Ads"
              sub={`${purchaseOptions.length} options · 5 góc · click "Tối ưu AI" dưới mỗi post để can thiệp sâu`}
            >
              <PurchaseDisplay
                options={purchaseOptions}
                activeTab={purchaseTab}
                onTabChange={setPurchaseTab}
                chatHistory={chatHistory}
                chatRunning={chatRunning}
                onChat={handlePostChat}
              />
            </OutputCard>
            <div className="btn-row" style={{ justifyContent: 'flex-end', marginTop: 8 }}>
              <Btn variant="secondary" size="md" icon="git-fork">Send to Canvas</Btn>
              <Btn variant="primary"   size="md" icon="save">Save as file</Btn>
            </div>
          </React.Fragment>
        ) : showBrand ? (
          <React.Fragment>
            <OutputCard
              icon="layout-grid"
              title="Brand Campaign Plan"
              sub={`${brandDays.length} ngày · ${brandDays.reduce((a, d) => a + d.posts.length, 0)} posts · Click để xem content & variation`}
            >
              <BrandDisplay
                days={brandDays}
                selectedKey={selectedKey}
                onSelect={setSelectedKey}
                varHistory={varHistory}
                varRunning={varRunning}
                onGenerateVar={generateVariation}
              />
            </OutputCard>
            <div className="btn-row" style={{ justifyContent: 'flex-end', marginTop: 8 }}>
              <Btn variant="secondary" size="md" icon="git-fork">Send to Canvas</Btn>
              <Btn variant="primary"   size="md" icon="save">Save as file</Btn>
            </div>
          </React.Fragment>
        ) : showRaw ? (
          <OutputCard icon="sparkles" title="Kết quả AI" sub="AI Agent · Generated">
            <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.7, color: 'var(--fg-primary)', whiteSpace: 'pre-wrap' }}>{data._text}</p>
          </OutputCard>
        ) : data ? (
          <OutputCard icon="file-text" title="Content plan · Demo data" sub="Chọn mode → nhập thông tin sản phẩm → Generate">
            <div style={{ fontSize: 13, color: 'var(--fg-muted)', padding: '4px 0', lineHeight: 1.6 }}>
              Chọn mode (Purchase / Brand) → nhập thông tin sản phẩm → Generate để AI tạo content đầy đủ.
            </div>
          </OutputCard>
        ) : null}
      </div>

      <VersionRail
        versions={section.versions}
        activeId={section.activeId}
        onPick={(id) => onUpdateSection({ activeId: id })}
      />
    </div>
  );
};

Object.assign(window, { ScreenContent });
