// route-publish.jsx — Multi-step wizard to publish an app to the marketplace.
// Steps: pick source → listing → screens → pricing → review.

const PUBLISH_STEPS = [
  { id: 'source', label: 'Source', subtitle: 'Which app to publish' },
  { id: 'listing', label: 'Listing', subtitle: 'Name, copy, category' },
  { id: 'screens', label: 'Screens', subtitle: 'Auto-captured · edit' },
  { id: 'pricing', label: 'Pricing', subtitle: 'Free, paid, freemium' },
  { id: 'review', label: 'Review', subtitle: 'Submit for review' },
];

function RoutePublish({ navigate, state, setState }) {
  const [step, setStep] = React.useState(0);
  const [submitting, setSubmitting] = React.useState(false);
  const [done, setDone] = React.useState(false);

  // Form state
  const [form, setForm] = React.useState({
    sourceId: MY_DRAFTS.find((d) => d.publishable)?.id || MY_DRAFTS[0].id,
    name: '',
    tagline: '',
    description: '',
    category: 'Conversion',
    tags: ['Wishlist', 'Drawer'],
    pricingModel: 'free',
    price: 9,
    trialDays: 7,
    supportEmail: 'sarah@sarahslinen.com',
    docsUrl: '',
  });
  const update = (patch) => setForm((f) => ({ ...f, ...patch }));

  // Pre-fill name + tagline when source changes
  React.useEffect(() => {
    const src = MY_DRAFTS.find((d) => d.id === form.sourceId);
    if (src && !form.name) update({ name: src.name, tagline: src.summary.split('.')[0] + '.', description: src.summary });
  }, [form.sourceId]);

  const goto = (i) => { if (i >= 0 && i < PUBLISH_STEPS.length) setStep(i); };
  const next = () => goto(step + 1);
  const back = () => goto(step - 1);

  const submit = () => {
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setDone(true);
    }, 1800);
  };

  if (done) return <PublishDoneState navigate={navigate} form={form} />;

  return (
    <Page>
      <PageHeader
        eyebrow={
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('creator/dashboard')}>Publisher dashboard</span>
            <I.chevronRight size={11} /> Publish app
          </span>
        }
        title="Publish to marketplace"
        secondary={<Btn variant="plain" onClick={() => navigate('creator/dashboard')}>Save & exit</Btn>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 20 }}>
        {/* Step rail */}
        <div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {PUBLISH_STEPS.map((s, i) => {
              const isActive = i === step;
              const isDone = i < step;
              return (
                <button key={s.id} onClick={() => goto(i)}
                  disabled={i > step + 1}
                  style={{
                    appearance: 'none', border: 'none', background: 'transparent',
                    textAlign: 'left', cursor: i > step + 1 ? 'not-allowed' : 'pointer',
                    fontFamily: 'inherit',
                    padding: '10px 12px', borderRadius: 8,
                    display: 'flex', alignItems: 'center', gap: 10,
                    background: isActive ? 'var(--p-color-bg-fill-tertiary)' : 'transparent',
                    opacity: i > step + 1 ? 0.5 : 1,
                  }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 11, flexShrink: 0,
                    background: isDone ? 'var(--p-color-bg-fill-success-active)'
                      : isActive ? 'var(--p-color-bg-fill-brand)'
                      : 'var(--p-color-bg-fill-tertiary)',
                    color: isDone || isActive ? 'white' : 'var(--p-color-text-secondary)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 11, fontWeight: 600,
                  }}>
                    {isDone ? <I.check size={12} /> : i + 1}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: isActive ? 600 : 500, color: 'var(--p-color-text)' }}>{s.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>{s.subtitle}</div>
                  </div>
                </button>
              );
            })}
          </div>

          <div style={{
            marginTop: 16, padding: 10,
            background: 'var(--p-color-bg-fill-magic)',
            color: 'var(--p-color-text-magic)',
            borderRadius: 8, fontSize: 11.5, lineHeight: 1.5,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600, marginBottom: 4 }}>
              <I.sparkle size={11} /> AI-assisted listing
            </div>
            We pre-fill copy, tags, and screens from your app. Review carefully — humans read these.
          </div>
        </div>

        {/* Step content */}
        <Card style={{ padding: 0, minHeight: 480, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '18px 22px 6px', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
            <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: -0.3 }}>{PUBLISH_STEPS[step].label}</div>
            <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginTop: 2, marginBottom: 14 }}>{PUBLISH_STEPS[step].subtitle}</div>
          </div>

          <div className="p-scroll" style={{ padding: 22, flex: 1, overflow: 'auto' }}>
            {step === 0 && <StepSource form={form} update={update} />}
            {step === 1 && <StepListing form={form} update={update} />}
            {step === 2 && <StepScreens form={form} update={update} />}
            {step === 3 && <StepPricing form={form} update={update} />}
            {step === 4 && <StepReview form={form} />}
          </div>

          <div style={{
            padding: '12px 22px',
            borderTop: '1px solid var(--p-color-border)',
            background: 'var(--p-color-bg-surface-secondary)',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            {step > 0 && <Btn icon={I.chevronLeft} onClick={back}>Back</Btn>}
            <div style={{ flex: 1 }} />
            <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>Step {step+1} of {PUBLISH_STEPS.length}</div>
            {step < PUBLISH_STEPS.length - 1 ? (
              <Btn variant="primary" iconRight={I.chevronRight} onClick={next}>Continue</Btn>
            ) : (
              <Btn variant="primary" icon={submitting ? I.spinner : I.sparkle} onClick={submit} disabled={submitting}>
                {submitting ? 'Submitting…' : 'Submit for review'}
              </Btn>
            )}
          </div>
        </Card>
      </div>
    </Page>
  );
}

