// Screen: SẢN PHẨM / Product

// ── Section metadata for the 15-part product intelligence output ─────
const PRODUCT_SECTION_META = [
  { num: 1,  short: 'Product Core',   icon: 'box',             color: '#66FCF1' },
  { num: 2,  short: 'Features',       icon: 'layers',          color: '#66FCF1' },
  { num: 3,  short: 'Benefits',       icon: 'check-circle',    color: '#4ADE80' },
  { num: 4,  short: 'Pain Points',    icon: 'alert-triangle',  color: '#FBBF24' },
  { num: 5,  short: 'Personas',       icon: 'users',           color: '#2E9DF7' },
  { num: 6,  short: 'Triggers',       icon: 'zap',             color: '#F472B6' },
  { num: 7,  short: 'Objections',     icon: 'shield',          color: '#F87171' },
  { num: 8,  short: 'Content Angles', icon: 'edit-3',          color: '#A78BFA' },
  { num: 9,  short: 'Hooks',          icon: 'target',          color: '#66FCF1' },
  { num: 10, short: 'Visual',         icon: 'image',           color: '#F472B6' },
  { num: 11, short: 'Branding',       icon: 'star',            color: '#FBBF24' },
  { num: 12, short: 'Sales & Ads',    icon: 'trending-up',     color: '#4ADE80' },
  { num: 13, short: 'AI Training',    icon: 'cpu',             color: '#7B4FD4' },
  { num: 14, short: 'USP',            icon: 'trophy',          color: '#FBBF24' },
  { num: 15, short: 'Ecosystem',      icon: 'git-fork',        color: '#66FCF1' },
];

