// Screen: CHÂN DUNG KHÁCH HÀNG / Persona — funnel layout

// ── 14-section metadata ───────────────────────────────────────
const PERSONA_SECTION_META = [
  { num: 1,  short: 'Overview',      icon: 'user',           color: '#2E9DF7' },
  { num: 2,  short: 'Life Context',  icon: 'home',           color: '#7B9CF7' },
  { num: 3,  short: 'Psychology',    icon: 'activity',       color: '#A78BFA' },
  { num: 4,  short: 'Buying Psych',  icon: 'shopping-cart',  color: '#4ADE80' },
  { num: 5,  short: 'Pain Points',   icon: 'alert-triangle', color: '#FBBF24' },
  { num: 6,  short: 'Desires',       icon: 'heart',          color: '#F472B6' },
  { num: 7,  short: 'Identity',      icon: 'star',           color: '#A78BFA' },
  { num: 8,  short: 'Content Beh.',  icon: 'play-circle',    color: '#66FCF1' },
  { num: 9,  short: 'Digital Beh.',  icon: 'smartphone',     color: '#2E9DF7' },
  { num: 10, short: 'Triggers',      icon: 'zap',            color: '#F472B6' },
  { num: 11, short: 'Objections',    icon: 'shield',         color: '#F87171' },
  { num: 12, short: 'Content Dir.',  icon: 'edit-3',         color: '#A78BFA' },
  { num: 13, short: 'Journey',       icon: 'map-pin',        color: '#4ADE80' },
  { num: 14, short: 'Segments',      icon: 'layers',         color: '#66FCF1' },
];

// Parse "# N. HEADING" markers into section map
function parsePersonaSections(text) {
  const result = {};
  let currentNum = null, currentHeading = '', 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;
}

// Section body renderer (uses globally-exposed InlineText + _hIcon from screen-product.jsx)
const PersonaSectionBody = ({ content, sectionColor = '#2E9DF7' }) => {
  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();
    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 ${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>
      );
    } else if (line.startsWith('- ') || line.startsWith('• ') || line.startsWith('* ')) {
      listBuf.push(line.replace(/^[-•*]\s+/, ''));
    } else if (line.startsWith('→') || line.startsWith('▸') || line.startsWith('⟹')) {
      flushList(idx);
      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={line.replace(/^[→▸⟹]\s*/, '')} />
          </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: 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>
      );
    } 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 Persona AI dashboard — 14-section tab navigation ─────