// ─── Step 1: Source ────────────────────────────────────────
function StepSource({ form, update }) {
  return (
    <>
      <div style={{ fontSize: 13, color: 'var(--p-color-text)', lineHeight: 1.55, marginBottom: 14, maxWidth: 580 }}>
        Pick an app from your library to publish. Apps must be at <span className="p-mono">v1+</span> and pass automated checks (lint, scopes, accessibility).
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {MY_DRAFTS.map((d) => {
          const selected = form.sourceId === d.id;
          const blocked = !d.installable;
          return (
            <Card key={d.id} onClick={() => !blocked && update({ sourceId: d.id, name: '' })}
              style={{
                padding: 14, cursor: blocked ? 'not-allowed' : 'pointer',
                borderColor: selected ? 'var(--p-color-border-magic)' : 'var(--p-color-border)',
                boxShadow: selected ? '0 0 0 1px var(--p-color-border-magic)' : 'var(--p-shadow-100)',
                opacity: blocked ? 0.6 : 1,
              }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{
                  width: 38, height: 38, borderRadius: 9,
                  background: d.color, color: 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700, fontSize: 17, flexShrink: 0,
                }}>{d.initial}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600 }}>{d.name}</span>
                    {d.publishable && <Badge tone="success" dot>Eligible</Badge>}
                    {blocked && <Badge tone="warning" dot>Needs work</Badge>}
                    {selected && <Badge tone="magic" dot>Selected</Badge>}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', marginTop: 2, lineHeight: 1.45 }}>
                    {d.summary}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginTop: 6 }}>
                    {d.versions} versions · {d.screens} screens · {d.files} files · {d.lastEdit}
                  </div>
                  {blocked && d.blocker && (
                    <div style={{ fontSize: 11.5, color: 'var(--p-color-text-warning)', marginTop: 4 }}>
                      ⚠ {d.blocker}
                    </div>
                  )}
                </div>
              </div>
            </Card>
          );
        })}
      </div>

      <div style={{ marginTop: 16, fontSize: 12, color: 'var(--p-color-text-secondary)' }}>
        Want to publish something else? <a style={{ color: 'var(--p-color-text-link)', cursor: 'pointer' }}>Browse installed apps →</a>
      </div>
    </>
  );
}