// Parse AI output text into sections by "# N. HEADING" markers
function parseProductSections(text) {
  const result = {};
  let currentNum = null;
  let currentHeading = '';
  let currentLines = [];
  for (const line of text.split('\n')) {
    const m = line.match(/^#+\s+(\d+)\.\s+(.+)/);
    if (m) {
      if (currentNum !== null)
        result[currentNum] = { num: currentNum, heading: currentHeading.replace(/\s*—.*$/, '').trim(), content: currentLines.join('\n').trim() };
      currentNum = parseInt(m[1]);
      currentHeading = m[2].trim();
      currentLines = [];
    } else if (currentNum !== null) {
      currentLines.push(line);
    }
  }
  if (currentNum !== null)
    result[currentNum] = { num: currentNum, heading: currentHeading.replace(/\s*—.*$/, '').trim(), content: currentLines.join('\n').trim() };
  return result;
}

// ── Heading → icon keyword map ───────────────────────────────
const _H_ICONS = [
  { keys: ['pain','đau','vấn đề','thất bại','rủi ro','khó khăn','áp lực'], icon: 'alert-triangle' },
  { keys: ['emotion','cảm xúc','tâm lý','feeling','tình cảm'],             icon: 'heart' },
  { keys: ['financial','tài chính','tiền','chi phí','giá cả'],              icon: 'dollar-sign' },
  { keys: ['social','xã hội','cộng đồng','peer','bạn bè'],                 icon: 'users' },
  { keys: ['trigger','kích hoạt','buying trigger','thúc đẩy'],              icon: 'zap' },
  { keys: ['trust','tin tưởng','authority','chuyên gia','uy tín'],          icon: 'shield-check' },
  { keys: ['urgency','khẩn','fomo','limited','khan hiếm'],                  icon: 'clock' },
  { keys: ['hook','headline','viral','pattern interrupt'],                   icon: 'target' },
  { keys: ['visual','hình ảnh','image','video','creative','sáng tạo'],      icon: 'image' },
  { keys: ['brand','thương hiệu','tone','positioning','slogan'],            icon: 'star' },
  { keys: ['benefit','lợi ích','result','kết quả','outcome'],               icon: 'check-circle' },
  { keys: ['feature','tính năng','technology','công nghệ','cấu tạo'],      icon: 'layers' },
  { keys: ['objection','phản đối','chưa mua','nghi ngờ','lo ngại'],        icon: 'help-circle' },
  { keys: ['content','nội dung','angle','góc','approach'],                  icon: 'edit-3' },
  { keys: ['ads','quảng cáo','cta','funnel','chuyển đổi','sales'],          icon: 'trending-up' },
  { keys: ['ai','agent','training','automation','chatbot'],                  icon: 'cpu' },
  { keys: ['competitor','cạnh tranh','usp','khác biệt','lợi thế'],          icon: 'trophy' },
  { keys: ['ecosystem','hệ thống','scale','chiến dịch','phát triển'],       icon: 'git-fork' },
  { keys: ['persona','khách hàng','audience','customer','tệp'],             icon: 'user' },
  { keys: ['soft sell','educational','học','giáo dục'],                     icon: 'graduation-cap' },
  { keys: ['hard sell','direct','thẳng'],                                   icon: 'zap' },
  { keys: ['before','after','trước','sau','transformation'],                icon: 'arrow-right' },
  { keys: ['story','câu chuyện','narrative','kể'],                          icon: 'book-open' },
  { keys: ['price','giá','plan','tier','gói'],                              icon: 'tag' },
];
function _hIcon(text) {
  const t = (text || '').toLowerCase();
  for (const { keys, icon } of _H_ICONS) {
    if (keys.some(k => t.includes(k))) return icon;
  }
  return 'chevron-right';
}

// Inline markdown: **bold** and `code`
const InlineText = ({ text }) => {
  const parts = (text || '').split(/(\*\*[^*]+\*\*|`[^`]+`)/g);
  return (
    <React.Fragment>
      {parts.map((p, i) => {
        if (p.startsWith('**') && p.endsWith('**'))
          return <strong key={i} style={{ color: 'var(--fg-primary)', fontWeight: 700 }}>{p.slice(2, -2)}</strong>;
        if (p.startsWith('`') && p.endsWith('`'))
          return <code key={i} style={{
            fontFamily: 'var(--font-mono)', fontSize: '0.87em',
            background: 'rgba(102,252,241,0.09)', padding: '1px 6px',
            borderRadius: 4, color: 'var(--accent-cyan)',
          }}>{p.slice(1, -1)}</code>;
        return <React.Fragment key={i}>{p}</React.Fragment>;
      })}
    </React.Fragment>
  );
};

// Render section content — bullets, sub-headings, arrows, paragraphs
const ProductSectionBody = ({ content, sectionColor = '#66FCF1' }) => {
  const lines = (content || '').split('\n');
  const out = [];
  let listBuf = [];

  const flushList = (key) => {
    if (!listBuf.length) return;
    out.push(
      <div key={`ul-${key}`} style={{
        display: 'flex', flexDirection: 'column',
        gap: 0, margin: '8px 0 16px 0',
        background: 'var(--bg-surface-2)',
        border: '1px solid var(--border-subtle)',
        borderRadius: 8, overflow: 'hidden',
      }}>
        {listBuf.map((item, i) => (
          <div key={i} style={{
            display: 'flex', gap: 10, alignItems: 'flex-start',
            padding: '9px 14px',
            borderBottom: i < listBuf.length - 1 ? '1px solid var(--border-subtle)' : 'none',
          }}>
            <span style={{
              width: 26, height: 26, borderRadius: 7, flexShrink: 0,
              background: sectionColor + '18',
              border: `1px solid ${sectionColor}28`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={_hIcon(item)} size={12} color={sectionColor} />
            </span>
            <span style={{ fontSize: 13, lineHeight: 1.72, color: 'var(--fg-primary)', flex: 1, paddingTop: 4 }}>
              <InlineText text={item} />
            </span>
          </div>
        ))}
      </div>
    );
    listBuf = [];
  };

  lines.forEach((raw, idx) => {
    const line = raw.trim();

    // blank line — flush list
    if (!line) { flushList(idx); return; }

    // sub-heading: ## or ### level
    if (line.match(/^#{2,}\s/)) {
      flushList(idx);
      const label = line.replace(/^#+\s+/, '');
      out.push(
        <div key={idx} style={{
          display: 'flex', alignItems: 'center', gap: 9,
          marginTop: 22, marginBottom: 8,
          paddingLeft: 12,
          borderLeft: `3px solid ${sectionColor}`,
        }}>
          <Icon name={_hIcon(label)} size={13} color={sectionColor} />
          <span style={{
            fontFamily: 'var(--font-display)', fontSize: 11.5, fontWeight: 700,
            color: 'var(--fg-primary)', letterSpacing: '0.05em', textTransform: 'uppercase',
          }}>
            <InlineText text={label} />
          </span>
        </div>
      );

    // bullet item
    } else if (line.startsWith('- ') || line.startsWith('• ') || line.startsWith('* ')) {
      listBuf.push(line.replace(/^[-•*]\s+/, ''));

    // arrow / implication line
    } else if (line.startsWith('→') || line.startsWith('▸') || line.startsWith('⟹')) {
      flushList(idx);
      const body = line.replace(/^[→▸⟹]\s*/, '');
      out.push(
        <div key={idx} style={{
          display: 'flex', gap: 10, alignItems: 'flex-start',
          padding: '10px 14px', marginBottom: 8,
          background: sectionColor + '0E',
          borderLeft: `3px solid ${sectionColor}`,
          borderRadius: '0 8px 8px 0',
        }}>
          <Icon name="corner-down-right" size={13} color={sectionColor} style={{ flexShrink: 0, marginTop: 2 }} />
          <span style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--fg-primary)', flex: 1 }}>
            <InlineText text={body} />
          </span>
        </div>
      );

    // numbered item (1. or 1)
    } else if (line.match(/^\d+[.)]\s/)) {
      flushList(idx);
      const num = line.match(/^(\d+)/)[1];
      const body = line.replace(/^\d+[.)]\s+/, '');
      out.push(
        <div key={idx} style={{
          display: 'flex', gap: 10, alignItems: 'flex-start',
          padding: '8px 14px', marginBottom: 4,
        }}>
          <span style={{
            width: 22, height: 22, borderRadius: 6, flexShrink: 0,
            background: sectionColor + '20',
            color: sectionColor,
            fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{num}</span>
          <span style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--fg-primary)', paddingTop: 2 }}>
            <InlineText text={body} />
          </span>
        </div>
      );

    // plain paragraph
    } else {
      flushList(idx);
      out.push(
        <div key={idx} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 10 }}>
          <span style={{
            width: 26, height: 26, borderRadius: 7, flexShrink: 0,
            background: sectionColor + '12',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name={_hIcon(line)} size={12} color={sectionColor + 'AA'} />
          </span>
          <p style={{ fontSize: 13, lineHeight: 1.78, margin: 0, color: 'var(--fg-secondary)', flex: 1, paddingTop: 4 }}>
            <InlineText text={line} />
          </p>
        </div>
      );
    }
  });
  flushList('end');
  return <div style={{ paddingTop: 2 }}>{out}</div>;
};

// ── Full AI result dashboard — 15-section tab navigation ─────
const ProductAIResult = ({ aiTab, setAiTab, sections }) => {
  const total = Object.keys(sections).length;
  const meta  = PRODUCT_SECTION_META.find(s => s.num === aiTab);
  const sec   = sections[aiTab];
  const color = meta?.color || '#66FCF1';

  return (
    <React.Fragment>
      {/* Progress bar + counter */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <div style={{ flex: 1, height: 3, background: 'var(--border-subtle)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{
            width: `${(aiTab / 15) * 100}%`, height: '100%',
            background: color, borderRadius: 2, transition: 'width 0.25s ease',
          }} />
        </div>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-muted)', whiteSpace: 'nowrap' }}>
          {aiTab} / {total || 15} sections
        </span>
      </div>

      {/* Tab bar — scrollable */}
      <div style={{ overflowX: 'auto', marginBottom: 16, paddingBottom: 2 }}>
        <div style={{ display: 'flex', gap: 4, minWidth: 'max-content' }}>
          {PRODUCT_SECTION_META.map(s => {
            const isActive = aiTab === s.num;
            const hasSec   = !!sections[s.num];
            return (
              <button key={s.num} onClick={() => setAiTab(s.num)} style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 10px', borderRadius: 7, cursor: 'pointer',
                border: `1px solid ${isActive ? s.color + '70' : 'transparent'}`,
                background: isActive ? s.color + '1C' : hasSec ? 'var(--bg-surface-2)' : 'transparent',
                color: isActive ? s.color : hasSec ? 'var(--fg-secondary)' : 'var(--fg-muted)',
                opacity: hasSec ? 1 : 0.38,
                fontFamily: 'var(--font-display)', fontSize: 11,
                fontWeight: isActive ? 600 : 400, whiteSpace: 'nowrap',
                transition: 'all 0.12s', outline: 'none',
              }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8.5, opacity: 0.5, marginRight: 1 }}>
                  {s.num.toString().padStart(2, '0')}
                </span>
                <Icon name={s.icon} size={11} color={isActive ? s.color : 'currentColor'} />
                {s.short}
              </button>
            );
          })}
        </div>
      </div>

      {/* Section card */}
      {sec ? (
        <div style={{
          background: 'var(--bg-surface)',
          border: `1px solid ${color}30`,
          borderRadius: 12,
          overflow: 'hidden',
          marginBottom: 12,
        }}>
          {/* Card header */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 18px',
            background: color + '0C',
            borderBottom: `1px solid ${color}25`,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10, flexShrink: 0,
              background: color + '1E',
              border: `1px solid ${color}40`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={meta?.icon || 'box'} size={17} color={color} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: 'var(--font-display)', fontSize: 14.5, fontWeight: 700,
                color: 'var(--fg-primary)', letterSpacing: '-0.01em',
              }}>
                {sec.heading}
              </div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 9.5,
                color: 'var(--fg-muted)', letterSpacing: '0.08em',
                textTransform: 'uppercase', marginTop: 2,
              }}>
                Section {aiTab.toString().padStart(2,'0')} · AI Agent · Marketing Intelligence
              </div>
            </div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 11,
              color: color, fontWeight: 700,
              background: color + '15', padding: '3px 8px', borderRadius: 5,
              border: `1px solid ${color}30`,
            }}>
              #{aiTab.toString().padStart(2,'0')}
            </div>
          </div>

          {/* Card body */}
          <div style={{ padding: '18px 18px 10px 18px' }}>
            <ProductSectionBody content={sec.content} sectionColor={color} />
          </div>
        </div>
      ) : (
        <div style={{
          padding: '32px 0', textAlign: 'center',
          color: 'var(--fg-muted)', fontSize: 13,
          border: '1px dashed var(--border-subtle)', borderRadius: 10,
          marginBottom: 12,
        }}>
          Section {aiTab} chưa có trong output
        </div>
      )}

      {/* Dot pagination + Prev / Next */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <Btn variant="ghost" size="sm" icon="chevron-left"
          onClick={() => setAiTab(t => Math.max(1, t - 1))}>Prev</Btn>
        <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
          {PRODUCT_SECTION_META.map(s => (
            <div key={s.num} onClick={() => setAiTab(s.num)} style={{
              width: aiTab === s.num ? 18 : 5,
              height: 5, borderRadius: 3, cursor: 'pointer',
              background: aiTab === s.num ? color : sections[s.num] ? 'var(--border)' : 'var(--border-subtle)',
              transition: 'all 0.18s ease',
            }} />
          ))}
        </div>
        <Btn variant="ghost" size="sm" icon="chevron-right"
          onClick={() => setAiTab(t => Math.min(15, t + 1))}>Next</Btn>
      </div>

      <div className="btn-row" style={{ justifyContent: 'flex-end', marginTop: 4 }}>
        <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>
  );
};

const ScreenProduct = ({ section, onUpdateSection, allSections = {}, lang = 'vi' }) => {
  const T = (vi, en) => lang === 'en' ? en : vi;
  const [draft, setDraft] = React.useState('');
  const [running, setRunning] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [aiTab, setAiTab] = React.useState(1);
  const [linkedVersionOverrides, setLinkedVersionOverrides] = React.useState({});
  const active = section.versions.find(v => v.id === section.activeId) || section.versions[0];
  const data = active && active.output;
  const parsedSections = React.useMemo(
    () => (data && data._text) ? parseProductSections(data._text) : {},
    [data]
  );
  React.useEffect(() => { setAiTab(1); }, [section.activeId]);

  const submit = async (attachments = []) => {
    if (!draft.trim()) return;
    setRunning(true);
    setSubmitError(null);
    try {
      const linkedCtx = window.buildLinkedContext(section.linkedSources, allSections, linkedVersionOverrides);
      const attCtx    = window.buildAttachmentContext(attachments);
      const result = await window._aiCall(draft, 'product', section.styleId, linkedCtx + attCtx);
      const ts = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      const newVer = {
        id: `p-ai-${Date.now()}`,
        ts,
        label: draft.slice(0, 28) + (draft.length > 28 ? '…' : ''),
        output: { _text: result },
      };
      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 toggleSource = (k) => {
    const cur = section.linkedSources || [];
    onUpdateSection({ linkedSources: cur.includes(k) ? cur.filter(x => x !== k) : [...cur, k] });
  };

  return (
    <div className="screen-body" data-screen-label="01 Sản phẩm">
      <div className="screen-canvas">
        <div className="screen-section-label">{T('SẢN PHẨM', 'PRODUCT')}</div>

        <PromptInput
          placeholder="Tên sản phẩm: [tên]\nThông tin: [mô tả sản phẩm, tính năng, giá, đối tượng, thị trường…]"
          value={draft}
          onChange={setDraft}
          onSubmit={submit}
          running={running}
          runLabel="Generate"
          currentKind="product"
          model={section.model} onModelChange={(v) => onUpdateSection({ model: v })}
          styleId={section.styleId} onStyleChange={(v) => onUpdateSection({ styleId: v })}
          linkedSources={section.linkedSources || []} onToggleSource={toggleSource}
          suggestions={[
            { icon: 'target',       label: 'B2B SaaS · MRR-focused' },
            { icon: 'shopping-bag', label: 'DTC e-commerce angle' },
            { icon: 'graduation-cap', label: 'Khoá học online' },
            { icon: 'leaf',         label: 'Reposition lại sản phẩm cũ' },
          ]}
        />

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

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

        {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="Generating product brief…" lines={5} />
        ) : data && data._text ? (
          <ProductAIResult aiTab={aiTab} setAiTab={setAiTab} sections={parsedSections} />
        ) : null}
      </div>

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

const Mini = ({ label, value }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--fg-muted)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{label}</span>
    <span style={{ fontSize: 12, color: 'var(--fg-primary)', lineHeight: 1.4 }}>{value}</span>
  </div>
);

Object.assign(window, { ScreenProduct, InlineText, _hIcon });
