// LINKONA prototype — creator detail drawer + proposal flow.
(function () {
  const { Button, Card, Badge, Tag, Input, Select, MatchScore, Avatar, ProgressBar } = window.LINKONADesignSystem_465a88;
  const { Icon, Eyebrow, Drawer } = window;
  const D = window.LK_DATA;

  function CreatorDrawer({ creator, result, ds, open, onClose, onSend, alreadySent }) {
    const [mode, setMode] = React.useState('profile'); // profile | compose | sent
    const [msg, setMsg] = React.useState('');
    React.useEffect(() => { if (open) { setMode(alreadySent ? 'profile' : 'profile'); setMsg(''); } }, [open, creator]);
    if (!creator) return null;
    const c = creator, a = c.audience;

    const send = () => { setMode('sent'); onSend(c.id); };

    return (
      <Drawer open={open} onClose={onClose} width={540}>
        {/* Header */}
        <div style={{ padding: '22px 28px', borderBottom: '1px solid var(--border-default)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'sticky', top: 0, background: 'var(--bg-surface)', zIndex: 5 }}>
          <Eyebrow>CREATOR PROFILE</Eyebrow>
          <button onClick={onClose} style={{ border: 'none', background: 'var(--ink-100)', width: 32, height: 32, borderRadius: '50%', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="x" size={17} color="var(--ink-500)" /></button>
        </div>

        <div style={{ padding: 28 }}>
          {/* Identity */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22 }}>
            <Avatar name={c.name} size={72} ring status={c.status} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 4 }}>
                <span style={{ fontSize: 21, fontWeight: 700, fontFamily: 'var(--font-display)' }}>{c.name}</span>
                <Badge tone="blue">{c.cat}</Badge>
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-muted)', marginBottom: 6 }}>{c.handle} · {c.city}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-secondary)', lineHeight: 1.55 }}>{c.bio}</div>
            </div>
            {result && <MatchScore score={result.score} size={66} label="AI Fit" />}
          </div>

          {result && (
            <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start', padding: 14, background: 'var(--grad-brand-soft)', border: '1px solid var(--border-default)', borderRadius: 'var(--r-md)', marginBottom: 22 }}>
              <Icon name="sparkle" size={17} color="var(--secondary)" style={{ marginTop: 1, flexShrink: 0 }} />
              <div style={{ fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.55 }}><b>매칭 근거</b> · {result.why}</div>
            </div>
          )}

          {mode === 'profile' && (
            <>
              {/* Stats */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 22 }}>
                <MiniStat label="팔로워" value={c.followers} />
                <MiniStat label="참여율" value={c.eng} tone="var(--success-600)" />
                <MiniStat label="평균 조회" value={c.avgViews} />
              </div>

              {/* Audience */}
              <SectionLabel>오디언스</SectionLabel>
              <Card padding="md" style={{ marginBottom: 20 }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <AudRow label="여성 비율" pct={a.female} display={a.female + '%'} />
                  <AudRow label={`주 연령대 ${a.ageTop}`} pct={a.agePct} display={a.agePct + '%'} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
                    <span style={{ color: 'var(--text-secondary)' }}>주요 지역</span>
                    <span style={{ fontWeight: 600 }}>{a.city}</span>
                  </div>
                </div>
              </Card>

              {/* Keywords */}
              <SectionLabel>콘텐츠 키워드</SectionLabel>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 20 }}>{c.kw.map((k) => <Tag key={k} selected>{k}</Tag>)}</div>

              {/* Past work */}
              <SectionLabel>최근 협업</SectionLabel>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 8 }}>
                {c.past.map((p, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', border: '1px solid var(--border-default)', borderRadius: 'var(--r-md)' }}>
                    <div style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', background: 'var(--ink-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="play" size={16} color="var(--ink-400)" /></div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.brand}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{p.type}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13.5, fontWeight: 600, color: 'var(--success-600)' }}>{p.roas}</div>
                      <div style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>ROAS</div>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {mode === 'compose' && (
            <div className="lk-fade">
              <SectionLabel>제안 내용</SectionLabel>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <Input label="제안 단가 (VND)" value={c.priceVND} onChange={() => {}} iconLeft={<Icon name="wallet" size={16} />} />
                  <Select label="산출물" defaultValue="릴스 1 · 스토리 3" options={['릴스 1 · 스토리 3', '숏폼 2', '릴스 1', '릴스 2 · 스토리 5']} />
                </div>
                <div>
                  <label style={{ fontSize: 14, fontWeight: 500, display: 'block', marginBottom: 7 }}>메시지</label>
                  <textarea value={msg} onChange={(e) => setMsg(e.target.value)} placeholder={`${c.name} 님, ${ds.product.name} 캠페인 협업을 제안드립니다…`} rows={4}
                    style={{ width: '100%', padding: '12px 14px', border: '1px solid var(--border-default)', borderRadius: 'var(--r-md)', fontFamily: 'var(--font-sans)', fontSize: 14.5, resize: 'vertical', outline: 'none', lineHeight: 1.55, color: 'var(--text-primary)' }} />
                </div>
                <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start', padding: 13, background: 'var(--ink-50)', borderRadius: 'var(--r-md)' }}>
                  <Icon name="camera" size={17} color="var(--ink-500)" style={{ marginTop: 1 }} />
                  <span style={{ fontSize: 12.5, color: 'var(--text-secondary)', lineHeight: 1.5 }}>콘텐츠는 호치민 현지 스튜디오(HAVANA · CINE SPACE) 제작 지원을 함께 선택할 수 있습니다.</span>
                </div>
              </div>
            </div>
          )}

          {mode === 'sent' && (
            <div className="lk-fade" style={{ textAlign: 'center', padding: '30px 0 10px' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--success-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
                <Icon name="check" size={30} color="var(--success-600)" />
              </div>
              <h3 style={{ fontSize: 19, fontWeight: 700, margin: '0 0 8px' }}>제안을 보냈습니다</h3>
              <p style={{ fontSize: 14, color: 'var(--text-secondary)', margin: '0 0 22px', lineHeight: 1.6 }}>{c.name} 님이 제안을 검토하면 알림으로 안내드립니다.<br/>보통 <b style={{ color: 'var(--text-primary)' }}>3일 이내</b> 응답합니다.</p>
              <div style={{ display: 'inline-flex', gap: 10 }}>
                <Button variant="outline" onClick={onClose}>닫기</Button>
                <Button variant="primary" onClick={() => setMode('profile')}>프로필 다시 보기</Button>
              </div>
            </div>
          )}
        </div>

        {/* Sticky action bar */}
        {mode !== 'sent' && (
          <div style={{ position: 'sticky', bottom: 0, background: 'var(--bg-surface)', borderTop: '1px solid var(--border-default)', padding: '16px 28px', display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>예상 단가</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 600 }}>{c.priceVND}</div>
            </div>
            {mode === 'profile'
              ? (alreadySent
                  ? <Button variant="outline" disabled iconLeft={<Icon name="check" size={17} color="var(--ink-400)" />}>제안 완료</Button>
                  : <Button variant="gradient" size="lg" onClick={() => setMode('compose')} iconRight={<Icon name="arrowRight" size={18} color="#fff" />}>제안 보내기</Button>)
              : <div style={{ display: 'flex', gap: 10 }}>
                  <Button variant="ghost" onClick={() => setMode('profile')}>뒤로</Button>
                  <Button variant="gradient" size="lg" onClick={send} iconLeft={<Icon name="check" size={18} color="#fff" />}>제안 전송</Button>
                </div>}
          </div>
        )}
      </Drawer>
    );
  }

  const MiniStat = ({ label, value, tone }) => (
    <div style={{ padding: '13px 14px', background: 'var(--ink-50)', borderRadius: 'var(--r-md)', textAlign: 'center' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 700, color: tone || 'var(--text-primary)' }}>{value}</div>
      <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{label}</div>
    </div>
  );
  const SectionLabel = ({ children }) => (
    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 10 }}>{children}</div>
  );
  const AudRow = ({ label, pct, display }) => (
    <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 }}>{display}</span>
      </div>
      <ProgressBar value={pct} height={6} />
    </div>
  );

  Object.assign(window, { CreatorDrawer });
})();