const PersonaAIResult = ({ aiTab, setAiTab, sections }) => {
  const total = Object.keys(sections).length;
  const meta  = PERSONA_SECTION_META.find(s => s.num === aiTab);
  const sec   = sections[aiTab];
  const color = meta?.color || '#2E9DF7';

  return (
    <React.Fragment>
      {/* Progress bar */}
      <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 / 14) * 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 || 14} sections
        </span>
      </div>

      {/* Tab bar */}
      <div style={{ overflowX: 'auto', marginBottom: 16, paddingBottom: 2 }}>
        <div style={{ display: 'flex', gap: 4, minWidth: 'max-content' }}>
          {PERSONA_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,
        }}>
          {/* 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 || 'user'} 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 · Customer Intelligence
              </div>
            </div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 11, color, fontWeight: 700,
              background: color + '15', padding: '3px 8px', borderRadius: 5,
              border: `1px solid ${color}30`,
            }}>
              #{aiTab.toString().padStart(2, '0')}
            </div>
          </div>
          {/* Body */}
          <div style={{ padding: '18px 18px 10px 18px' }}>
            <PersonaSectionBody 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 + nav */}
      <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' }}>
          {PERSONA_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(14, 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 ScreenPersona = ({ 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) ? parsePersonaSections(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, 'persona', section.styleId, linkedCtx + attCtx);
      const ts = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
      const newVer = {
        id: `ps-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="02 Chân dung khách hàng">
      <div className="screen-canvas">
        <div className="screen-section-label">{T('CHÂN DUNG KHÁCH HÀNG', 'CUSTOMER PERSONA')}</div>

        <PromptInput
          placeholder="Tên sản phẩm: [tên]\nThông tin: [mô tả]\nKhách hàng hiện tại: [nếu có]\nThị trường: [nếu có]"
          value={draft}
          onChange={setDraft}
          onSubmit={submit}
          running={running}
          runLabel="Generate"
          currentKind="persona"
          model={section.model} onModelChange={(v) => onUpdateSection({ model: v })}
          styleId={section.styleId} onStyleChange={(v) => onUpdateSection({ styleId: v })}
          linkedSources={section.linkedSources || []} onToggleSource={toggleSource}
          suggestions={[
            { icon: 'filter',   label: 'Funnel theo độ ready-to-buy' },
            { icon: 'users',    label: 'B2B decision-maker tier' },
            { icon: 'globe',    label: 'Funnel multi-region VN/TH/ID' },
            { icon: 'sparkles', label: 'Auto-pull từ Sản phẩm' },
          ]}
        />

        <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="Building customer intelligence profile…" lines={5} />
        ) : data && data._text ? (
          <PersonaAIResult aiTab={aiTab} setAiTab={setAiTab} sections={parsedSections} />
        ) : null}
      </div>

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

// ── Funnel tier (each layer of the funnel) ─────────────────
const TIER_COLORS = ['#6F4FF2', '#2E9DF7', '#FBBF24', '#4ADE80'];

const FunnelTier = ({ tier, index, total }) => {
  const [open, setOpen] = React.useState(index === 2); // "Considering" open by default
  const color = TIER_COLORS[index] || '#66FCF1';
  // Funnel shape: each tier narrower
  const insetPct = (index / (total - 1)) * 14; // 0–14% inset from each side
  return (
    <div className="funnel-tier-wrap" style={{ paddingLeft: `${insetPct}%`, paddingRight: `${insetPct}%` }}>
      <div className="funnel-tier" style={{ '--tier-color': color }}>
        <button className="funnel-tier-head" onClick={() => setOpen(o => !o)}>
          <div className="funnel-tier-num" style={{ background: `${color}22`, color }}>
            <span>{(index + 1).toString().padStart(2, '0')}</span>
          </div>
          <div className="funnel-tier-meta">
            <div className="funnel-tier-name">
              {tier.name}
              <span className="funnel-tier-en">· {tier.en}</span>
            </div>
            <div className="funnel-tier-desc">{tier.desc}</div>
          </div>
          <div className="funnel-tier-size">
            <span className="funnel-tier-size-val">{tier.size}</span>
            <span className="funnel-tier-size-pct" style={{ color }}>{tier.pct}%</span>
          </div>
          <div className="funnel-tier-bar" style={{ background: `${color}18` }}>
            <div className="funnel-tier-bar-fill" style={{ width: `${tier.pct * 1.5}%`, background: color }} />
          </div>
          <Icon name={open ? 'chevron-up' : 'chevron-down'} size={15} color="var(--fg-secondary)" />
        </button>
        {open && (
          <div className="funnel-tier-body fade-in">
            <div className="funnel-tier-grid">
              <div className="funnel-tier-col">
                <span className="funnel-tier-col-label">Triggers</span>
                <ul className="funnel-tier-bullets">
                  {tier.triggers.map((t, i) => <li key={i}>{t}</li>)}
                </ul>
              </div>
              <div className="funnel-tier-col">
                <span className="funnel-tier-col-label">Kênh thường dùng</span>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 4 }}>
                  {tier.channels.map((c, i) => (
                    <span key={i} style={{
                      background: 'var(--bg-surface-2)',
                      border: '1px solid var(--border-subtle)',
                      borderRadius: 999, padding: '3px 9px',
                      fontSize: 11, color: 'var(--fg-secondary)',
                    }}>{c}</span>
                  ))}
                </div>
              </div>
              <div className="funnel-tier-col">
                <span className="funnel-tier-col-label">Objection chính</span>
                <p style={{ fontSize: 12.5, color: 'var(--fg-primary)', lineHeight: 1.5, margin: 0, fontStyle: 'italic' }}>
                  "{tier.objection}"
                </p>
              </div>
            </div>

            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              letterSpacing: '0.14em', textTransform: 'uppercase',
              color: 'var(--fg-muted)', marginTop: 18, marginBottom: 8,
            }}>
              Personas mẫu trong tầng này ({tier.personas.length})
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 10 }}>
              {tier.personas.map((p, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 10, padding: 12,
                  background: 'var(--bg-surface-2)',
                  border: '1px solid var(--border-subtle)',
                  borderRadius: 8,
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 8,
                    background: `linear-gradient(135deg, ${color}, ${color}88)`,
                    color: '#fff',
                    fontFamily: 'var(--font-display)',
                    fontWeight: 600, fontSize: 13,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>{p.initial}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 600, color: 'var(--fg-primary)' }}>
                      {p.name}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--fg-secondary)', marginTop: 2 }}>{p.tag}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--fg-primary)', marginTop: 6, lineHeight: 1.5 }}>{p.note}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ScreenPersona, FunnelTier });
