// LINKONA prototype — campaign tracking + performance report.
(function () {
  const { Button, Card, Badge, Tag, Stat, MatchScore, Avatar, ProgressBar } = window.LINKONADesignSystem_465a88;
  const { Icon, Eyebrow, PageHead, SkinBar } = window;
  const D = window.LK_DATA;

  // ============ Campaign tracking ============
  const TIMELINE = [
    { t: 'AI 매칭', s: '적합 크리에이터 확정', done: true },
    { t: '계약 · 브리핑', s: '단가 협의 · 콘텐츠 가이드 전달', done: true },
    { t: '콘텐츠 제작', s: '호치민 현지 스튜디오 · 인플루언서 자체 제작', done: true, active: true },
    { t: '게시 · 시딩', s: '릴스 · 스토리 순차 게시', done: false },
    { t: '성과 분석', s: 'KPI 측정 · B&A 리포트', done: false },
  ];
  function AdvCampaign({ ds, onOpenReport }) {
    const C = D.CREATORS;
    const roster = ds.results.slice(0, 3).map((r, i) => ({ ...C[r.c], deliver: ['게시 완료', '제작 중', '초안 검토'][i], pct: [100, 60, 30][i], tone: ['success', 'blue', 'warning'][i] }));
    return (
      <div className="lk-fade">
        <PageHead eyebrow="CAMPAIGN · 진행중" title={ds.product.name}
          desc={`${ds.brief.market} · ${ds.brief.period} · ${roster.length}명 크리에이터 진행 중`}
          right={<Button variant="outline" onClick={onOpenReport} iconRight={<Icon name="arrowRight" size={17} />}>성과 리포트</Button>} />

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 16, marginBottom: 22 }} className="lk-stagger">
          <Card padding="md"><Stat value="342K" label="현재 도달" delta="+58K" deltaDir="up" /></Card>
          <Card padding="md"><Stat value="5.4%" label="평균 참여율" delta="+0.6%" deltaDir="up" /></Card>
          <Card padding="md"><Stat value="1,204" label="QR 스캔" delta="+180" deltaDir="up" /></Card>
          <Card padding="md"><Stat value="68%" label="캠페인 진척" gradient /></Card>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 22, alignItems: 'start' }}>
          {/* Roster */}
          <Card padding="none">
            <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>참여 크리에이터</h3>
            </div>
            {roster.map((c, i) => (
              <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '1fr 130px 120px', gap: 16, alignItems: 'center', padding: '15px 24px', borderTop: i ? '1px solid var(--border-subtle)' : 'none' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <Avatar name={c.name} size={42} ring status={c.status} />
                  <div>
                    <div style={{ fontSize: 14.5, fontWeight: 600 }}>{c.name}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-muted)' }}>{c.handle}</div>
                  </div>
                </div>
                <Badge tone={c.tone}>{c.deliver}</Badge>
                <ProgressBar value={c.pct} />
              </div>
            ))}
          </Card>
          {/* Timeline */}
          <Card padding="md">
            <Eyebrow style={{ marginBottom: 16 }}>진행 단계</Eyebrow>
            <div style={{ position: 'relative' }}>
              {TIMELINE.map((s, i) => (
                <div key={i} style={{ display: 'flex', gap: 13, paddingBottom: i < TIMELINE.length - 1 ? 20 : 0 }}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                    <div style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1,
                      background: s.done ? (s.active ? 'var(--grad-brand)' : 'var(--success-500)') : 'var(--ink-100)' }}>
                      {s.done && !s.active ? <Icon name="check" size={13} color="#fff" /> : s.active ? <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff' }} /> : <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--ink-300)' }} />}
                    </div>
                    {i < TIMELINE.length - 1 && <div style={{ width: 2, flex: 1, background: s.done ? 'var(--success-300, var(--success-500))' : 'var(--border-default)', marginTop: 2, minHeight: 20 }} />}
                  </div>
                  <div style={{ paddingTop: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: s.active ? 700 : 600, color: s.done ? 'var(--text-primary)' : 'var(--text-muted)' }}>{s.t}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.45 }}>{s.s}</div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    );
  }

  // ============ Performance report ============
  function AdvReport({ ds }) {
    const k = ds.kpi, sk = ds.skin;
    const bars = [38, 52, 61, 74, 82, 96]; // reach index over weeks
    return (
      <div className="lk-fade">
        <PageHead eyebrow="PERFORMANCE REPORT" title="성과 리포트"
          desc={`${ds.product.name} · ${ds.brief.market} 캠페인 · 한 번의 캠페인이 남기는 것.`}
          right={<Button variant="outline" iconLeft={<Icon name="report" size={16} />}>PDF 내보내기</Button>} />

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 16, marginBottom: 22 }} className="lk-stagger">
          <Card padding="md"><Stat value={k.reach} label="총 도달" delta={k.reachDelta} deltaDir="up" /></Card>
          <Card padding="md"><Stat value={k.roas} label="ROAS" delta="+0.6" deltaDir="up" gradient /></Card>
          <Card padding="md"><Stat value={k.ctr} label="평균 CTR" delta="+0.4%" deltaDir="up" /></Card>
          <Card padding="md"><Stat value={k.conv} label="전환율" delta="+0.3%" deltaDir="up" /></Card>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 22, marginBottom: 22, alignItems: 'start' }}>
          {/* Reach chart */}
          <Card padding="lg">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 20 }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>주차별 누적 도달</h3>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-muted)' }}>WEEKS 1–6</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'stretch', gap: 14, height: 180 }}>
              {bars.map((b, i) => (
                <div key={i} style={{ flex: 1, height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' }}>
                    <div className="lk-bar-y" style={{ width: '100%', height: b + '%', minHeight: 8, borderRadius: '8px 8px 3px 3px', background: i === bars.length - 1 ? 'var(--grad-brand)' : 'var(--blue-100)' }} />
                  </div>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-muted)', marginTop: 8 }}>W{i + 1}</span>
                </div>
              ))}
            </div>
          </Card>
          {/* Content breakdown */}
          <Card padding="lg">
            <h3 style={{ fontSize: 16, fontWeight: 600, margin: '0 0 18px' }}>콘텐츠 성과</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
              <BreakRow label="릴스 (자체 제작)" v="6.8%" w={90} />
              <BreakRow label="릴스 (현지 스튜디오)" v="7.4%" w={100} tone="var(--secondary)" />
              <BreakRow label="스토리 시딩" v="4.1%" w={55} tone="var(--accent)" />
            </div>
            <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
              <span style={{ color: 'var(--text-secondary)' }}>최고 성과 크리에이터</span>
              <span style={{ fontWeight: 600 }}>{D.CREATORS[ds.results[0].c].name}</span>
            </div>
          </Card>
        </div>

        {/* Before & After skin big-data (dark section) */}
        <Card padding="none" style={{ background: 'var(--ink-900)', border: 'none' }}>
          <div style={{ padding: '30px 34px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--amber-500)', marginBottom: 8 }}>SKIN BIG DATA · BEFORE & AFTER</div>
                <h3 style={{ fontSize: 21, fontWeight: 700, margin: 0, color: '#fff' }}>피부 빅데이터 리포트</h3>
                <p style={{ margin: '8px 0 0', color: 'rgba(255,255,255,.62)', fontSize: 13.5, maxWidth: 520, lineHeight: 1.6 }}>QR 코드로 수집된 제품 구매자 {sk.sample.toLocaleString()}명의 얼굴 이미지를 11가지 피부 지표로 수치화, Before/After를 분석했습니다.</p>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(255,255,255,.08)', padding: '10px 16px', borderRadius: 'var(--r-full)' }}>
                <Icon name="shield" size={18} color="var(--amber-500)" />
                <span style={{ fontSize: 12.5, color: '#fff', fontWeight: 500 }}>2024 CES 혁신상 엔진</span>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '40px 56px' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {sk.labels.map((l, i) => (
                  <div key={l} style={{ '--x': 1 }}>
                    <DarkSkinBar label={l} before={sk.before[i]} after={sk.after[i]} />
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 16 }}>
                <div style={{ display: 'flex', gap: 24 }}>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 800, lineHeight: 1, background: 'var(--grad-text)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>+{Math.round(sk.after.reduce((a, b) => a + b, 0) / 4 - sk.before.reduce((a, b) => a + b, 0) / 4)}</div>
                    <div style={{ fontSize: 13, color: 'rgba(255,255,255,.6)', marginTop: 6 }}>평균 지표 개선</div>
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 800, lineHeight: 1, color: '#fff' }}>{sk.sample.toLocaleString()}</div>
                    <div style={{ fontSize: 13, color: 'rgba(255,255,255,.6)', marginTop: 6 }}>분석 샘플 수</div>
                  </div>
                </div>
                <p style={{ margin: 0, fontSize: 13, color: 'rgba(255,255,255,.55)', lineHeight: 1.65 }}>이 데이터는 캠페인 성과 검증을 넘어, 피부 데이터가 필요한 업체에 판매 가능한 <span style={{ color: '#fff', fontWeight: 600 }}>자산</span>으로 축적됩니다. 링코나가 단순 매칭 플랫폼이 아닌, 글로벌 뷰티 데이터 플랫폼인 이유입니다.</p>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  const BreakRow = ({ label, v, w, tone }) => (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, marginBottom: 6 }}>
        <span style={{ color: 'var(--text-secondary)' }}>{label}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--success-600)' }}>{v}</span>
      </div>
      <div style={{ height: 8, background: 'var(--ink-100)', borderRadius: 'var(--r-full)', overflow: 'hidden' }}>
        <div className="lk-bar" style={{ width: w + '%', height: '100%', background: tone || 'var(--primary)', borderRadius: 'var(--r-full)', transformOrigin: 'left' }} />
      </div>
    </div>
  );

  const DarkSkinBar = ({ label, before, after }) => (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 7 }}>
        <span style={{ color: 'rgba(255,255,255,.72)' }}>{label}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--amber-500)' }}>+{after - before}</span>
      </div>
      <div style={{ position: 'relative', height: 9, background: 'rgba(255,255,255,.1)', borderRadius: 'var(--r-full)', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, width: before + '%', background: 'rgba(255,255,255,.28)', borderRadius: 'var(--r-full)' }} />
        <div className="lk-bar" style={{ position: 'absolute', inset: 0, width: after + '%', background: 'var(--grad-brand)', borderRadius: 'var(--r-full)', transformOrigin: 'left' }} />
      </div>
    </div>
  );

  Object.assign(window, { AdvCampaign, AdvReport });
})();
