// route-marketplace.jsx — Browse community-published apps. Detail dialog.
// Distinct from the starter Library: marketplace apps are published by other creators (and you).

function RouteMarketplace({ navigate, state, setState }) {
  const [category, setCategory] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [sort, setSort] = React.useState('popular');
  const [openApp, setOpenApp] = React.useState(null);

  const apps = React.useMemo(() => {
    let xs = MARKETPLACE_APPS.filter((a) => !a.pending);
    if (category !== 'all') xs = xs.filter((a) => a.category === category);
    if (query) {
      const q = query.toLowerCase();
      xs = xs.filter((a) => a.name.toLowerCase().includes(q) || a.tagline.toLowerCase().includes(q) || a.dev.toLowerCase().includes(q));
    }
    if (sort === 'popular') xs = [...xs].sort((a,b)=>b.installs-a.installs);
    if (sort === 'rating') xs = [...xs].sort((a,b)=>(b.rating||0)-(a.rating||0));
    if (sort === 'newest') xs = [...xs].sort((a,b)=>(b.badge==='New'?1:0)-(a.badge==='New'?1:0));
    return xs;
  }, [category, query, sort]);

  const featured = MARKETPLACE_APPS.filter((a) => a.badge === 'Staff pick').slice(0, 2);
  const trending = MARKETPLACE_APPS.find((a) => a.badge === 'Trending');

  return (
    <Page>
      <PageHeader
        eyebrow="Distribute"
        title="Marketplace"
        primary={<Btn variant="primary" icon={I.layers} onClick={() => navigate('creator/dashboard')}>My publisher dashboard</Btn>}
        secondary={<Btn icon={I.sparkle} onClick={() => navigate('creator/publish')}>Publish an app</Btn>}
      />

      <div style={{ fontSize: 13, color: 'var(--p-color-text-secondary)', marginTop: -8, marginBottom: 16, maxWidth: 720 }}>
        Apps built by other Ecommos creators. Install with one click — they run inside your admin and storefront just like apps you build yourself. <a style={{ color: 'var(--p-color-text-link)', cursor: 'pointer' }} onClick={() => navigate('creator/publish')}>Publish your own app →</a>
      </div>

      {/* Hero — featured row */}
      {featured.length === 2 && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
          {featured.map((a) => (
            <MarketHeroCard key={a.id} app={a} onClick={() => setOpenApp(a)} />
          ))}
        </div>
      )}

      {/* Search + filters bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '4px 0 14px' }}>
        <div style={{ flex: '0 0 320px' }}>
          <Input placeholder="Search 240+ apps" prefix={<I.search size={14} />} value={query} onChange={setQuery} />
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)' }}>Sort:</div>
        {[['popular','Popular'],['rating','Top-rated'],['newest','Newest']].map(([id,l]) => (
          <Chip key={id} active={sort===id} onClick={() => setSort(id)}>{l}</Chip>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 20 }}>
        {/* Sidebar — categories */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 8 }}>Categories</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {MARKETPLACE_CATEGORIES.map((c) => {
              const count = c.id === 'all' ? MARKETPLACE_APPS.filter(a=>!a.pending).length : MARKETPLACE_APPS.filter(a=>a.category===c.id && !a.pending).length;
              const Icn = c.icon ? I[c.icon] : null;
              const active = category === c.id;
              return (
                <button key={c.id} onClick={() => setCategory(c.id)}
                  style={{
                    appearance: 'none', border: 'none', background: active ? 'var(--p-color-bg-fill-tertiary)' : 'transparent',
                    color: active ? 'var(--p-color-text)' : 'var(--p-color-text-secondary)',
                    fontWeight: active ? 600 : 400, fontSize: 12.5,
                    textAlign: 'left', padding: '6px 10px', borderRadius: 6, cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'inherit',
                  }}>
                  {Icn && <Icn size={13} />}
                  <span style={{ flex: 1 }}>{c.label}</span>
                  <span style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', opacity: active ? 1 : 0.7 }}>{count}</span>
                </button>
              );
            })}
          </div>

          {/* Spotlight on a trending app */}
          {trending && (
            <Card style={{ marginTop: 16, padding: 12 }}>
              <Badge tone="info" dot>Trending</Badge>
              <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>{trending.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', lineHeight: 1.4, marginTop: 2 }}>{trending.tagline}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 8, fontSize: 11, color: 'var(--p-color-text-secondary)' }}>
                <Stars rating={trending.rating} size={10} />
                <span>{trending.rating} · {trending.reviews.toLocaleString()} reviews</span>
              </div>
              <Btn size="sm" style={{ marginTop: 10, width: '100%' }} onClick={() => setOpenApp(trending)}>Open listing</Btn>
            </Card>
          )}
        </div>

        {/* App grid */}
        <div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>
              {category === 'all' ? 'All apps' : category}
            </div>
            <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)' }}>{apps.length} results</div>
          </div>

          {apps.length === 0 ? (
            <Card style={{ padding: 40, textAlign: 'center', color: 'var(--p-color-text-secondary)' }}>
              <I.search size={20} />
              <div style={{ fontSize: 13, marginTop: 8 }}>No apps match "{query}".</div>
              <Btn size="sm" style={{ marginTop: 12 }} onClick={() => { setQuery(''); setCategory('all'); }}>Reset filters</Btn>
            </Card>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
              {apps.map((a) => <MarketAppCard key={a.id} app={a} onClick={() => setOpenApp(a)} />)}
            </div>
          )}
        </div>
      </div>

      {openApp && <MarketAppDialog app={openApp} onClose={() => setOpenApp(null)} navigate={navigate} />}
    </Page>
  );
}