// ─── Step 2: Listing ───────────────────────────────────────
function StepListing({ form, update }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
      <div>
        <Field label="App name" hint="How it appears in the marketplace.">
          <Input value={form.name} onChange={(v) => update({ name: v })} placeholder="Wishlist Drawer" />
        </Field>
        <Field label="Tagline" hint="One short sentence. Shown on cards.">
          <Input value={form.tagline} onChange={(v) => update({ tagline: v })} placeholder="A wishlist drawer that doesn't scream &quot;app&quot;." />
          <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 3, textAlign: 'right' }}>{form.tagline.length} / 80</div>
        </Field>
        <Field label="Full description" hint="What it does, who it's for, why it's different.">
          <Input multiline rows={5} value={form.description} onChange={(v) => update({ description: v })} placeholder="A wishlist drawer designed for taste-led brands. Quiet, type-led, no animation gimmicks…" />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Category">
            <Select value={form.category} onChange={(v) => update({ category: v })}
              options={MARKETPLACE_CATEGORIES.filter((c) => c.id !== 'all').map((c) => c.id)} />
          </Field>
          <Field label="Tags · up to 5">
            <Input value={form.tags.join(', ')} onChange={(v) => update({ tags: v.split(',').map((x)=>x.trim()).filter(Boolean).slice(0,5) })} placeholder="Wishlist, Drawer, Customer account" />
          </Field>
        </div>
      </div>

      {/* Live preview card */}
      <div>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 8 }}>Live preview</div>
        <Card style={{ padding: 14 }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{
              width: 44, height: 44, borderRadius: 11,
              background: MY_DRAFTS.find((d)=>d.id===form.sourceId)?.color || 'var(--p-color-bg-fill-tertiary)', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 19, letterSpacing: -0.5, flexShrink: 0,
            }}>{(form.name || '?')[0]}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{form.name || 'Untitled app'}</div>
              <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', display: 'flex', alignItems: 'center', gap: 4 }}>
                <span>Sarah Nguyễn</span>
                <Badge tone="magic" style={{ fontSize: 9, minHeight: 16, padding: '0 5px' }}>You</Badge>
              </div>
            </div>
          </div>
          <div style={{ fontSize: 12.5, lineHeight: 1.45, marginTop: 10, minHeight: 36, color: form.tagline ? 'var(--p-color-text)' : 'var(--p-color-text-disabled)' }}>
            {form.tagline || 'Your tagline appears here.'}
          </div>
          <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--p-color-border-secondary)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Stars rating={null} />
            <span style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>No reviews yet</span>
            <div style={{ flex: 1 }} />
            <Badge>{form.category}</Badge>
          </div>
        </Card>
        <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 8, lineHeight: 1.5 }}>
          Card preview at marketplace listing size. Hero treatment for staff picks is applied automatically.
        </div>
      </div>
    </div>
  );
}

