// Screen: DIGITAL ADS — Meta Ads AI Intelligence System

const ADS_TABS = [
  {
    num: 1, id: 'overview',
    label: 'Ads Overview',
    icon: 'layers',
    color: '#F87171',
    sub: 'Strategic Layer',
    desc: 'Mục tiêu campaign · Bước đi chiến lược · Hành trình khách hàng · Meta AI learning',
  },
  {
    num: 2, id: 'setting',
    label: 'Ads Setting',
    icon: 'sliders',
    color: '#FBBF24',
    sub: 'Execution Layer',
    desc: 'Setup từng trường Ads Manager · Target · Location · Tuổi · Placement · Bid · Creative',
  },
  {
    num: 3, id: 'analytics',
    label: 'Analytics & Forecast',
    icon: 'bar-chart-2',
    color: '#4ADE80',
    sub: 'Intelligence Layer',
    desc: 'CPM · CTR · CPC · CPL · Reach · Conversion · Rủi ro · Scale potential',
  },
];

// ── Parser: split "# N. TITLE" top-level sections ─────────────

function parseAdsSections(text) {
  const result = {};
  let cur = null;
  const lines = [];

  const flush = () => {
    if (cur === null) return;
    result[cur] = lines.join('\n').trim();
    cur = null;
    lines.length = 0;
  };

  for (const line of (text || '').split('\n')) {
    const m = line.match(/^#\s+(\d+)\.\s+(.*)/);
    if (m) { flush(); cur = parseInt(m[1]); continue; }
    if (cur !== null) lines.push(line);
  }
  flush();
  return result;
}

// ── Content body renderer ─────────────────────────────────────

const AdsContentBody = ({ content, color = '#F87171' }) => {
  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: color + '18', border: `1px solid ${color}28`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={_hIcon(item)} size={12} color={color} />
            </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();
    if (!line) { flushList(idx); return; }

    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 ${color}`,
        }}>
          <Icon name={_hIcon(label)} size={13} color={color} />
          <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>
      );
    } else if (line.startsWith('- ') || line.startsWith('• ') || line.startsWith('* ')) {
      listBuf.push(line.replace(/^[-•*]\s+/, ''));
    } 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: color + '0E', borderLeft: `3px solid ${color}`,
          borderRadius: '0 8px 8px 0',
        }}>
          <Icon name="corner-down-right" size={13} color={color} />
          <span style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--fg-primary)', flex: 1 }}>
            <InlineText text={body} />
          </span>
        </div>
      );
    } 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: color + '20', color,
            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, flex: 1 }}>
            <InlineText text={body} />
          </span>
        </div>
      );
    } 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: color + '12',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name={_hIcon(line)} size={12} color={color + '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>;
};

// ── Overview renderer — SUMMARY chips + AdsContentBody ──────────

const AdsOverviewBody = ({ content, color }) => {
  const summaryItems = [];
  const restLines    = [];

  (content || '').split('\n').forEach(raw => {
    const line = raw.trim();
    const m = line.match(/^SUMMARY:\s*(.+?):\s*(.+)$/i);
    if (m) {
      summaryItems.push({ label: m[1].trim(), value: m[2].trim() });
    } else {
      restLines.push(raw);
    }
  });

  const CHIP_ICONS = [
    { key: 'chiến dịch',     icon: 'layers',       color: '#F87171' },
    { key: 'nhóm quảng cáo', icon: 'users',        color: '#FBBF24' },
    { key: 'bài quảng cáo',  icon: 'image',        color: '#4ADE80' },
  ];

  const iconFor = (label) => {
    const l = label.toLowerCase();
    const match = CHIP_ICONS.find(c => l.includes(c.key));
    return match || { icon: 'layers', color };
  };

  return (
    <div style={{ paddingTop: 2 }}>
      {summaryItems.length > 0 && (
        <div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' }}>
          {summaryItems.map((item, i) => {
            const cfg = iconFor(item.label);
            return (
              <div key={i} style={{
                flex: '1 1 140px', display: 'flex', alignItems: 'center', gap: 11,
                padding: '11px 16px', borderRadius: 10,
                border: `1.5px solid ${cfg.color}35`,
                background: `${cfg.color}0A`,
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 9, flexShrink: 0,
                  background: `${cfg.color}1C`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name={cfg.icon} size={16} color={cfg.color} />
                </div>
                <div>
                  <div style={{
                    fontSize: 10, fontWeight: 700, textTransform: 'uppercase',
                    letterSpacing: '0.05em', color: 'var(--fg-muted)', marginBottom: 3,
                  }}>
                    {item.label}
                  </div>
                  <div style={{
                    fontSize: 14.5, fontWeight: 700,
                    color: 'var(--fg-primary)', fontFamily: 'var(--font-display)',
                    lineHeight: 1.2,
                  }}>
                    {item.value}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
      <AdsContentBody content={restLines.join('\n')} color={color} />
    </div>
  );
};

// ── Setting renderer — "- Key: Value" bullets as form rows ────

const AdsSettingBody = ({ content, color }) => {
  const sections = [];
  let cur = null;

  (content || '').split('\n').forEach(raw => {
    const line = raw.trim();
    if (!line) return;
    if (line.match(/^#{2,}\s/)) {
      cur = { heading: line.replace(/^#+\s+/, ''), rows: [], other: [] };
      sections.push(cur);
    } else if (cur) {
      if (line.startsWith('- ') || line.startsWith('• ')) {
        cur.rows.push(line.replace(/^[-•]\s+/, ''));
      } else {
        cur.other.push(line);
      }
    } else {
      if (!sections.length) sections.push({ heading: null, rows: [], other: [] });
      sections[0].other.push(line);
    }
  });

  return (
    <div style={{ paddingTop: 2 }}>
      {sections.map((sec, si) => (
        <div key={si}>
          {sec.heading && (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 9,
              marginTop: si === 0 ? 4 : 22, marginBottom: 8,
              paddingLeft: 12, borderLeft: `3px solid ${color}`,
            }}>
              <Icon name={_hIcon(sec.heading)} size={13} color={color} />
              <span style={{
                fontFamily: 'var(--font-display)', fontSize: 11.5, fontWeight: 700,
                color: 'var(--fg-primary)', letterSpacing: '0.05em', textTransform: 'uppercase',
              }}>{sec.heading}</span>
            </div>
          )}
          {sec.other.map((line, i) => (
            <p key={`o-${i}`} style={{ fontSize: 12.5, lineHeight: 1.65, color: 'var(--fg-muted)', margin: '0 0 8px', paddingLeft: 4 }}>
              <InlineText text={line} />
            </p>
          ))}
          {sec.rows.length > 0 && (
            <div style={{
              marginBottom: 10, borderRadius: 10, overflow: 'hidden',
              border: `1px solid ${color}22`,
            }}>
              {sec.rows.map((row, i) => {
                const ci = row.indexOf(':');
                const hasKV = ci > 0 && ci < 55;
                const fKey = hasKV ? row.slice(0, ci).trim() : null;
                const fVal = hasKV ? row.slice(ci + 1).trim() : row;
                return (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'stretch',
                    borderBottom: i < sec.rows.length - 1 ? `1px solid ${color}15` : 'none',
                    background: i % 2 === 0 ? `${color}05` : 'transparent',
                  }}>
                    {fKey && (
                      <div style={{
                        minWidth: 155, maxWidth: 170, padding: '9px 12px',
                        borderRight: `1px solid ${color}18`,
                        display: 'flex', alignItems: 'center', gap: 6,
                        flexShrink: 0,
                      }}>
                        <Icon name={_hIcon(fKey)} size={11} color={color} />
                        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', lineHeight: 1.4 }}>{fKey}</span>
                      </div>
                    )}
                    <div style={{ flex: 1, padding: '9px 13px', fontSize: 12.5, color: 'var(--fg-primary)', lineHeight: 1.55, display: 'flex', alignItems: 'center' }}>
                      <InlineText text={fVal} />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

// ── Analytics renderer — METRIC lines as stat cards ───────────

const AdsAnalyticsBody = ({ content, color }) => {
  const metricLines = [];
  const restLines   = [];
  let metricsDone   = false;

  (content || '').split('\n').forEach(raw => {
    const line = raw.trim();
    if (!metricsDone && line.match(/^METRIC:\s*.+:\s*.+/i)) {
      const m = line.match(/^METRIC:\s*(.+?):\s*(.+)$/i);
      if (m) metricLines.push({ name: m[1].trim(), value: m[2].trim() });
    } else {
      if (metricLines.length && !metricsDone && !line.match(/^METRIC:/i)) metricsDone = true;
      restLines.push(raw);
    }
  });

  return (
    <div style={{ paddingTop: 2 }}>
      {metricLines.length > 0 && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
          gap: 10, marginBottom: 22,
        }}>
          {metricLines.map((m, i) => (
            <div key={i} style={{
              padding: '12px 14px', borderRadius: 10,
              border: `1px solid ${color}28`,
              background: `${color}08`,
            }}>
              <div style={{
                fontSize: 10, fontWeight: 700, letterSpacing: '0.05em',
                textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 6,
              }}>
                {m.name}
              </div>
              <div style={{
                fontSize: 15, fontWeight: 700,
                color, fontFamily: 'var(--font-display)', lineHeight: 1.3,
              }}>
                {m.value}
              </div>
            </div>
          ))}
        </div>
      )}
      <AdsContentBody content={restLines.join('\n')} color={color} />
    </div>
  );
};

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

const ScreenAds = ({ 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 [activeTab, setActiveTab] = 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 adsSections = React.useMemo(
    () => (data && data._text) ? parseAdsSections(data._text) : {},
    [data]
  );
  const hasSections = Object.keys(adsSections).length > 0;

  React.useEffect(() => { setActiveTab(1); }, [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 linkedCtx = window.buildLinkedContext(section.linkedSources, allSections, linkedVersionOverrides);
      const attCtx    = window.buildAttachmentContext(attachments);
      const result    = await window._aiCall(draft, 'ads', section.styleId, linkedCtx + attCtx);
      const ts     = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      const newVer = {
        id: `a-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 curTab = ADS_TABS.find(t => t.num === activeTab) || ADS_TABS[0];

  // Progress bar: count how many of 3 sections have content
  const sectionsDone = ADS_TABS.filter(t => adsSections[t.num] && adsSections[t.num].length > 0).length;

  return (
    <div className="screen-body" data-screen-label="04 Digital Ads">
      <div className="screen-canvas">
        <div className="screen-section-label">{T('DIGITAL ADS · META', 'DIGITAL ADS · META')}</div>

        <PromptInput
          placeholder="Nhập: mục tiêu campaign, sản phẩm, ngân sách/ngày, đối tượng, kết quả mong muốn, pixel status…"
          value={draft}
          onChange={setDraft}
          onSubmit={submit}
          running={running}
          runLabel="Generate"
          currentKind="ads"
          model={section.model}     onModelChange={(v) => onUpdateSection({ model: v })}
          styleId={section.styleId} onStyleChange={(v) => onUpdateSection({ styleId: v })}
          linkedSources={section.linkedSources || []} onToggleSource={toggleSource}
          suggestions={[
            { icon: 'user-plus',     label: 'Lead Generation campaign'  },
            { icon: 'shopping-cart', label: 'Conversion · Sales funnel'  },
            { icon: 'repeat',        label: 'Retargeting strategy'       },
            { icon: 'trending-up',   label: 'Scale từ winning ad set'    },
          ]}
        />

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

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

        {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="AI đang phân tích Meta signals & xây campaign strategy…" lines={8} />
        ) : hasSections ? (
          <React.Fragment>
            {/* Progress bar */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
              <div style={{ flex: 1, height: 3, background: 'var(--border-subtle)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{
                  width: `${(sectionsDone / 3) * 100}%`, height: '100%',
                  background: curTab.color, borderRadius: 2, transition: 'width 0.25s ease',
                }} />
              </div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-muted)', whiteSpace: 'nowrap' }}>
                {activeTab} / 3 layers
              </span>
            </div>

            {/* 3-tab navigation */}
            <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
              {ADS_TABS.map(tab => {
                const isActive   = activeTab === tab.num;
                const hasContent = !!(adsSections[tab.num] && adsSections[tab.num].length > 0);
                return (
                  <button
                    key={tab.num}
                    onClick={() => setActiveTab(tab.num)}
                    style={{
                      flex: 1, padding: '10px 12px', borderRadius: 10, cursor: 'pointer',
                      border: `1.5px solid ${isActive ? tab.color : 'var(--border)'}`,
                      background: isActive ? `${tab.color}0E` : 'var(--bg-surface)',
                      display: 'flex', alignItems: 'center', gap: 9,
                      transition: 'border-color 0.15s, background 0.15s',
                      textAlign: 'left', position: 'relative',
                    }}
                  >
                    <div style={{
                      width: 32, height: 32, borderRadius: 8, flexShrink: 0,
                      background: isActive ? `${tab.color}1C` : 'var(--bg-card)',
                      color: isActive ? tab.color : 'var(--fg-muted)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      transition: 'all 0.15s',
                    }}>
                      <Icon name={tab.icon} size={15} />
                    </div>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{
                        fontSize: 12, fontWeight: 600,
                        color: isActive ? 'var(--fg-primary)' : 'var(--fg-secondary)',
                        fontFamily: 'var(--font-display)', letterSpacing: '-0.01em',
                        lineHeight: 1.3, transition: 'color 0.15s',
                      }}>
                        {tab.label}
                      </div>
                      <div style={{ fontSize: 10, color: isActive ? tab.color + 'BB' : 'var(--fg-muted)', marginTop: 2, lineHeight: 1.3 }}>
                        {tab.sub}
                      </div>
                    </div>
                    {hasContent && (
                      <div style={{
                        width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
                        background: isActive ? tab.color : tab.color + '60',
                      }} />
                    )}
                  </button>
                );
              })}
            </div>

            {/* Active section content */}
            <OutputCard
              icon={curTab.icon}
              title={curTab.label}
              sub={`${curTab.sub} · AI Meta Ads Intelligence`}
            >
              {adsSections[activeTab] ? (
                activeTab === 1
                  ? <AdsOverviewBody  content={adsSections[activeTab]} color={curTab.color} />
                  : activeTab === 2
                    ? <AdsSettingBody   content={adsSections[activeTab]} color={curTab.color} />
                    : <AdsAnalyticsBody content={adsSections[activeTab]} color={curTab.color} />
              ) : (
                <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>
                  Không có dữ liệu cho phần này.
                </div>
              )}
            </OutputCard>

            {/* Navigation between tabs */}
            <div style={{ display: 'flex', gap: 8, marginTop: 12, justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ display: 'flex', gap: 8 }}>
                {activeTab > 1 && (
                  <Btn variant="ghost" size="sm" icon="arrow-left" onClick={() => setActiveTab(activeTab - 1)}>
                    {ADS_TABS[activeTab - 2].label}
                  </Btn>
                )}
              </div>
              <div className="btn-row" style={{ margin: 0 }}>
                <Btn variant="secondary" size="md" icon="git-fork">Send to Canvas</Btn>
                <Btn variant="primary"   size="md" icon="save">Save as file</Btn>
                <Btn variant="accent"    size="md" icon="external-link">Push to Ads Manager</Btn>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                {activeTab < 3 && (
                  <Btn variant="ghost" size="sm" icon="arrow-right" onClick={() => setActiveTab(activeTab + 1)}>
                    {ADS_TABS[activeTab].label}
                  </Btn>
                )}
              </div>
            </div>
          </React.Fragment>

        ) : data && data._text ? (
          <OutputCard icon="sparkles" title="Meta Ads Analysis" 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>

        ) : null}
      </div>

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

Object.assign(window, { ScreenAds });