// ─── Hero card (featured / staff pick) ───────────────────────
function MarketHeroCard({ app, onClick }) {
  return (
    <Card onClick={onClick} style={{
      padding: 0, cursor: 'pointer', overflow: 'hidden', position: 'relative',
      background: `linear-gradient(135deg, ${app.color} 0%, oklch(0.94 0.02 280) 60%)`,
      borderColor: 'transparent',
      minHeight: 180,
      display: 'flex',
    }}>
      <div style={{ padding: 20, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
          <Badge style={{ background: 'rgba(255,255,255,0.85)', color: '#1a1a1a' }} dot>{app.badge}</Badge>
          <Badge style={{ background: 'rgba(255,255,255,0.6)', color: 'rgba(0,0,0,0.7)' }}>{app.category}</Badge>
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5, color: '#1a1a1a' }}>{app.name}</div>
        <div style={{ fontSize: 13.5, color: 'rgba(0,0,0,0.7)', lineHeight: 1.45, marginTop: 4, maxWidth: 280 }}>{app.tagline}</div>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'rgba(0,0,0,0.65)' }}>
          <span style={{ fontWeight: 600 }}>{app.dev}</span>
          {app.devVerified && <I.check size={11} />}
          <span>·</span>
          <Stars rating={app.rating} size={10} />
          <span>{app.rating}</span>
          <span>·</span>
          <span>{(app.installs/1000).toFixed(1)}k installs</span>
        </div>
      </div>
      <div style={{
        width: 100, margin: 16, borderRadius: 12,
        background: 'rgba(255,255,255,0.65)', backdropFilter: 'blur(8px)',
        border: '1px solid rgba(255,255,255,0.8)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: app.color, color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, fontSize: 26, letterSpacing: -1,
          boxShadow: '0 6px 16px rgba(0,0,0,0.12)',
        }}>{app.initial}</div>
      </div>
    </Card>
  );
}