// ─── Step 3: Screens ───────────────────────────────────────
function StepScreens({ form, update }) {
  const src = MY_DRAFTS.find((d) => d.id === form.sourceId);
  const screens = ['Storefront · Drawer', 'Account page · Saved items', 'Admin · Settings'];
  return (
    <>
      <div style={{ fontSize: 13, color: 'var(--p-color-text)', lineHeight: 1.55, marginBottom: 14, maxWidth: 580 }}>
        We auto-captured {screens.length} screens from your live app. Reorder by drag, rename captions, or upload your own.
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 12 }}>
        {screens.map((s, i) => (
          <Card key={i} style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{
              height: 180, position: 'relative',
              background: `linear-gradient(135deg, ${src?.color || 'oklch(0.85 0.05 280)'} 0%, oklch(0.96 0.01 280) 100%)`,
            }}>
              <div className="p-ph" style={{ position: 'absolute', inset: 12, borderRadius: 8 }}>
                screenshot · 16:10
              </div>
              <div style={{
                position: 'absolute', top: 8, left: 8,
                background: 'rgba(26,26,26,0.78)', color: 'white',
                padding: '2px 7px', borderRadius: 5, fontSize: 10, fontFamily: 'var(--p-font-family-mono)',
              }}>{String(i+1).padStart(2,'0')}</div>
            </div>
            <div style={{ padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Input value={s} onChange={() => {}} />
              <Btn variant="plain" size="sm" icon={I.edit} />
              <Btn variant="plain" size="sm" icon={I.close} />
            </div>
          </Card>
        ))}
        {/* Upload card */}
        <Card style={{
          padding: 20, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          borderStyle: 'dashed', cursor: 'pointer', minHeight: 220,
          color: 'var(--p-color-text-secondary)',
        }}>
          <I.plus size={20} />
          <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6, color: 'var(--p-color-text)' }}>Upload custom screenshot</div>
          <div style={{ fontSize: 11.5, marginTop: 2 }}>PNG / JPG · 1600×1000 recommended</div>
        </Card>
      </div>
      <div style={{
        marginTop: 16, padding: 12,
        background: 'var(--p-color-bg-fill-info)', color: 'var(--p-color-text-info)',
        borderRadius: 8, fontSize: 12, lineHeight: 1.5,
      }}>
        <b>Demo video.</b> Add a 30-60s loop showing the core flow. Optional but increases install rate ~3×. <a style={{ color: 'inherit', textDecoration: 'underline', cursor: 'pointer' }}>Record now →</a>
      </div>
    </>
  );
}

// ─── Step 4: Pricing ───────────────────────────────────────
function StepPricing({ form, update }) {
  const models = [
    { id: 'free', label: 'Free', sub: 'No charge. Builds reputation fast.', icon: 'sparkle' },
    { id: 'paid', label: 'Paid', sub: 'Recurring or one-time charge.', icon: 'layers' },
    { id: 'freemium', label: 'Freemium', sub: 'Free tier + paid plans.', icon: 'wand' },
  ];
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 20 }}>
        {models.map((m) => {
          const sel = form.pricingModel === m.id;
          const Icn = I[m.icon];
          return (
            <Card key={m.id} onClick={() => update({ pricingModel: m.id })}
              style={{
                padding: 14, cursor: 'pointer',
                borderColor: sel ? 'var(--p-color-border-magic)' : 'var(--p-color-border)',
                boxShadow: sel ? '0 0 0 1px var(--p-color-border-magic)' : 'var(--p-shadow-100)',
              }}>
              <div style={{
                width: 32, height: 32, borderRadius: 8,
                background: sel ? 'var(--p-color-bg-fill-magic-active)' : 'var(--p-color-bg-fill-tertiary)',
                color: sel ? 'white' : 'var(--p-color-text-secondary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8,
              }}><Icn size={15} /></div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{m.label}</div>
              <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginTop: 2 }}>{m.sub}</div>
            </Card>
          );
        })}
      </div>

      {form.pricingModel === 'free' && (
        <div style={{
          padding: 14,
          background: 'var(--p-color-bg-fill-success)', color: 'var(--p-color-text-success)',
          borderRadius: 8, fontSize: 12.5, lineHeight: 1.5,
        }}>
          <b>Free apps</b> install with one click — no Stripe handshake. Great for building a foothold. You can upgrade to paid pricing any time after launch.
        </div>
      )}

      {(form.pricingModel === 'paid' || form.pricingModel === 'freemium') && <>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 6 }}>
          <Field label="Monthly price (USD)">
            <Input prefix={<span style={{ color: 'var(--p-color-text-secondary)' }}>$</span>}
              value={String(form.price)} onChange={(v) => update({ price: Number(v.replace(/[^\d.]/g,''))||0 })} suffix={<span style={{ color: 'var(--p-color-text-secondary)', fontSize: 11.5 }}>/mo</span>} />
          </Field>
          <Field label="Free trial">
            <Select value={String(form.trialDays)} onChange={(v) => update({ trialDays: Number(v) })}
              options={['0', '7', '14', '30']} render={(v) => v==='0' ? 'No trial' : v + ' days'} />
          </Field>
          <Field label="Ecommos fee">
            <div className="p-input" style={{ display: 'flex', alignItems: 'center', color: 'var(--p-color-text-secondary)', background: 'var(--p-color-bg-fill-tertiary)' }}>
              <span className="p-mono">15%</span><span style={{ marginLeft: 'auto', fontSize: 11 }}>after $1M/yr</span>
            </div>
          </Field>
        </div>

        {/* Projected earnings */}
        <Card style={{ marginTop: 16, padding: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 8 }}>Projected earnings · based on apps in your category</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
            {[
              ['Low', 12, 'p25 installs/mo'],
              ['Median', 38, 'p50'],
              ['High', 124, 'p90'],
            ].map(([l, count, sub]) => (
              <div key={l} style={{ padding: '10px 0', borderRight: l !== 'High' ? '1px solid var(--p-color-border-secondary)' : 'none' }}>
                <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{l} · {sub}</div>
                <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.3, marginTop: 2 }}>
                  ${Math.round(count * form.price * 0.85).toLocaleString()}<span style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', fontWeight: 500 }}>/mo</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>after fee</div>
              </div>
            ))}
          </div>
        </Card>
      </>}

      <Field label="Payout account" style={{ marginTop: 16 }}>
        <div className="p-input" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Badge tone="success" dot>Stripe Express connected</Badge>
          <span style={{ color: 'var(--p-color-text-secondary)', fontSize: 12 }}>···· 4242 · sarah@sarahslinen.com</span>
          <div style={{ flex: 1 }} />
          <Btn variant="plain" size="sm">Change</Btn>
        </div>
      </Field>
    </>
  );
}

