/* screen-creator.jsx — Creator Portal Dashboard */
/* global React, Sidebar, Topbar, Counter, Sparkline, BarChart, LineChart, Donut, Avatar, Pill, MatchCircle, Icon, useInView, Reveal */

function ScreenCreator() {
  return (
    <div className="app-shell" data-portal="creator">
      <AppSidebar portal="creator" active="creator-dashboard" />
      <main className="main">
        <AppTopbar user="L" />

        {/* Hero strip */}
        <div className="row items-end justify-between mb-6">
          <div>
            <span className="pill pill-mint">Creator workspace</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>
              Hey <span style={{
                background: 'linear-gradient(90deg, #1FD6B4, #009CFF)',
                WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent'
              }}>Linh</span>, you&rsquo;re on a streak.
            </h1>
            <div className="page-subtitle">7 brands actively viewing your media kit · 3 briefs waiting for reply</div>
          </div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm">{Icon.external} Public profile</button>
            <button className="btn btn-primary btn-sm">{Icon.plus} New post</button>
          </div>
        </div>

        {/* Top row: earnings + streak + open briefs */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr 1fr', gap: 14 }}>
          <EarningsHero />
          <StreakCard />
          <OpenBriefsCounter />
        </div>

        {/* Middle: brief feed + content performance */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 14, marginTop: 18 }}>
          <BriefFeed />
          <ContentPerformance />
        </div>

        {/* Media kit + audience */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 14, marginTop: 18 }}>
          <MediaKitPreview />
          <CreatorAudience />
        </div>

        {/* Earnings calendar */}
        <div style={{ marginTop: 18 }}>
          <EarningsTimeline />
        </div>

      </main>
    </div>
  );
}

function EarningsHero() {
  return (
    <div className="card-elevated" style={{
      padding: 24,
      background: 'linear-gradient(135deg, #79FEE7 0%, #009CFF 110%)',
      color: 'var(--ink)',
      position: 'relative', overflow: 'hidden',
      minHeight: 200
    }}>
      <div style={{
        position: 'absolute', top: -40, right: -40,
        width: 200, height: 200, borderRadius: '50%',
        background: 'rgba(255,255,255,0.35)',
        filter: 'blur(20px)'
      }} />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <div className="cap-label" style={{ color: 'var(--ink)', opacity: 0.7 }}>This month · May 2026</div>
        <div className="font-display tabular" style={{ fontSize: 'clamp(40px, 4.6vw, 60px)', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 12 }}>
          <Counter to={2840} prefix="$" duration={2200} />
        </div>
        <div className="row items-center gap-8 mt-3">
          <Pill variant="ink" icon={Icon.trend}>+62% vs last month</Pill>
          <span style={{ fontSize: 12, fontWeight: 600 }}>Q2 total: <span className="bold tabular">$4,720</span></span>
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 14, right: 14 }}>
        <Sparkline data={[800, 1200, 1450, 1800, 2100, 2400, 2840]} color="white" fillId="earnSpark" height={56} />
      </div>
    </div>
  );
}

function StreakCard() {
  return (
    <div className="card-elevated" style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
      <div className="cap-label">On time delivery streak</div>
      <div className="row items-end gap-6 mt-2">
        <div className="font-display tabular" style={{ fontSize: 56, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, color: 'var(--coral)' }}>
          <Counter to={14} duration={1500} />
        </div>
        <div className="muted" style={{ fontSize: 12, paddingBottom: 8 }}>campaigns</div>
      </div>

      {/* flames */}
      <div className="row gap-4 mt-3" style={{ flexWrap: 'wrap' }}>
        {Array.from({ length: 14 }).map((_, i) => (
          <div key={i} style={{
            width: 18, height: 22,
            background: i < 12 ? `linear-gradient(180deg, #FEE960, #FF7A59)` : '#FFD9CC',
            clipPath: 'polygon(50% 0%, 100% 35%, 100% 80%, 60% 100%, 40% 100%, 0% 80%, 0% 35%)',
            animation: `flame .4s ${i * 60}ms backwards`,
            transform: 'scale(0)'
          }} />
        ))}
      </div>
      <div className="muted" style={{ fontSize: 11, marginTop: 8 }}>
        12 weeks fire 🔥 · 2 weeks to break record (16)
      </div>
      <style>{`@keyframes flame { from { transform: scale(0); } to { transform: scale(1); } }`}</style>
    </div>
  );
}