// ─── Standard marketplace app card ───────────────────────────
function MarketAppCard({ app, onClick }) {
  return (
    <Card onClick={onClick} style={{ padding: 14, cursor: 'pointer', display: 'flex', flexDirection: 'column', minHeight: 168 }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <div style={{
          width: 44, height: 44, borderRadius: 11,
          background: app.color, color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, fontSize: 19, letterSpacing: -0.5, flexShrink: 0,
        }}>{app.initial}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{app.name}</div>
            {app.badge && app.badge !== 'Pending review' && (
              <Badge tone={app.badge === 'New' ? 'info' : app.badge === 'Trending' ? 'magic' : 'success'} style={{ fontSize: 10 }}>{app.badge}</Badge>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', display: 'flex', alignItems: 'center', gap: 4 }}>
            <span>{app.dev}</span>
            {app.devVerified && <I.check size={10} />}
            {app.devOwn && <Badge tone="magic" style={{ fontSize: 9, minHeight: 16, padding: '0 5px' }}>You</Badge>}
          </div>
        </div>
      </div>

      <div style={{ fontSize: 12.5, color: 'var(--p-color-text)', lineHeight: 1.45, marginTop: 10, minHeight: 36 }}>
        {app.tagline}
      </div>

      <div style={{ flex: 1 }} />

      <div style={{
        marginTop: 12, paddingTop: 10,
        borderTop: '1px solid var(--p-color-border-secondary)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <Stars rating={app.rating} size={11} />
        <span style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
          {app.rating ? `${app.rating} · ${app.reviews.toLocaleString()}` : 'No reviews yet'}
        </span>
        <span style={{ fontSize: 11, color: 'var(--p-color-text-disabled)' }}>·</span>
        <span style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{app.installs.toLocaleString()} installs</span>
        <div style={{ flex: 1 }} />
        <Badge tone={app.price === 'free' ? 'success' : app.price === 'freemium' ? 'info' : 'neutral'}>
          {app.priceLabel}
        </Badge>
      </div>
    </Card>
  );
}

// ─── Stars ─────────────────────────────────────────────────
function Stars({ rating, size = 12 }) {
  if (!rating) return <span style={{ fontSize: size, color: 'var(--p-color-text-disabled)', letterSpacing: 1 }}>· · · · ·</span>;
  const full = Math.floor(rating);
  const half = rating - full >= 0.4;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 1, color: 'oklch(0.78 0.14 80)' }}>
      {[0,1,2,3,4].map((i) => {
        const filled = i < full;
        const halfFilled = i === full && half;
        return (
          <svg key={i} viewBox="0 0 20 20" width={size} height={size}>
            <defs>
              <linearGradient id={`hf-${i}-${size}`}>
                <stop offset="50%" stopColor="oklch(0.78 0.14 80)" />
                <stop offset="50%" stopColor="rgba(0,0,0,0.12)" />
              </linearGradient>
            </defs>
            <path d="M10 1.6l2.6 5.4 6 .9-4.3 4.2 1 6-5.3-2.8-5.3 2.8 1-6-4.3-4.2 6-.9z"
              fill={filled ? 'currentColor' : halfFilled ? `url(#hf-${i}-${size})` : 'rgba(0,0,0,0.12)'}
            />
          </svg>
        );
      })}
    </span>
  );
}

// ─── App detail dialog ─────────────────────────────────────
function MarketAppDialog({ app, onClose, navigate }) {
  const [tab, setTab] = React.useState('overview');
  const [installing, setInstalling] = React.useState(false);
  const [installed, setInstalled] = React.useState(false);

  const install = () => {
    setInstalling(true);
    setTimeout(() => { setInstalling(false); setInstalled(true); }, 1200);
  };

  return (
    <div className="p-backdrop" onClick={onClose}>
      <div className="p-dialog p-fade-in" onClick={(e) => e.stopPropagation()}
        style={{ width: 760, maxWidth: '94%', maxHeight: '90%' }}>
        {/* Header band */}
        <div style={{
          padding: '18px 22px', display: 'flex', alignItems: 'center', gap: 14,
          borderBottom: '1px solid var(--p-color-border)',
          background: `linear-gradient(180deg, color-mix(in oklch, ${app.color} 18%, transparent) 0%, transparent 100%)`,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14,
            background: app.color, color: 'white',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 25, letterSpacing: -0.6, flexShrink: 0,
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
          }}>{app.initial}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.3 }}>{app.name}</div>
              {app.badge && app.badge !== 'Pending review' && (
                <Badge tone={app.badge === 'New' ? 'info' : app.badge === 'Trending' ? 'magic' : 'success'}>{app.badge}</Badge>
              )}
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
              <span style={{ fontWeight: 500 }}>{app.dev}</span>
              {app.devVerified && <I.check size={11} />}
              <span>· {app.devShops} apps published</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, fontSize: 12, color: 'var(--p-color-text-secondary)' }}>
              <Stars rating={app.rating} />
              <span>{app.rating ? `${app.rating} · ${app.reviews.toLocaleString()} reviews` : 'No reviews yet'}</span>
              <span>·</span>
              <span>{app.installs.toLocaleString()} installs</span>
              <span>·</span>
              <span>{app.surfaces.join(' + ')}</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end', flexShrink: 0 }}>
            <Badge tone={app.price === 'free' ? 'success' : app.price === 'freemium' ? 'info' : 'neutral'} style={{ fontSize: 12 }}>{app.priceLabel}</Badge>
            {installed ? (
              <Btn variant="primary" icon={I.check}>Installed</Btn>
            ) : installing ? (
              <Btn variant="magic" icon={I.spinner} disabled>Installing…</Btn>
            ) : (
              <Btn variant="primary" icon={I.plus} onClick={install}>Install on Sarah's Linen</Btn>
            )}
            <Btn variant="plain" size="sm" icon={I.close} onClick={onClose} />
          </div>
        </div>

        {/* Tabs */}
        <Tabs
          tabs={[
            { id: 'overview', label: 'Overview' },
            { id: 'reviews', label: 'Reviews', count: app.reviews },
            { id: 'pricing', label: 'Pricing & support' },
          ]}
          value={tab} onChange={setTab}
        />

        <div className="p-dialog__body p-scroll" style={{ padding: 22 }}>
          {tab === 'overview' && <>
            {/* Screens strip */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 16, overflowX: 'auto', paddingBottom: 6 }} className="p-scroll">
              {app.screens.map((s, i) => (
                <div key={i} style={{
                  flex: '0 0 220px', height: 140, borderRadius: 10, position: 'relative',
                  background: `linear-gradient(135deg, ${app.color} 0%, oklch(0.96 0.01 280) 100%)`,
                  border: '1px solid var(--p-color-border)', overflow: 'hidden',
                }}>
                  <div className="p-ph" style={{ position: 'absolute', inset: 6, borderRadius: 8 }}>screen {i+1}</div>
                  <div style={{
                    position: 'absolute', bottom: 6, left: 6, right: 6,
                    background: 'rgba(26,26,26,0.78)', color: 'white',
                    padding: '4px 8px', borderRadius: 5,
                    fontSize: 10.5, fontWeight: 500,
                  }}>{s}</div>
                </div>
              ))}
            </div>

            <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--p-color-text)', marginBottom: 14 }}>
              {app.description}
            </div>

            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
              {app.tags.map((t) => <Chip key={t}>{t}</Chip>)}
            </div>

            <div style={{
              padding: 12, background: 'var(--p-color-bg-surface-secondary)',
              border: '1px solid var(--p-color-border)', borderRadius: 10,
            }}>
              <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, fontWeight: 600, marginBottom: 6 }}>What this app touches</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 6, fontSize: 12 }}>
                {app.surfaces.includes('admin') && <div>◐ Admin surface — adds a sidebar entry under Operations</div>}
                {app.surfaces.includes('storefront') && <div>◑ Storefront block — drop into theme editor</div>}
                <div>· Reads: products, customers</div>
                <div>· Writes: discounts, customer tags</div>
              </div>
            </div>
          </>}

          {tab === 'reviews' && <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '4px 0 14px', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
              <div>
                <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6 }}>{app.rating || '—'}</div>
                <Stars rating={app.rating} size={13} />
                <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{app.reviews.toLocaleString()} reviews</div>
              </div>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 3 }}>
                {[5,4,3,2,1].map((n) => {
                  const pct = n === 5 ? 78 : n === 4 ? 16 : n === 3 ? 4 : n === 2 ? 1 : 1;
                  return (
                    <div key={n} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--p-color-text-secondary)' }}>
                      <span style={{ width: 12 }}>{n}★</span>
                      <div style={{ flex: 1, height: 6, background: 'var(--p-color-bg-fill-tertiary)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ width: pct + '%', height: '100%', background: 'oklch(0.78 0.14 80)' }} />
                      </div>
                      <span style={{ width: 30, textAlign: 'right' }}>{pct}%</span>
                    </div>
                  );
                })}
              </div>
            </div>
            {SAMPLE_REVIEWS.map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, padding: '14px 0', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
                <Avatar initials={r.initials} />
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontSize: 13, fontWeight: 600 }}>{r.who}</span>
                    <Stars rating={r.rating} size={11} />
                    <span style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>· {r.when}</span>
                  </div>
                  <div style={{ fontSize: 12.5, lineHeight: 1.5, marginTop: 4, color: 'var(--p-color-text)' }}>{r.text}</div>
                </div>
              </div>
            ))}
          </>}

          {tab === 'pricing' && <>
            <Card style={{ padding: 14, marginBottom: 12 }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>{app.priceLabel}</div>
              <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', lineHeight: 1.5 }}>
                Billed monthly through your Ecommos account · cancel anytime. {app.trialDays && `Includes ${app.trialDays}-day free trial.`}
              </div>
            </Card>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Support</div>
            <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', lineHeight: 1.6 }}>
              · Avg first response: 4h<br/>
              · Documentation: <a style={{ color: 'var(--p-color-text-link)' }}>{app.dev.toLowerCase().replace(/[^a-z]/g,'')}.com/docs</a><br/>
              · Status: <span style={{ color: 'var(--p-color-text-success)' }}>● operational</span>
            </div>
          </>}
        </div>

        <div className="p-dialog__foot">
          <Btn onClick={onClose}>Close</Btn>
          {installed ? (
            <Btn variant="primary" onClick={() => { onClose(); navigate('operations'); }}>Open in Operations</Btn>
          ) : (
            <Btn variant="primary" icon={installing ? I.spinner : I.plus} onClick={install} disabled={installing}>
              {installing ? 'Installing…' : `Install · ${app.priceLabel.split(' ·')[0]}`}
            </Btn>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RouteMarketplace, MarketAppCard, MarketHeroCard, MarketAppDialog, Stars });
