// route-new-app.jsx — Sidekick-style AI chat to scaffold a new app.

const STARTER_PROMPTS = [
  { icon: 'wand', t: 'Stack multiple discount codes', d: 'with rules: max stack = 2, exclude sale' },
  { icon: 'store', t: 'Flash sale for VIP customers', d: '1 hour, with countdown timer' },
  { icon: 'sparkle', t: 'Free gift over $80', d: 'auto-add at checkout' },
  { icon: 'layers', t: 'Bundle 3 items, 15% off', d: 'select from collection' },
];

function RouteNewApp({ navigate, state, setState }) {
  const [draft, setDraft] = React.useState('');
  const [messages, setMessages] = React.useState([]); // {role, content, options?, status?}
  const [isThinking, setIsThinking] = React.useState(false);
  const [pickedDirection, setPickedDirection] = React.useState(null);
  const [scaffolding, setScaffolding] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, isThinking]);

  const send = (text) => {
    if (!text.trim()) return;
    const msgs = [...messages, { role: 'user', content: text }];
    setMessages(msgs);
    setDraft('');
    setIsThinking(true);
    setTimeout(() => {
      setIsThinking(false);
      // canned AI response — first round → 3 options
      setMessages([...msgs, {
        role: 'ai',
        content: `Got it. I'll call this app **Discount Stacker**. It can either reuse your existing Coupon Manager UI or start fresh. Here are three directions — pick one and I'll generate v1:`,
        options: [
          { name: 'Lite', tagline: 'Up to 2 stacked codes · no exclusions', detail: 'Reuses your Coupon Manager list view. Fastest path.', time: '~30s', recommended: false },
          { name: 'Pro', tagline: 'Up to 5 stacked codes · exclusion rules', detail: 'Adds rules panel + per-code stack limits. Most flexible.', time: '~1 min', recommended: true },
          { name: 'Custom', tagline: 'Blank scaffold · you define logic via chat', detail: 'Best for novel logic. Slower start, more control.', time: '~2 min', recommended: false },
        ],
      }]);
    }, 1100);
  };

  const pickDirection = (name) => {
    setPickedDirection(name);
    setScaffolding(true);
    setTimeout(() => {
      // navigate to editor with a freshly scaffolded app
      setScaffolding(false);
      setState((s) => ({
        ...s,
        editor: {
          ...s.editor,
          appName: 'Discount Stacker',
          freshScaffold: name,
          chat: [
            { role: 'ai', content: `**Discount Stacker · ${name}** scaffolded. v1 (Draft) created. Try point-click on any element to refine.`, ts: 'Just now' },
          ],
          versions: [
            { id: 'v1', label: `Initial scaffold · ${name}`, ts: 'Just now', live: false, draft: true },
          ],
          liveVersion: null,
        },
      }));
      navigate('creator/editor');
    }, 1800);
  };

  const empty = messages.length === 0;

  return (
    <Page fullWidth>
      <div style={{
        maxWidth: 880, margin: '0 auto', padding: '12px 24px 40px',
        minHeight: 'calc(100% - 0px)', display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
          <Btn variant="plain" size="sm" icon={I.chevronLeft} onClick={() => navigate('creator/library')}>Library</Btn>
          <div style={{ flex: 1 }} />
          <Badge tone="magic" dot>AI Builder · beta</Badge>
        </div>

        {empty && !isThinking ? (
          /* Empty state — big hero composer (Lovable / v0 style) */
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBottom: 60 }}>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <div style={{
                width: 56, height: 56, 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: 14, boxShadow: '0 8px 24px rgba(107,70,193,0.25)',
              }}>
                <I.sparkle size={26} />
              </div>
              <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.8, marginBottom: 8 }}>
                What would you like to build?
              </div>
              <div style={{ fontSize: 15, color: 'var(--p-color-text-secondary)', maxWidth: 480, margin: '0 auto' }}>
                Describe your app. Ecommos drafts the UI &amp; logic, then you refine via chat or point-click.
              </div>
            </div>

            {/* Big input card */}
            <Card style={{ padding: 16, marginBottom: 22 }}>
              <Input
                multiline rows={3} autoFocus
                value={draft}
                onChange={setDraft}
                onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(draft); } }}
                placeholder={'e.g. "An app for customers to stack multiple discount codes at checkout, with rules I can set"'}
              />
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
                <Btn variant="plain" size="sm" icon={I.paperclip}>Attach data</Btn>
                <Btn variant="plain" size="sm" icon={I.store}>Link to product</Btn>
                <div style={{ flex: 1 }} />
                <span style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>
                  <span className="p-mono">⌘↵</span> to send
                </span>
                <Btn variant="magic" icon={I.send} onClick={() => send(draft)} disabled={!draft.trim()}>
                  Generate
                </Btn>
              </div>
            </Card>

            {/* Starter prompts */}
            <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, fontWeight: 500, marginBottom: 8 }}>
              Try a starter
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {STARTER_PROMPTS.map((p) => {
                const Icn = I[p.icon] || I.sparkle;
                return (
                  <Card key={p.t} onClick={() => send(p.t + ' (' + p.d + ')')} style={{ padding: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 8,
                      background: 'var(--p-color-bg-fill-magic)',
                      color: 'var(--p-color-text-magic)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}><Icn size={15} /></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{p.t}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{p.d}</div>
                    </div>
                    <I.chevronRight size={12} />
                  </Card>
                );
              })}
            </div>
          </div>
        ) : (
          /* Conversation mode */
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            <div ref={scrollRef} className="p-scroll" style={{ flex: 1, overflow: 'auto', paddingBottom: 12 }}>
              {messages.map((m, i) => <ChatMessage key={i} m={m} onPickOption={pickDirection} picked={pickedDirection} />)}
              {isThinking && (
                <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 14 }}>
                  <AIAvatar />
                  <div style={{ padding: '8px 12px', background: 'var(--p-color-bg-surface)', border: '1px solid var(--p-color-border)', borderRadius: '4px 14px 14px 14px', display: 'flex', gap: 6, alignItems: 'center' }}>
                    <ThinkingDots />
                    <span style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)' }}>Thinking about your app…</span>
                  </div>
                </div>
              )}
              {scaffolding && (
                <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 14 }}>
                  <AIAvatar />
                  <Card style={{ padding: 14, flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                      <I.spinner /> <b>Scaffolding Discount Stacker · {pickedDirection}…</b>
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', display: 'grid', gap: 4 }}>
                      <div>✓ Wiring schema (codes, stack rules)</div>
                      <div>✓ Generating UI (list + composer)</div>
                      <div className="p-caret">Creating v1 in your Drafts</div>
                    </div>
                  </Card>
                </div>
              )}
            </div>
            {/* composer */}
            <Card style={{ padding: 12 }}>
              <Input
                multiline rows={2}
                value={draft}
                onChange={setDraft}
                onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(draft); } }}
                placeholder="Reply, refine, or ask a question…"
              />
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                <Btn variant="plain" size="sm" icon={I.paperclip} />
                <Btn variant="plain" size="sm" icon={I.store} />
                <div style={{ flex: 1 }} />
                <Btn variant="magic" size="sm" icon={I.send} onClick={() => send(draft)} disabled={!draft.trim() || isThinking || scaffolding}>Send</Btn>
              </div>
            </Card>
          </div>
        )}
      </div>
    </Page>
  );
}

