// route-draft.jsx — Draft app detail page. Sits between "AI scaffolded a thing" and "live in operations".
// Shows what was built, prompt history, generated screens, and outbound paths
// (continue refining · install locally · publish to marketplace · delete).

function RouteDraftDetail({ navigate, state, setState }) {
  const draftId = state.draftDetail?.id || MY_DRAFTS[0].id;
  const draft = MY_DRAFTS.find((d) => d.id === draftId) || MY_DRAFTS[0];

  const [installing, setInstalling] = React.useState(false);
  const [installed, setInstalled] = React.useState(false);
  const [deleteConfirm, setDeleteConfirm] = React.useState(false);

  const installToShop = () => {
    setInstalling(true);
    setTimeout(() => { setInstalling(false); setInstalled(true); }, 1400);
  };

  const promptHistory = [
    { who: 'You', when: '3d ago', text: draft.prompt, role: 'user' },
    { who: 'AI', when: '3d ago', text: `Scaffolded **${draft.name}** (${draft.direction}). Generated 3 screens, 11 files. Created **v1 (Draft)**.`, role: 'ai', meta: 'v1 · scaffold' },
    { who: 'You', when: '2d ago', text: 'Make the empty state quieter — less iconography.', role: 'user' },
    { who: 'AI', when: '2d ago', text: 'Replaced empty-state illustration with type-only treatment. Created **v2**.', role: 'ai', meta: 'v2 · empty state' },
    { who: 'You', when: '12m ago', text: 'Add a "saved on this device" hint when customer is anon.', role: 'user', attached: 'Empty state · drawer' },
    { who: 'AI', when: '11m ago', text: 'Added subtle hint string. Created **v3 (current)**.', role: 'ai', meta: 'v3 · current' },
  ];

  return (
    <Page>
      <PageHeader
        eyebrow={
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('creator')}>Creator</span>
            <I.chevronRight size={11} />
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('creator/library')}>Drafts</span>
            <I.chevronRight size={11} /> {draft.name}
          </span>
        }
        title={
          <span style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{
              width: 36, height: 36, borderRadius: 9,
              background: draft.color, color: 'white',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 17,
            }}>{draft.initial}</span>
            {draft.name}
            <Badge tone="magic" dot style={{ fontSize: 12 }}>v{draft.versions} · Draft</Badge>
          </span>
        }
        primary={<Btn variant="primary" icon={I.wand} onClick={() => navigate('creator/editor')}>Continue in editor</Btn>}
        secondary={<Btn variant="plain" icon={I.more} />}
      />

      {/* Status banner */}
      <div style={{
        padding: '12px 14px', marginBottom: 16,
        background: 'var(--p-color-bg-fill-magic)', color: 'var(--p-color-text-magic)',
        borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <I.sparkle size={16} />
        <div style={{ flex: 1, fontSize: 13, lineHeight: 1.5 }}>
          <b>v{draft.versions} ready.</b> Built from prompt and {draft.prompts} refinement{draft.prompts===1?'':'s'}. Last edit {draft.lastEdit}.
        </div>
        <Btn size="sm" variant="plain" style={{ color: 'inherit' }} icon={I.layers}>{draft.versions} versions</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16 }}>
        {/* LEFT — screens + prompt + history */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* What this app does */}
          <Card style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <I.sparkle size={13} />
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06 }}>What this app does</div>
              <Badge tone="magic" style={{ fontSize: 10 }}>AI summary</Badge>
            </div>
            <div style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--p-color-text)' }}>{draft.summary}</div>
            <div style={{
              marginTop: 12, padding: 10,
              background: 'var(--p-color-bg-surface-secondary)',
              border: '1px solid var(--p-color-border-secondary)',
              borderRadius: 8,
            }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 4 }}>Original prompt</div>
              <div style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--p-color-text)', fontStyle: 'italic' }}>"{draft.prompt}"</div>
              <div style={{ marginTop: 6, fontSize: 11, color: 'var(--p-color-text-secondary)' }}>
                {draft.createdBy} · direction: <span className="p-mono">{draft.direction}</span>
              </div>
            </div>
          </Card>

          {/* Generated screens */}
          <Card>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--p-color-border-secondary)', display: 'flex', alignItems: 'center' }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Generated screens</div>
              <Badge>{draft.screens}</Badge>
              <div style={{ flex: 1 }} />
              <Btn variant="plain" size="sm" icon={I.external} onClick={() => navigate('creator/editor')}>Preview live</Btn>
            </div>
            <div style={{ padding: 16, display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
              {Array(draft.screens).fill(0).map((_, i) => {
                const labels = ['Drawer · empty state', 'Drawer · with items', 'Saved items account page', 'Admin · widget settings', 'Storefront · floating toggle'];
                return (
                  <div key={i} style={{
                    height: 140, borderRadius: 10, position: 'relative',
                    background: `linear-gradient(135deg, ${draft.color} 0%, oklch(0.96 0.01 280) 100%)`,
                    border: '1px solid var(--p-color-border-secondary)', overflow: 'hidden',
                    cursor: 'pointer',
                  }}>
                    <div className="p-ph" style={{ position: 'absolute', inset: 8, borderRadius: 8 }}>screen {i+1}</div>
                    <div style={{
                      position: 'absolute', bottom: 6, left: 6,
                      background: 'rgba(26,26,26,0.78)', color: 'white',
                      padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 500,
                    }}>{labels[i] || `Screen ${i+1}`}</div>
                  </div>
                );
              })}
            </div>
          </Card>

          {/* Prompt + version history */}
          <Card>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--p-color-border-secondary)', display: 'flex', alignItems: 'center' }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Build history</div>
              <Badge>{draft.prompts + draft.versions} events</Badge>
              <div style={{ flex: 1 }} />
              <Btn variant="plain" size="sm" iconRight={I.chevronRight}>Open chat</Btn>
            </div>
            <div style={{ padding: '6px 0' }}>
              {promptHistory.map((p, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 12, padding: '10px 16px',
                  borderTop: i ? '1px solid var(--p-color-border-secondary)' : 'none',
                }}>
                  <div style={{
                    width: 24, height: 24, borderRadius: 6, flexShrink: 0,
                    background: p.role === 'ai' ? 'linear-gradient(135deg, var(--p-color-bg-fill-magic-active) 0%, #a18bff 100%)' : 'var(--p-color-bg-fill-tertiary)',
                    color: p.role === 'ai' ? 'white' : 'var(--p-color-text)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {p.role === 'ai' ? <I.sparkle size={11} /> : <span style={{ fontSize: 10, fontWeight: 600 }}>You</span>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    {p.attached && (
                      <div style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        background: 'var(--p-color-bg-fill-tertiary)', borderRadius: 5,
                        padding: '2px 6px', marginBottom: 4,
                        fontSize: 11, color: 'var(--p-color-text-secondary)',
                        fontFamily: 'var(--p-font-family-mono)',
                      }}>
                        <I.cursor size={10} /> {p.attached}
                      </div>
                    )}
                    <div style={{ fontSize: 12.5, lineHeight: 1.5 }}
                      dangerouslySetInnerHTML={{ __html: (p.text || '').replace(/\*\*(.+?)\*\*/g, '<b>$1</b>') }} />
                    <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 3, display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span>{p.when}</span>
                      {p.meta && <><span>·</span><span className="p-mono">{p.meta}</span></>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* RIGHT — outbound actions */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Install to my shop */}
          <Card style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <div style={{
                width: 28, height: 28, borderRadius: 7,
                background: 'var(--p-color-bg-fill-success)', color: 'var(--p-color-text-success)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><I.store size={14} /></div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Install on Sarah's Linen</div>
            </div>
            <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', lineHeight: 1.5, marginBottom: 10 }}>
              Activates the app in your Operations sidebar. You can keep editing — every change goes live instantly.
            </div>
            {!draft.installable && (
              <div style={{
                padding: '6px 10px', marginBottom: 10,
                background: 'var(--p-color-bg-fill-warning)', color: 'var(--p-color-text-warning)',
                borderRadius: 6, fontSize: 11.5, lineHeight: 1.4,
              }}>
                ⚠ {draft.blocker}
              </div>
            )}
            {installed ? (
              <Btn icon={I.check} variant="primary" style={{ width: '100%' }} onClick={() => navigate('operations')}>Installed · open in Operations</Btn>
            ) : installing ? (
              <Btn icon={I.spinner} variant="magic" disabled style={{ width: '100%' }}>Installing…</Btn>
            ) : (
              <Btn variant="primary" icon={I.plus} style={{ width: '100%' }} disabled={!draft.installable} onClick={installToShop}>Install</Btn>
            )}
          </Card>

          {/* Publish to marketplace */}
          <Card style={{
            padding: 16,
            background: 'linear-gradient(135deg, var(--p-color-bg-fill-magic) 0%, var(--p-color-bg-surface) 80%)',
            borderColor: 'var(--p-color-border-magic)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <div style={{
                width: 28, height: 28, borderRadius: 7,
                background: 'var(--p-color-bg-fill-magic-active)', color: 'white',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><I.sparkle size={14} /></div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Publish to marketplace</div>
              {draft.publishable && <Badge tone="success" dot>Eligible</Badge>}
            </div>
            <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', lineHeight: 1.5, marginBottom: 10 }}>
              Let other shops install your app. We'll auto-generate a listing — you review before submitting.
            </div>
            {!draft.publishable ? (
              <>
                <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginBottom: 8 }}>
                  Needs: ≥ v2 · installable on your shop first.
                </div>
                <Btn style={{ width: '100%' }} disabled>Not eligible yet</Btn>
              </>
            ) : (
              <Btn variant="magic" icon={I.sparkle} style={{ width: '100%' }} onClick={() => navigate('creator/publish')}>Start publish flow</Btn>
            )}
          </Card>

          {/* Quick stats */}
          <Card style={{ padding: 14 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 10 }}>Draft stats</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {[
                ['Versions', draft.versions],
                ['Prompts', draft.prompts],
                ['Screens', draft.screens],
                ['Files', draft.files],
              ].map(([l, v]) => (
                <div key={l}>
                  <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: -0.3 }}>{v}</div>
                  <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>{l}</div>
                </div>
              ))}
            </div>
          </Card>

          {/* Share + rename + delete */}
          <Card>
            {[
              { label: 'Share preview link', icon: I.external, sub: 'Send a read-only URL to a teammate' },
              { label: 'Rename draft', icon: I.edit, sub: draft.name },
              { label: 'Duplicate as new draft', icon: I.layers, sub: 'Branch off for experiments' },
              { label: 'Delete draft', icon: I.close, sub: 'Removes versions and chat history', critical: true, onClick: () => setDeleteConfirm(true) },
            ].map((row, i) => (
              <div key={row.label} onClick={row.onClick} style={{
                padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
                borderTop: i ? '1px solid var(--p-color-border-secondary)' : 'none',
                cursor: 'pointer',
                color: row.critical ? 'var(--p-color-text-critical)' : 'inherit',
              }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--p-color-bg-surface-hover)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              >
                <row.icon size={13} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{row.label}</div>
                  <div style={{ fontSize: 11, color: row.critical ? 'var(--p-color-text-critical)' : 'var(--p-color-text-secondary)', opacity: 0.7 }}>{row.sub}</div>
                </div>
                <I.chevronRight size={11} />
              </div>
            ))}
          </Card>
        </div>
      </div>

      {deleteConfirm && (
        <Dialog
          title={`Delete ${draft.name}?`}
          icon={I.close}
          onClose={() => setDeleteConfirm(false)}
          footer={
            <>
              <Btn onClick={() => setDeleteConfirm(false)}>Cancel</Btn>
              <Btn variant="critical" onClick={() => { setDeleteConfirm(false); navigate('creator'); }}>Delete draft</Btn>
            </>
          }
        >
          This deletes the draft, all {draft.versions} versions, and {draft.prompts} prompts. You can't undo this.
        </Dialog>
      )}
    </Page>
  );
}

Object.assign(window, { RouteDraftDetail });
