// LINKONA prototype — advertiser (brand) workspace.
(function () {
  const { Button, Card, Badge, Tag, Input, Select, Stat, MatchScore, ProgressBar, Avatar } = window.LINKONADesignSystem_465a88;
  const { Icon, Eyebrow, PageHead, Drawer } = window;
  const D = window.LK_DATA;

  // ============ Dashboard ============
  function AdvDashboard({ ds, onNew, onOpenReport }) {
    const k = ds.kpi;
    return (
      <div className="lk-fade">
        <PageHead eyebrow="OVERVIEW" title="대시보드"
          desc="베트남 테스트베드에서 진행 중인 K-뷰티 인플루언서 캠페인 현황입니다."
          right={<Button variant="gradient" onClick={onNew} iconLeft={<Icon name="plus" size={17} color="#fff" />}>새 캠페인</Button>} />
        <div className="lk-stagger" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 16, marginBottom: 22 }}>
          <Card padding="md"><Stat value="3.2M" label="누적 도달" delta="+240K" deltaDir="up" /></Card>
          <Card padding="md"><Stat value="94%" label="평균 매칭 정확도" delta="+3%" deltaDir="up" gradient /></Card>
          <Card padding="md"><Stat value="4.8x" label="평균 ROAS" delta="+0.4" deltaDir="up" /></Card>
          <Card padding="md"><Stat value="12" label="활성 크리에이터" delta="+3" deltaDir="up" /></Card>
        </div>
        <Card padding="none" style={{ marginBottom: 22 }}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 16.5, fontWeight: 600, margin: 0 }}>진행 캠페인</h3>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-muted)' }}>{D.CAMPAIGNS.length} ACTIVE</span>
          </div>
          <div>
            {D.CAMPAIGNS.map((c, i) => (
              <div key={i} className="lk-linkrow" onClick={() => c.status === '완료' && onOpenReport()} style={{ display: 'grid', gridTemplateColumns: '1.7fr 88px 88px 90px 1.1fr', gap: 18, alignItems: 'center', padding: '15px 24px', borderTop: i ? '1px solid var(--border-subtle)' : 'none', cursor: c.status === '완료' ? 'pointer' : 'default' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ width: 7, height: 32, borderRadius: 4, background: `var(--${c.tone}-500)`, flexShrink: 0 }} />
                  <div>
                    <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 4 }}>{c.name}</div>
                    <Badge tone={c.status === '완료' ? 'success' : c.status === '진행중' ? 'blue' : 'warning'}>{c.status}</Badge>
                  </div>
                </div>
                <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 14.5, fontWeight: 600 }}>{c.reach}</div><div style={{ fontSize: 11, color: 'var(--text-muted)' }}>도달</div></div>
                <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 14.5, fontWeight: 600, color: 'var(--success-600)' }}>{c.roas}</div><div style={{ fontSize: 11, color: 'var(--text-muted)' }}>ROAS</div></div>
                <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 14.5, fontWeight: 600 }}>{c.creators}</div><div style={{ fontSize: 11, color: 'var(--text-muted)' }}>크리에이터</div></div>
                <ProgressBar value={c.pct} />
              </div>
            ))}
          </div>
        </Card>
        <Card padding="lg" accent style={{ background: 'var(--grad-brand-soft)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' }}>
            <div style={{ maxWidth: 560 }}>
              <Eyebrow style={{ marginBottom: 8 }}>AI INFLUENCER MATCHING</Eyebrow>
              <h3 style={{ fontSize: 21, fontWeight: 700, margin: '0 0 8px' }}>제품 URL 한 줄에서 성과 리포트까지, 여섯 단계.</h3>
              <p style={{ margin: 0, color: 'var(--text-secondary)', fontSize: 14.5, lineHeight: 1.6 }}>단순 인플루언서 매칭이 아닙니다. 피부 빅데이터 기반 적합도 분석부터 콘텐츠 기획, 성과 리포트까지 하나의 흐름으로 이어집니다.</p>
            </div>
            <Button variant="gradient" size="lg" onClick={onNew} iconRight={<Icon name="arrowRight" size={18} color="#fff" />}>매칭 시작</Button>
          </div>
        </Card>
      </div>
    );
  }

  // ============ Campaign brief ============
  const STEPS = ['제품', '타깃 & 예산', '키워드'];
  function AdvBrief({ ds, grad, onRun, onBack }) {
    const [step, setStep] = React.useState(0);
    const [url, setUrl] = React.useState(ds.product.url);
    const [loaded, setLoaded] = React.useState(true);
    const [market, setMarket] = React.useState(ds.brief.market);
    const [budget, setBudget] = React.useState(ds.brief.budgetKRW);
    const [period, setPeriod] = React.useState(ds.brief.period);
    const [size, setSize] = React.useState(ds.brief.size);
    const [kws, setKws] = React.useState(ds.brief.keywords);
    const KW_POOL = ['브라이트닝', '데일리 루틴', '민감성', '수분', '선케어', '톤업', '숏폼', 'GRWM', '발색', '성분 리뷰', '진정', '글로우'];
    const toggleKw = (k) => setKws((p) => p.includes(k) ? p.filter((x) => x !== k) : [...p, k]);

    return (
      <div className="lk-fade" style={{ maxWidth: 860, margin: '0 auto' }}>
        <button onClick={onBack} className="lk-linkrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-secondary)', fontSize: 13.5, fontFamily: 'var(--font-sans)', padding: '4px 8px', borderRadius: 'var(--r-sm)', marginBottom: 14 }}>
          <Icon name="arrowLeft" size={16} /> 대시보드
        </button>
        <PageHead eyebrow="NEW CAMPAIGN" title="캠페인 브리프"
          desc="제품과 타깃을 입력하면 LINKONA AI 엔진이 베트남 크리에이터 풀에서 적합도를 계산합니다." />

        {/* Stepper */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 26 }}>
          {STEPS.map((s, i) => (
            <React.Fragment key={s}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <div style={{ width: 26, height: 26, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, fontFamily: 'var(--font-display)',
                  background: i <= step ? 'var(--grad-brand)' : 'var(--ink-100)', color: i <= step ? '#fff' : 'var(--text-muted)' }}>{i < step ? '✓' : i + 1}</div>
                <span style={{ fontSize: 13.5, fontWeight: i === step ? 600 : 500, color: i === step ? 'var(--text-primary)' : 'var(--text-muted)' }}>{s}</span>
              </div>
              {i < STEPS.length - 1 && <div style={{ flex: 1, height: 1.5, background: i < step ? 'var(--blue-300)' : 'var(--border-default)', margin: '0 14px' }} />}
            </React.Fragment>
          ))}
        </div>

        <Card padding="lg">
          {step === 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <Input label="제품 URL" value={url} onChange={(e) => setUrl(e.target.value)} iconLeft={<Icon name="link" size={17} />} placeholder="브랜드 제품 페이지 주소" />
              {loaded && (
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', padding: 16, background: 'var(--ink-50)', border: '1px solid var(--border-default)', borderRadius: 'var(--r-md)' }}>
                  <div style={{ width: 60, height: 60, borderRadius: 'var(--r-md)', background: 'var(--grad-brand-soft)', border: '1px solid var(--border-default)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name="sparkle" size={26} color="var(--secondary)" />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                      <span style={{ fontSize: 15, fontWeight: 600 }}>{ds.product.name}</span>
                      <Badge tone="blue">{ds.product.category}</Badge>
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5 }}>{ds.product.blurb}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600 }}>{ds.product.priceKRW}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--success-600)', display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'flex-end' }}><Icon name="check" size={12} color="var(--success-600)" /> 자동 인식</div>
                  </div>
                </div>
              )}
              <Input label="브랜드명" value={ds.brand.name} onChange={() => {}} />
            </div>
          )}
          {step === 1 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <Select label="타깃 시장" value={market} onChange={(e) => setMarket(e.target.value)} options={['베트남', '태국', '인도네시아', '필리핀']} />
              <Select label="캠페인 기간" value={period} onChange={(e) => setPeriod(e.target.value)} options={['2주', '3주', '4주', '6주', '8주']} />
              <Input label="예산 (KRW)" value={budget} onChange={(e) => setBudget(e.target.value)} iconLeft={<Icon name="wallet" size={17} />} />
              <Select label="팔로워 규모" value={size} onChange={(e) => setSize(e.target.value)} options={['나노 5K–20K', '마이크로 20K–50K', '미드 50K–200K', '매크로 200K+']} />
              <div style={{ gridColumn: '1 / -1', display: 'flex', gap: 12, padding: 14, background: 'var(--violet-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--violet-100)' }}>
                <Icon name="shield" size={20} color="var(--secondary)" style={{ marginTop: 1 }} />
                <div style={{ fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.55 }}><b>피부 빅데이터 매칭</b> — 2024 CES 혁신상 엔진이 제품 카테고리에 맞는 타깃 피부군을 자동 분류해 적합도에 반영합니다.</div>
              </div>
            </div>
          )}
          {step === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 5 }}>콘텐츠 키워드</div>
                <div style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 12 }}>선택한 키워드가 크리에이터 적합도 계산에 가중치로 반영됩니다.</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {KW_POOL.map((k) => <Tag key={k} selected={kws.includes(k)} onClick={() => toggleKw(k)}>{k}</Tag>)}
                </div>
              </div>
              <div style={{ padding: 18, background: 'var(--ink-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--border-default)' }}>
                <Eyebrow style={{ marginBottom: 12 }}>브리프 요약</Eyebrow>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px 24px', fontSize: 13.5 }}>
                  <SummRow label="제품" value={ds.product.name} />
                  <SummRow label="시장" value={market} />
                  <SummRow label="예산" value={budget} />
                  <SummRow label="기간" value={period} />
                  <SummRow label="규모" value={size} />
                  <SummRow label="키워드" value={kws.join(' · ') || '—'} />
                </div>
              </div>
            </div>
          )}
        </Card>

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
          <Button variant="ghost" onClick={() => step === 0 ? onBack() : setStep(step - 1)}>{step === 0 ? '취소' : '이전'}</Button>
          {step < 2
            ? <Button variant="primary" onClick={() => setStep(step + 1)} iconRight={<Icon name="arrowRight" size={17} color="#fff" />}>다음</Button>
            : <Button variant="gradient" size="lg" onClick={() => onRun({ market, budget, period, size, kws })} iconLeft={<Icon name="sparkle" size={18} color="#fff" />}>AI 매칭 실행</Button>}
        </div>
      </div>
    );
  }
  const SummRow = ({ label, value }) => (
    <div style={{ display: 'flex', gap: 10 }}>
      <span style={{ color: 'var(--text-muted)', minWidth: 44 }}>{label}</span>
      <span style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{value}</span>
    </div>
  );

  // ============ Matching (loading -> results) ============
  const PHASES = [
    { t: '인플루언서 데이터 수집', s: 'StarNgage · Heepsy · Modash · KOCCA' },
    { t: 'AI 스크리닝', s: '2,000+ 베트남 크리에이터 풀 필터링' },
    { t: '피부 빅데이터 분류', s: 'LINKONA AI 엔진 · 타깃 피부군 매핑' },
    { t: 'CPM/CPE 최적화 매칭', s: 'ROI 예측 · 적합도 점수 산출' },
  ];
  function AdvMatchLoading({ onDone }) {
    const [p, setP] = React.useState(0);
    React.useEffect(() => {
      const timers = PHASES.map((_, i) => setTimeout(() => setP(i + 1), 700 * (i + 1)));
      const done = setTimeout(onDone, 700 * PHASES.length + 650);
      return () => { timers.forEach(clearTimeout); clearTimeout(done); };
    }, []);
    return (
      <div style={{ maxWidth: 560, margin: '40px auto 0' }} className="lk-fade">
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ position: 'relative', width: 78, height: 78, margin: '0 auto 20px' }}>
            <div className="lk-spin" style={{ position: 'absolute', inset: 0, borderRadius: '50%', background: 'conic-gradient(from 0deg, transparent, var(--blue-500), var(--violet-500), var(--orange-500), transparent)', WebkitMask: 'radial-gradient(farthest-side, transparent calc(100% - 5px), #000 calc(100% - 5px))', mask: 'radial-gradient(farthest-side, transparent calc(100% - 5px), #000 calc(100% - 5px))' }} />
            <div style={{ position: 'absolute', inset: 18, borderRadius: '50%', background: 'var(--grad-brand-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="sparkle" size={28} color="var(--secondary)" />
            </div>
          </div>
          <Eyebrow style={{ marginBottom: 8 }}>AI MATCHING</Eyebrow>
          <h2 style={{ fontSize: 23, fontWeight: 700, margin: 0 }}>적합한 크리에이터를 찾는 중…</h2>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {PHASES.map((ph, i) => {
            const done = i < p, active = i === p;
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 18px', background: 'var(--bg-surface)', border: `1px solid ${active ? 'var(--blue-300)' : 'var(--border-default)'}`, borderRadius: 'var(--r-md)', boxShadow: active ? 'var(--shadow-sm)' : 'none', opacity: i > p ? 0.5 : 1, transition: 'all .3s var(--ease-out)' }}>
                <div style={{ width: 28, height: 28, borderRadius: '50%', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: done ? 'var(--success-100)' : active ? 'var(--blue-50)' : 'var(--ink-100)' }}>
                  {done ? <Icon name="check" size={16} color="var(--success-600)" /> : active ? <div className="lk-spin" style={{ width: 15, height: 15, borderRadius: '50%', border: '2px solid var(--blue-200)', borderTopColor: 'var(--primary)' }} /> : <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>{i + 1}</span>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: done || active ? 'var(--text-primary)' : 'var(--text-muted)' }}>{ph.t}</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{ph.s}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  function AdvResults({ ds, onOpen, proposals }) {
    const C = D.CREATORS;
    return (
      <div className="lk-fade">
        <PageHead eyebrow="AI MATCHING · 결과" title="매칭 결과"
          desc={`${ds.product.name} · ${ds.brief.market} · 적합도 순으로 정렬되었습니다.`} />
        <div style={{ display: 'grid', gridTemplateColumns: '288px 1fr', gap: 22, alignItems: 'start' }}>
          {/* Filter recap */}
          <Card padding="md">
            <Eyebrow style={{ marginBottom: 14 }}>매칭 조건</Eyebrow>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <FilterRow label="제품 카테고리" value={ds.product.category} />
              <FilterRow label="타깃 시장" value={ds.brief.market} />
              <FilterRow label="팔로워 규모" value={ds.brief.size} />
              <div>
                <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginBottom: 8 }}>콘텐츠 키워드</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{ds.brief.keywords.map((k) => <Tag key={k} selected>{k}</Tag>)}</div>
              </div>
              <div style={{ padding: 12, background: 'var(--grad-brand-soft)', borderRadius: 'var(--r-md)', border: '1px solid var(--border-default)', display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                <Icon name="shield" size={16} color="var(--secondary)" style={{ marginTop: 1 }} />
                <span style={{ fontSize: 12, color: 'var(--ink-700)', lineHeight: 1.5 }}>피부 빅데이터 기반 적합도 · CES 혁신상 엔진</span>
              </div>
            </div>
          </Card>
          {/* Result cards */}
          <div>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
              <span style={{ fontSize: 14, color: 'var(--text-secondary)' }}>매칭 결과 <b style={{ color: 'var(--text-primary)' }}>{ds.results.length}명</b> · 정확도순</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-muted)' }}>매일 업데이트</span>
            </div>
            <div className="lk-stagger" style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
              {ds.results.map((r) => {
                const c = C[r.c];
                const sent = proposals.includes(c.id);
                return (
                  <Card key={c.id} padding="md" interactive onClick={() => onOpen(c)}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                      <Avatar name={c.name} size={54} ring status={c.status} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                          <span style={{ fontSize: 16, fontWeight: 600 }}>{c.name}</span>
                          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>{c.handle}</span>
                          <Badge tone="blue">{c.cat}</Badge>
                          {sent && <Badge tone="success">제안 완료</Badge>}
                        </div>
                        <div style={{ display: 'flex', gap: 18, fontFamily: 'var(--font-mono)', fontSize: 12.5, color: 'var(--text-secondary)', marginBottom: 8 }}>
                          <span>팔로워 <b style={{ color: 'var(--text-primary)' }}>{c.followers}</b></span>
                          <span>참여율 <b style={{ color: 'var(--success-600)' }}>{c.eng}</b></span>
                          <span>{c.city}</span>
                        </div>
                        <div style={{ fontSize: 12.5, color: 'var(--text-secondary)', display: 'flex', gap: 7, alignItems: 'flex-start' }}>
                          <Icon name="sparkle" size={14} color="var(--secondary)" style={{ marginTop: 1, flexShrink: 0 }} />
                          <span>{r.why}</span>
                        </div>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                        <MatchScore score={r.score} size={62} label="AI Fit" />
                        <Icon name="chevronRight" size={18} color="var(--ink-300)" />
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }
  const FilterRow = ({ label, value }) => (
    <div><div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginBottom: 3 }}>{label}</div><div style={{ fontSize: 14, fontWeight: 500 }}>{value}</div></div>
  );

  Object.assign(window, { AdvDashboard, AdvBrief, AdvMatchLoading, AdvResults });
})();