// ─── Step 5: Review ────────────────────────────────────────
function StepReview({ form }) {
  const src = MY_DRAFTS.find((d) => d.id === form.sourceId);
  return (
    <>
      <div style={{ fontSize: 13, color: 'var(--p-color-text)', lineHeight: 1.55, marginBottom: 14 }}>
        We'll run automated checks (lint, scopes, accessibility, performance) and queue your app for human review. Most apps get a verdict within <b>3 business days</b>.
      </div>

      <Card style={{ padding: 14, marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{
            width: 52, height: 52, borderRadius: 13,
            background: src?.color, color: 'white',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 22, flexShrink: 0,
          }}>{(form.name || '?')[0]}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>{form.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginTop: 2 }}>{form.tagline}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
              <Badge>{form.category}</Badge>
              {form.tags.map((t) => <Chip key={t}>{t}</Chip>)}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <Badge tone={form.pricingModel === 'free' ? 'success' : 'magic'} style={{ fontSize: 12 }}>
              {form.pricingModel === 'free' ? 'Free' : form.pricingModel === 'paid' ? `$${form.price}/mo` : `Free + paid plans`}
            </Badge>
            {form.trialDays > 0 && form.pricingModel !== 'free' && (
              <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 3 }}>{form.trialDays}-day trial</div>
            )}
          </div>
        </div>
      </Card>

      <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06 }}>Pre-flight checks</div>
      {[
        ['Code passes lint + type-check', 'success'],
        ['Requested scopes match used APIs', 'success'],
        ['Accessibility · WCAG AA', 'success'],
        ['Has at least 1 screenshot', 'success'],
        ['Listing copy under 600 chars', 'success'],
        ['Refund policy provided', 'warning'],
      ].map(([label, tone]) => (
        <div key={label} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '8px 12px', borderTop: '1px solid var(--p-color-border-secondary)',
        }}>
          <div style={{
            width: 18, height: 18, borderRadius: 9,
            background: tone === 'success' ? 'var(--p-color-bg-fill-success)' : 'var(--p-color-bg-fill-warning)',
            color: tone === 'success' ? 'var(--p-color-text-success)' : 'var(--p-color-text-warning)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{tone === 'success' ? <I.check size={11} /> : '!'}</div>
          <div style={{ flex: 1, fontSize: 12.5 }}>{label}</div>
          {tone === 'warning' && <Btn variant="plain" size="sm">Add</Btn>}
        </div>
      ))}

      <div style={{ marginTop: 18, padding: 10, background: 'var(--p-color-bg-fill-tertiary)', borderRadius: 6, fontSize: 11.5, color: 'var(--p-color-text-secondary)', lineHeight: 1.5 }}>
        By submitting, you agree to the Ecommos Marketplace <a style={{ color: 'var(--p-color-text-link)' }}>Developer Terms</a> and <a style={{ color: 'var(--p-color-text-link)' }}>Quality guidelines</a>.
      </div>
    </>
  );
}