function OpenBriefsCounter() {
  return (
    <div className="card-elevated" style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
      <div className="cap-label">Open briefs · accepting</div>
      <div className="font-display tabular" style={{ fontSize: 56, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 6 }}>
        <Counter to={7} duration={1200} />
      </div>
      <div className="row items-center gap-8 mt-2">
        <Pill variant="cyan">Matched</Pill>
        <Pill variant="yellow">3 closing soon</Pill>
      </div>

      {/* timeline bars showing brief deadlines */}
      <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 4 }}>
        {[
          { d: 'Acne care · DermaQ', days: 2, c: 'var(--coral)' },
          { d: 'Tet 26 fashion · YODY', days: 5, c: 'var(--yellow-deep)' },
          { d: 'Vegan snacks · Saigon Vegan', days: 9, c: 'var(--mint-deep)' },
          { d: 'Smart home · Xiaomi VN', days: 14, c: 'var(--indigo)' },
        ].map((b, i) => (
          <div key={i} className="row items-center gap-8" style={{ fontSize: 11 }}>
            <span style={{ flex: 1, fontWeight: 600 }}>{b.d}</span>
            <div style={{ width: 80, height: 4, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{
                height: '100%', width: ((14 - b.days) / 14 * 100) + '%',
                background: b.c, borderRadius: 999
              }} />
            </div>
            <span className="tabular bold" style={{ width: 36, textAlign: 'right' }}>{b.days}d</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function BriefFeed() {
  const briefs = [
    { brand: 'DermaQ', title: 'Acne care · awareness video', match: 92, budget: '$1.2K – $2.4K', deadline: '2d', tags: ['skincare', 'tiktok', 'GenZ'] },
    { brand: 'YODY', title: 'Tet 2026 fashion — IG reels', match: 84, budget: '$1.8K – $3.6K', deadline: '5d', tags: ['fashion', 'instagram'] },
    { brand: 'Saigon Vegan', title: 'Plant-based protein bars', match: 78, budget: '$800 – $1.6K', deadline: '9d', tags: ['food', 'wellness'] },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Matched briefs</div>
          <div className="muted" style={{ fontSize: 12 }}>AI matches based on your media kit</div>
        </div>
        <a className="row items-center gap-6" style={{ fontSize: 12, color: 'var(--cyan-dark)', fontWeight: 700, cursor: 'pointer' }}>
          View all 7 {Icon.arrow}
        </a>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {briefs.map((b, i) => (
          <div key={i} style={{
            padding: 14, background: 'var(--bg-soft)', borderRadius: 14,
            position: 'relative',
            animation: `cardIn .5s ${0.2 + i * 0.12}s backwards cubic-bezier(.4,0,.2,1)` }}>
            <div className="row items-center gap-12">
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: ['var(--cyan)', 'var(--pink-hot)', 'var(--mint-deep)'][i],
                color: 'white', display: 'grid', placeItems: 'center',
                fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 18
              }}>{b.brand.charAt(0)}</div>
              <div className="flex-1">
                <div className="row items-center gap-6">
                  <div className="bold" style={{ fontSize: 13 }}>{b.brand}</div>
                  <span className="muted" style={{ fontSize: 11 }}>· {b.deadline} left</span>
                </div>
                <div className="font-display bold" style={{ fontSize: 14, marginTop: 2 }}>{b.title}</div>
                <div className="row gap-4 mt-2" style={{ flexWrap: 'wrap' }}>
                  {b.tags.map(t => <Pill key={t} variant="ink">{t}</Pill>)}
                </div>
              </div>
              <div className="text-right">
                <MatchCircle score={b.match} size={48} />
                <div className="bold tabular" style={{ fontSize: 11, marginTop: 4 }}>{b.budget}</div>
              </div>
            </div>
            <div className="row gap-8 mt-3">
              <button className="btn btn-ghost btn-sm" style={{ flex: 1, padding: '6px 12px' }}>Pass</button>
              <button className="btn btn-primary btn-sm" style={{ flex: 1, padding: '6px 12px' }}>Apply {Icon.arrow}</button>
            </div>
          </div>
        ))}
      </div>
      <style>{`@keyframes cardIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </div>
  );
}

function ContentPerformance() {
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Engagement rate · 12 weeks</div>
          <div className="muted" style={{ fontSize: 12 }}>You&rsquo;re trending up · top 8% in your tier</div>
        </div>
        <Pill variant="mint" icon={Icon.trend}>+0.8pp</Pill>
      </div>
      <LineChart
        series={[
          { name: 'You', color: '#1FD6B4', data: [3.2, 3.4, 3.1, 3.6, 4.0, 3.8, 4.2, 4.4, 4.6, 4.8, 5.1, 5.4] },
          { name: 'Tier avg', color: '#738A9E', data: [3.8, 3.9, 4.0, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5] },
        ]}
        xLabels={['W1','W2','W3','W4','W5','W6','W7','W8','W9','W10','W11','W12']}
        height={220}
      />
      <div className="row gap-12 mt-3" style={{ paddingTop: 12, borderTop: '1px solid var(--line)' }}>
        <div className="row items-center gap-6"><span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--mint-deep)' }} /><span style={{ fontSize: 12, fontWeight: 600 }}>You · 5.4%</span></div>
        <div className="row items-center gap-6"><span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--ink-soft)' }} /><span style={{ fontSize: 12, fontWeight: 600 }}>Skincare · Micro avg · 4.5%</span></div>
      </div>
    </div>
  );
}

function MediaKitPreview() {
  return (
    <div className="card-elevated" style={{ position: 'relative', overflow: 'hidden' }}>
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Your media kit</div>
          <div className="muted" style={{ fontSize: 12 }}>Auto-built from your last 60 posts · refreshed 2h ago</div>
        </div>
        <button className="btn btn-ghost btn-sm">Edit</button>
      </div>

      <div className="row items-center gap-16 mb-4">
        <div style={{ position: 'relative' }}>
          <Avatar name="Linh Châu" size={72} />
          <div style={{ position: 'absolute', bottom: -2, right: -2 }}>{Icon.verified}</div>
        </div>
        <div className="flex-1">
          <div className="font-display bold" style={{ fontSize: 20, letterSpacing: '-0.015em' }}>Linh Châu</div>
          <div className="muted" style={{ fontSize: 12 }}>@linhchau · Skincare · Beauty · HCM</div>
          <div className="row gap-6 mt-2">
            <Pill variant="cyan" icon={Icon.tiktok}>482K</Pill>
            <Pill variant="pink" icon={Icon.instagram}>184K</Pill>
            <Pill variant="ink" icon={Icon.youtube}>32K</Pill>
          </div>
        </div>
        <div>
          <MatchCircle score={94} size={56} label="Level" />
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        {[
          ['Total reach', '482K'],
          ['Avg. ER', '6.2%'],
          ['Posts / mo', '14'],
          ['Tier', 'Micro+'],
        ].map(([l, v], i) => (
          <div key={i} style={{ padding: 10, background: 'var(--bg-soft)', borderRadius: 10, textAlign: 'center' }}>
            <div className="cap-label" style={{ fontSize: 9 }}>{l}</div>
            <div className="font-display bold tabular" style={{ fontSize: 16, marginTop: 2 }}>{v}</div>
          </div>
        ))}
      </div>

      <div className="cap-label mt-6 mb-2">Rate card</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[
          ['TikTok video · 30s', 1.8, 'var(--cyan)'],
          ['IG reel · 15s', 1.4, 'var(--pink-hot)'],
          ['IG static · single', 0.6, 'var(--lavender-deep)'],
          ['YouTube short', 1.2, 'var(--coral)'],
        ].map(([l, p, c], i) => (
          <div key={i} className="row items-center justify-between" style={{
            padding: '10px 12px', background: 'var(--bg-soft)', borderRadius: 10
          }}>
            <div className="row items-center gap-8">
              <span style={{ width: 8, height: 8, borderRadius: 999, background: c }} />
              <span className="bold" style={{ fontSize: 13 }}>{l}</span>
            </div>
            <span className="font-display bold tabular" style={{ fontSize: 16 }}>${p}K</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function CreatorAudience() {
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Your audience</div>
          <div className="muted" style={{ fontSize: 12 }}>482K total · verified by 3 platforms</div>
        </div>
      </div>

      <div className="row items-center gap-16">
        <Donut
          data={[
            { label: 'F', value: 78, color: '#FF6FA3' },
            { label: 'M', value: 20, color: '#009CFF' },
            { label: 'Other', value: 2, color: '#FEE960' },
          ]}
          size={140}
          thickness={18}
          centerLabel="Female"
          centerValue="78%"
        />
        <div className="flex-1">
          <div className="cap-label mb-2">Age skew</div>
          <BarChart
            data={[
              { label: '13–17', value: 12, color: 'var(--lavender)' },
              { label: '18–24', value: 48, color: 'var(--pink-hot)' },
              { label: '25–34', value: 28, color: 'var(--cyan)' },
              { label: '35+', value: 12, color: 'var(--mint-deep)' },
            ]}
            height={88}
            labelFmt={(v) => v + '%'}
          />
        </div>
      </div>

      <div className="cap-label mt-6 mb-2">Top countries</div>
      <div className="row gap-12" style={{ flexWrap: 'wrap' }}>
        {[
          ['🇻🇳', 'Vietnam', 88],
          ['🇸🇬', 'Singapore', 5],
          ['🇲🇾', 'Malaysia', 3],
          ['🇵🇭', 'Philippines', 2],
          ['🇰🇷', 'Korea', 1],
        ].map(([f, c, v], i) => (
          <div key={i} className="row items-center gap-6" style={{
            padding: '6px 12px', background: 'var(--bg-soft)', borderRadius: 999,
            fontSize: 12, fontWeight: 600
          }}>
            <span style={{ fontSize: 14 }}>{f}</span>
            {c}
            <span className="tabular bold" style={{ color: 'var(--cyan-dark)' }}>{v}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function EarningsTimeline() {
  // 12-week mini calendar with earnings spread
  const weeks = [
    [200, 0, 0, 0, 350],
    [0, 480, 0, 0, 0],
    [0, 0, 220, 600, 0],
    [800, 0, 0, 0, 0],
    [0, 0, 0, 280, 0],
    [0, 1200, 0, 0, 0],
    [0, 0, 380, 0, 0],
    [600, 0, 0, 220, 0],
    [0, 0, 0, 0, 800],
    [0, 380, 0, 0, 280],
    [0, 0, 480, 0, 0],
    [1200, 0, 0, 600, 0],
  ];
  const max = Math.max(...weeks.flat());

  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Earnings calendar · 12 weeks</div>
          <div className="muted" style={{ fontSize: 12 }}>Each cell = one payout · click to view detail</div>
        </div>
        <div className="row gap-12">
          <Pill variant="mint">$4,720 total Q2</Pill>
          <Pill variant="cyan">17 payouts</Pill>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'auto repeat(12, 1fr)', gap: 6, alignItems: 'center' }}>
        <div />
        {weeks.map((_, i) => (
          <div key={i} className="cap-label text-center" style={{ fontSize: 9 }}>W{i + 1}</div>
        ))}
        {['M','T','W','T','F'].map((d, r) => (
          <React.Fragment key={r}>
            <div className="cap-label text-center" style={{ fontSize: 9 }}>{d}</div>
            {weeks.map((w, c) => {
              const v = w[r];
              const intensity = v / max;
              return (
                <div key={c} title={v ? `$${v}` : 'No payout'}
                  style={{
                    aspectRatio: '1/1',
                    background: v
                      ? `rgba(0,156,255,${0.15 + intensity * 0.85})`
                      : 'var(--bg-soft)',
                    borderRadius: 5,
                    animation: v ? `cellPop .4s ${(c * 5 + r) * 18}ms backwards cubic-bezier(.4,0,.2,1)` : 'none',
                    transform: v ? 'scale(0)' : 'scale(1)',
                    cursor: 'pointer',
                    position: 'relative',
                  }}>
                  {v >= 600 && <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontSize: 8, fontWeight: 800, color: 'white' }}>${(v / 1000).toFixed(1)}K</div>}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
      <style>{`@keyframes cellPop { from { transform: scale(0); } to { transform: scale(1); } }`}</style>
    </div>
  );
}

Object.assign(window, { ScreenCreator });
