// route-dashboard.jsx — Publisher dashboard for apps the user has shipped to marketplace.
// Shows installs, earnings, ratings, reviews, recent activity, per-app detail.

function RoutePublisherDashboard({ navigate, state, setState }) {
  const [range, setRange] = React.useState('30d');
  const [focusedAppId, setFocusedAppId] = React.useState(MY_PUBLISHED[0]?.id);
  const focused = MY_PUBLISHED.find((a) => a.id === focusedAppId) || MY_PUBLISHED[0];

  // Aggregate KPIs
  const totals = MY_PUBLISHED.reduce((acc, a) => ({
    installs: acc.installs + a.installs,
    reviews: acc.reviews + a.reviews,
    ratingSum: acc.ratingSum + (a.rating ? a.rating * a.reviews : 0),
    ratingN: acc.ratingN + (a.rating ? a.reviews : 0),
    earnings: acc.earnings + a.earnings,
  }), { installs: 0, reviews: 0, ratingSum: 0, ratingN: 0, earnings: 0 });
  const avgRating = totals.ratingN ? (totals.ratingSum / totals.ratingN).toFixed(1) : '—';

  return (
    <Page>
      <PageHeader
        eyebrow={
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('marketplace')}>Marketplace</span>
            <I.chevronRight size={11} /> Publisher dashboard
          </span>
        }
        title="Publisher dashboard"
        primary={<Btn variant="primary" icon={I.sparkle} onClick={() => navigate('creator/publish')}>Publish a new app</Btn>}
        secondary={
          <div style={{ display: 'inline-flex', background: 'var(--p-color-bg-fill-tertiary)', borderRadius: 8, padding: 3, gap: 2 }}>
            {[['7d','7 days'],['30d','30 days'],['90d','90 days'],['all','All time']].map(([id,l]) => (
              <button key={id} onClick={() => setRange(id)} style={{
                appearance: 'none', border: 'none', cursor: 'pointer',
                padding: '4px 10px', borderRadius: 6,
                fontFamily: 'inherit', fontSize: 12, fontWeight: range===id ? 600 : 500,
                background: range===id ? 'var(--p-color-bg-surface)' : 'transparent',
                color: range===id ? 'var(--p-color-text)' : 'var(--p-color-text-secondary)',
                boxShadow: range===id ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
              }}>{l}</button>
            ))}
          </div>
        }
      />

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginBottom: 16 }}>
        <KpiTile label="Total installs" value={totals.installs.toLocaleString()} sub="+34 this period" tone="success" />
        <KpiTile label="Earnings (period)" value={'$' + (range==='all' ? 0 : 0).toFixed(2)} sub="Free apps only" mono />
        <KpiTile label="Average rating" value={avgRating} sub={`${totals.reviews} reviews total`} stars={parseFloat(avgRating) || null} />
        <KpiTile label="Published apps" value={String(MY_PUBLISHED.length)} sub="1 live · 1 in review" />
      </div>

      {/* Earnings + Installs chart */}
      <Card style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Installs over time</div>
          <Badge>{range === '7d' ? 'last 7 days' : range === '30d' ? 'last 14 days' : 'last 14 weeks'}</Badge>
          <div style={{ flex: 1 }} />
          <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: 'var(--p-color-bg-fill-magic-active)' }} />
              Curtain Call
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: 'var(--p-color-bg-fill-tertiary)', border: '1px dashed var(--p-color-border-hover)' }} />
              Frostline (pending)
            </span>
          </div>
        </div>
        <InstallsChart data={focused.sparkline || []} />
      </Card>

      {/* Apps + activity grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
        {/* Apps list with details */}
        <Card>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--p-color-border)', display: 'flex', alignItems: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Your published apps</div>
            <div style={{ flex: 1 }} />
            <Btn variant="plain" size="sm" iconRight={I.chevronRight} onClick={() => navigate('marketplace')}>View in marketplace</Btn>
          </div>
          {MY_PUBLISHED.map((a) => {
            const m = MARKETPLACE_APPS.find((x) => x.id === a.id);
            const active = a.id === focusedAppId;
            return (
              <div key={a.id} onClick={() => setFocusedAppId(a.id)} style={{
                padding: '14px 16px', borderTop: '1px solid var(--p-color-border-secondary)',
                cursor: 'pointer',
                background: active ? 'var(--p-color-bg-fill-tertiary)' : 'transparent',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 9,
                    background: m?.color || 'var(--p-color-bg-fill-tertiary)', color: 'white',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 700, fontSize: 16, flexShrink: 0,
                  }}>{a.name[0]}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 600 }}>{a.name}</span>
                      {a.status === 'live' && <Badge tone="success" dot>Live</Badge>}
                      {a.status === 'in-review' && <Badge tone="info" dot>In review</Badge>}
                      {a.status === 'draft' && <Badge tone="magic" dot>Draft</Badge>}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
                      {a.publishedAt} · {a.price}
                    </div>
                  </div>
                  {a.sparkline && <MiniSpark data={a.sparkline} />}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginTop: 12 }}>
                  <Stat label="Installs" value={a.installs.toLocaleString()} sub={a.installsTrend} />
                  <Stat label="Earnings" value={'$' + a.earnings.toFixed(2)} sub={a.earningsLabel} />
                  <Stat label="Rating" value={a.rating || '—'} sub={a.reviews ? `${a.reviews} reviews` : 'No reviews'} />
                  <Stat label="Conversion" value={a.installs ? '38%' : '—'} sub="Listing → install" />
                </div>

                {a.note && (
                  <div style={{
                    marginTop: 10, padding: '8px 10px',
                    background: 'var(--p-color-bg-fill-info)', color: 'var(--p-color-text-info)',
                    borderRadius: 6, fontSize: 11.5, lineHeight: 1.5,
                    display: 'flex', alignItems: 'flex-start', gap: 6,
                  }}>
                    <I.spinner size={11} />
                    <span>{a.note}</span>
                  </div>
                )}

                {active && (
                  <div style={{ marginTop: 12, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    <Btn size="sm" icon={I.external}>View listing</Btn>
                    <Btn size="sm" icon={I.edit}>Edit listing</Btn>
                    <Btn size="sm" icon={I.layers} onClick={() => navigate('creator/editor')}>Open in editor</Btn>
                    {a.status === 'live' && <Btn size="sm" variant="plain" icon={I.pause}>Unpublish</Btn>}
                  </div>
                )}
              </div>
            );
          })}

          {/* Empty CTA */}
          <div style={{ padding: 14, borderTop: '1px solid var(--p-color-border-secondary)', display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              border: '1px dashed var(--p-color-border-hover)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--p-color-text-secondary)',
            }}><I.plus size={14} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>Got another app ready to share?</div>
              <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{MY_DRAFTS.filter(d=>d.publishable).length} draft{MY_DRAFTS.filter(d=>d.publishable).length===1?'':'s'} eligible to publish</div>
            </div>
            <Btn variant="magic" size="sm" icon={I.sparkle} onClick={() => navigate('creator/publish')}>Publish</Btn>
          </div>
        </Card>

        {/* Activity feed + Payouts */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--p-color-border)', fontSize: 13, fontWeight: 600 }}>
              Recent activity
            </div>
            {PUBLISHER_ACTIVITY.map((a, i) => {
              const Icn = I[a.icon] || I.bell;
              return (
                <div key={i} style={{
                  padding: '11px 16px', borderTop: '1px solid var(--p-color-border-secondary)',
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                }}>
                  <div style={{
                    width: 24, height: 24, borderRadius: 6, flexShrink: 0,
                    background: a.tone === 'success' ? 'var(--p-color-bg-fill-success)'
                      : a.tone === 'magic' ? 'var(--p-color-bg-fill-magic)'
                      : a.tone === 'info' ? 'var(--p-color-bg-fill-info)'
                      : 'var(--p-color-bg-fill-tertiary)',
                    color: a.tone === 'success' ? 'var(--p-color-text-success)'
                      : a.tone === 'magic' ? 'var(--p-color-text-magic)'
                      : a.tone === 'info' ? 'var(--p-color-text-info)'
                      : 'var(--p-color-text-secondary)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}><Icn size={12} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, lineHeight: 1.45 }}>
                      {a.type === 'install' && <><b>{a.who}</b> installed <b>{a.app}</b></>}
                      {a.type === 'review' && <><b>{a.who}</b> left a review on <b>{a.app}</b></>}
                      {a.type === 'review-status' && <><b>{a.app}</b> · <span style={{ color: 'var(--p-color-text-secondary)' }}>{a.detail}</span></>}
                      {a.type === 'payout' && <>{a.detail}</>}
                    </div>
                    {a.detail && a.type === 'review' && (
                      <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginTop: 2, lineHeight: 1.45 }}>{a.detail}</div>
                    )}
                    <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 2 }}>{a.when}</div>
                  </div>
                </div>
              );
            })}
          </Card>

          <Card style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <I.layers size={14} />
              <div style={{ fontSize: 13, fontWeight: 600 }}>Payouts</div>
              <div style={{ flex: 1 }} />
              <Badge>Stripe Express</Badge>
            </div>
            <div style={{ display: 'flex', gap: 14, marginTop: 8 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04 }}>Pending</div>
                <div style={{ fontSize: 20, fontWeight: 700, marginTop: 2 }}>$0.00</div>
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>Next: Jun 1</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04 }}>Lifetime</div>
                <div style={{ fontSize: 20, fontWeight: 700, marginTop: 2 }}>$0.00</div>
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>Free apps only</div>
              </div>
            </div>
            <div style={{
              marginTop: 12, padding: 10,
              background: 'var(--p-color-bg-fill-magic)',
              color: 'var(--p-color-text-magic)',
              borderRadius: 8, fontSize: 11.5, lineHeight: 1.5,
            }}>
              <b>Tip:</b> Re-publishing Curtain Call as a $9/mo Pro tier could unlock $400-700/mo at your current install rate. <a style={{ color: 'inherit', textDecoration: 'underline', cursor: 'pointer' }} onClick={() => navigate('creator/publish')}>Try paid pricing →</a>
            </div>
          </Card>
        </div>
      </div>
    </Page>
  );
}