// ─── Done state ────────────────────────────────────────────
function PublishDoneState({ navigate, form }) {
  return (
    <Page>
      <div style={{ maxWidth: 540, margin: '60px auto 0', textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 16,
          background: 'linear-gradient(135deg, var(--p-color-bg-fill-magic-active) 0%, #a18bff 100%)',
          color: 'white', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 16, boxShadow: '0 12px 32px rgba(107,70,193,0.25)',
        }}><I.sparkle size={30} /></div>

        <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, marginBottom: 6 }}>{form.name} is on its way.</div>
        <div style={{ fontSize: 14, color: 'var(--p-color-text-secondary)', lineHeight: 1.55, maxWidth: 420, margin: '0 auto 24px' }}>
          Submitted to the Ecommos Marketplace review queue. We'll email you when it's live — usually within 3 business days.
        </div>

        <Card style={{ padding: 14, marginBottom: 16, textAlign: 'left' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 10 }}>What happens next</div>
          {[
            ['1', 'Automated checks complete (~2 min)', 'done'],
            ['2', 'Listing visible at sarahslinen.com/apps/preview', 'done'],
            ['3', 'Human review by Ecommos quality team', 'pending'],
            ['4', 'Go-live & first install notifications', 'pending'],
          ].map(([n, l, s]) => (
            <div key={n} style={{ display: 'flex', gap: 10, padding: '6px 0', alignItems: 'center' }}>
              <div style={{
                width: 22, height: 22, borderRadius: 11, flexShrink: 0,
                background: s==='done' ? 'var(--p-color-bg-fill-success)' : 'var(--p-color-bg-fill-tertiary)',
                color: s==='done' ? 'var(--p-color-text-success)' : 'var(--p-color-text-secondary)',
                fontSize: 11, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{s==='done' ? <I.check size={11} /> : n}</div>
              <div style={{ flex: 1, fontSize: 12.5, color: s==='done' ? 'var(--p-color-text)' : 'var(--p-color-text-secondary)' }}>{l}</div>
              {s==='done' && <span style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>just now</span>}
            </div>
          ))}
        </Card>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
          <Btn onClick={() => navigate('creator/dashboard')}>Back to dashboard</Btn>
          <Btn variant="primary" icon={I.external} onClick={() => navigate('marketplace')}>View marketplace</Btn>
        </div>
      </div>
    </Page>
  );
}

// ─── Field + Select primitives (local to this wizard) ──────
function Field({ label, hint, children, style }) {
  return (
    <div style={{ marginBottom: 14, ...style }}>
      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 500, marginBottom: 4 }}>{label}</label>
      {hint && <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginBottom: 6 }}>{hint}</div>}
      {children}
    </div>
  );
}

function Select({ value, onChange, options, render }) {
  return (
    <div className="p-input" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 0 }}>
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{
        width: '100%', appearance: 'none', border: 'none', outline: 'none', background: 'transparent',
        font: 'inherit', color: 'inherit', padding: '6px 10px', cursor: 'pointer',
      }}>
        {options.map((o) => <option key={o} value={o}>{render ? render(o) : o}</option>)}
      </select>
      <I.chevronDown size={12} style={{ marginRight: 10, pointerEvents: 'none' }} />
    </div>
  );
}

Object.assign(window, { RoutePublish, PublishDoneState, Field, Select });