function AIAvatar({ size = 28 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: 'linear-gradient(135deg, var(--p-color-bg-fill-magic-active) 0%, #a18bff 100%)',
      color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}><I.sparkle size={size * 0.55} /></div>
  );
}

function ThinkingDots() {
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {[0, 1, 2].map((i) => (
        <div key={i} style={{
          width: 5, height: 5, borderRadius: '50%',
          background: 'var(--p-color-text-magic)',
          animation: 'p-thinking 1.2s ease-in-out infinite',
          animationDelay: i * 0.18 + 's',
        }} />
      ))}
      <style>{`
        @keyframes p-thinking {
          0%, 80%, 100% { opacity: 0.3; transform: scale(0.85); }
          40% { opacity: 1; transform: scale(1); }
        }
      `}</style>
    </div>
  );
}

function ChatMessage({ m, onPickOption, picked }) {
  if (m.role === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 14 }}>
        <div style={{
          maxWidth: 520, background: 'var(--p-color-bg-inverse)', color: 'white',
          padding: '10px 14px', borderRadius: '14px 14px 4px 14px',
          fontSize: 13.5, lineHeight: 1.5,
        }}>{m.content}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 14 }}>
      <AIAvatar />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          background: 'var(--p-color-bg-surface)', border: '1px solid var(--p-color-border)',
          padding: '10px 14px', borderRadius: '4px 14px 14px 14px',
          fontSize: 13.5, lineHeight: 1.55,
        }} dangerouslySetInnerHTML={{ __html: renderMd(m.content) }} />
        {m.options && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 12 }}>
            {m.options.map((o) => {
              const isPicked = picked === o.name;
              return (
                <Card key={o.name}
                  onClick={() => !picked && onPickOption(o.name)}
                  style={{
                    padding: 12, cursor: picked ? 'default' : 'pointer',
                    borderColor: o.recommended ? 'var(--p-color-border-magic)' : 'var(--p-color-border)',
                    boxShadow: o.recommended ? '0 0 0 1px var(--p-color-border-magic)' : 'var(--p-shadow-100)',
                    opacity: picked && !isPicked ? 0.5 : 1,
                    transition: 'all .15s',
                  }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{o.name}</div>
                    {o.recommended && <Badge tone="magic" style={{ fontSize: 10 }}>recommended</Badge>}
                    {isPicked && <Badge tone="success" dot>picked</Badge>}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', marginBottom: 6, fontWeight: 500 }}>{o.tagline}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', lineHeight: 1.5, minHeight: 32 }}>{o.detail}</div>
                  <div style={{ marginTop: 8, fontSize: 11, color: 'var(--p-color-text-secondary)', display: 'flex', gap: 6, alignItems: 'center' }}>
                    <I.spinner size={11} /> {o.time}
                  </div>
                </Card>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function renderMd(s) {
  return (s || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
    .replace(/`([^`]+)`/g, '<code style="background:var(--p-color-bg-fill-tertiary);padding:1px 5px;border-radius:3px;font-family:var(--p-font-family-mono);font-size:12px;">$1</code>')
    .replace(/\n/g, '<br/>');
}

Object.assign(window, { RouteNewApp, AIAvatar, ThinkingDots, ChatMessage, renderMd });