// ─── Sub-components ─────────────────────────────────────────
function KpiTile({ label, value, sub, tone, mono, stars }) {
  return (
    <Card padding>
      <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
        <div className={mono ? 'p-mono' : ''} style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.4 }}>{value}</div>
        {stars && <Stars rating={stars} size={11} />}
      </div>
      <div style={{ fontSize: 12, color: tone === 'success' ? 'var(--p-color-text-success)' : 'var(--p-color-text-secondary)', marginTop: 2 }}>{sub}</div>
    </Card>
  );
}

function Stat({ label, value, sub }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04 }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 700, marginTop: 1 }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>{sub}</div>
    </div>
  );
}

function MiniSpark({ data }) {
  if (!data || !data.length) return null;
  const W = 80, H = 28, max = Math.max(...data, 1);
  const pts = data.map((v, i) => `${(i/(data.length-1))*W},${H - (v/max)*H}`).join(' ');
  return (
    <svg width={W} height={H} style={{ flexShrink: 0 }}>
      <polyline points={pts} fill="none" stroke="var(--p-color-bg-fill-magic-active)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
      <polyline points={`0,${H} ${pts} ${W},${H}`} fill="var(--p-color-bg-fill-magic)" opacity="0.4" />
    </svg>
  );
}

function InstallsChart({ data }) {
  // Build a 14-bar chart. If no data, show ghost bars.
  const bars = data && data.length ? data : Array(14).fill(0);
  const max = Math.max(...bars, 1);
  const W = 720, H = 180, barW = (W - 30) / bars.length;
  const labels = ['May 9', 'May 12', 'May 15', 'May 18', 'May 21', 'Today'];

  return (
    <div style={{ position: 'relative' }}>
      <svg viewBox={`0 0 ${W} ${H + 24}`} width="100%" height={H + 24}>
        {/* gridlines */}
        {[0, 0.25, 0.5, 0.75, 1].map((p) => (
          <line key={p} x1="30" x2={W} y1={H - p*H + 6} y2={H - p*H + 6}
            stroke="var(--p-color-border-secondary)" strokeDasharray={p===0 ? 'none' : '2 4'} />
        ))}
        {/* y-axis labels */}
        {[0, 0.5, 1].map((p) => (
          <text key={p} x="0" y={H - p*H + 10} fontSize="9.5" fill="var(--p-color-text-secondary)" fontFamily="var(--p-font-family-mono)">
            {Math.round(max * p)}
          </text>
        ))}
        {/* bars */}
        {bars.map((v, i) => {
          const h = (v / max) * H;
          return (
            <rect key={i} x={30 + i*barW + 3} y={H - h + 6} width={barW - 6} height={h}
              fill="var(--p-color-bg-fill-magic-active)" rx="2">
              <title>{`Day ${i+1}: ${v} install${v===1?'':'s'}`}</title>
            </rect>
          );
        })}
        {/* x-axis labels */}
        {labels.map((l, i) => (
          <text key={i} x={30 + (i / (labels.length-1)) * (W - 30)} y={H + 20}
            fontSize="10" fill="var(--p-color-text-secondary)" textAnchor={i===0?'start':i===labels.length-1?'end':'middle'}>
            {l}
          </text>
        ))}
      </svg>
    </div>
  );
}

Object.assign(window, { RoutePublisherDashboard, KpiTile, Stat, MiniSpark, InstallsChart });
