/* A3 Studio (chat) — the conversation surface + composer. */
const { Button, Icon, Tag, HGroup, Filler } = window.A3DesignSystem_a87aaf;

function A3Avatar() {
    return (
        <div style={{ width: 26, height: 26, flex: '0 0 auto', borderRadius: 7, background: 'var(--iso-primary-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid var(--iso-primary-200)' }}>
            <svg width="14" height="14" viewBox="0 0 128 128" fill="none">
                <path d="M 63.999985,63.999996 14.844273,35.653537 63.999989,7.3070782 113.15569,35.653537 V 92.346454 L 63.999989,120.69292 14.844273,92.346454 V 54.551177 l 49.155716,28.346457 16.38522,-9.448819 V 54.551177 L 47.61475,35.653537 63.999989,26.204718 96.770448,45.102357 V 82.897634 L 63.999989,101.79528 31.229511,82.897634" stroke="var(--iso-primary-color)" strokeWidth="7.2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
        </div>
    );
}

/* Lightweight **bold** rendering for agent prose. */
function RichText({ text }) {
    const parts = text.split(/(\*\*[^*]+\*\*|`[^`]+`)/g);
    return parts.map((p, i) => {
        if (p.startsWith('**')) return <b key={i}>{p.slice(2, -2)}</b>;
        if (p.startsWith('`')) return <code key={i} style={{ fontFamily: 'var(--font-mono)', fontSize: '.9em', color: 'var(--iso-primary-600)', background: 'var(--iso-surface-100)', padding: '1px 5px', borderRadius: 4 }}>{p.slice(1, -1)}</code>;
        return <React.Fragment key={i}>{p}</React.Fragment>;
    });
}

function UserMsg({ text }) {
    return (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <div style={{ maxWidth: '82%', background: 'var(--iso-surface-100)', borderRadius: 12, borderTopRightRadius: 4, padding: '10px 14px', fontSize: 14, lineHeight: 1.55 }}>
                {text}
            </div>
        </div>
    );
}

function AgentMsg({ text }) {
    return (
        <div style={{ display: 'flex', gap: 10 }}>
            <A3Avatar />
            <div style={{ flex: 1, minWidth: 0, fontSize: 14, lineHeight: 1.6, paddingTop: 3 }}>
                <RichText text={text} />
            </div>
        </div>
    );
}

const TOOL_STATUS = {
    ok: { icon: 'fas fa-check', color: 'var(--p-green-600)' },
    error: { icon: 'fas fa-xmark', color: 'var(--iso-danger-500)' },
    run: { icon: 'fas fa-spinner-third', color: 'var(--p-text-muted-color)' },
};

function ToolCard({ m, onOpenFile }) {
    const st = TOOL_STATUS[m.status] || TOOL_STATUS.ok;
    const isTool = !!m.kind;
    const fileArg = m.kind === 'config' && /^[\w./-]+\.(md|ts|tsx)$/.test(m.args) ? m.args.split('/').pop() : null;
    const canOpen = fileArg && onOpenFile;
    return (
        <div style={{ marginLeft: 36, border: '1px solid var(--iso-surface-200)', borderRadius: 8, overflow: 'hidden', background: 'var(--iso-surface-0)' }}>
            <HGroup gap="1" onClick={canOpen ? () => onOpenFile(fileArg) : undefined}
                style={{ padding: '7px 10px', fontFamily: 'var(--font-mono)', fontSize: 12, cursor: canOpen ? 'pointer' : 'default' }}>
                <Icon name={m.icon} size={12} color={isTool ? 'var(--iso-primary-color)' : 'var(--p-text-muted-color)'} />
                {isTool && <span style={{ fontFamily: 'var(--font-family)', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--iso-primary-color)', background: 'var(--iso-primary-50)', padding: '1px 6px', borderRadius: 4 }}>tool</span>}
                <span style={{ fontWeight: 600 }}>{m.name}</span>
                <span style={{ color: 'var(--p-text-muted-color)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.args}</span>
                <Filler />
                {canOpen && <HGroup gap="0-5" style={{ color: 'var(--iso-primary-color)', fontFamily: 'var(--font-family)', fontSize: 11, fontWeight: 600 }}>
                    <Icon name="far fa-arrow-up-right-from-square" size={10} color="var(--iso-primary-color)" /> Open file
                </HGroup>}
                <Icon name={st.icon} size={11} color={st.color}
                    style={m.status === 'run' ? { animation: 'a3-spin .7s linear infinite' } : null} />
            </HGroup>
            {m.result && (
                <div style={{
                    padding: '6px 10px 7px 30px', fontFamily: 'var(--font-mono)', fontSize: 11.5, lineHeight: 1.5,
                    borderTop: '1px solid var(--iso-surface-100)',
                    color: m.status === 'error' ? 'var(--iso-danger-500)' : 'var(--p-text-muted-color)',
                    background: m.status === 'error' ? 'color-mix(in srgb, var(--p-red-500) 6%, transparent)' : 'var(--iso-surface-50)',
                }}>{m.result}</div>
            )}
        </div>
    );
}

function DiffCard({ m, onOpenFile }) {
    const bg = { add: 'color-mix(in srgb, var(--p-green-500) 12%, transparent)', del: 'color-mix(in srgb, var(--p-red-500) 11%, transparent)', ctx: 'transparent' };
    const fg = { add: 'var(--p-green-700)', del: 'var(--p-red-700)', ctx: 'var(--p-text-muted-color)' };
    const sign = { add: '+', del: '−', ctx: ' ' };
    const stage = m.file.split('/').pop().replace('.stage.ts', '');
    return (
        <div style={{ marginLeft: 36, border: '1px solid var(--iso-surface-200)', borderRadius: 8, overflow: 'hidden' }}>
            <HGroup gap="1"
                onClick={onOpenFile ? () => onOpenFile(stage) : undefined}
                style={{ padding: '6px 10px', background: 'var(--iso-surface-50)', borderBottom: '1px solid var(--iso-surface-200)', fontFamily: 'var(--font-mono)', fontSize: 11.5, cursor: onOpenFile ? 'pointer' : 'default' }}>
                <Icon name="far fa-pen-to-square" size={11} color="var(--iso-primary-color)" />
                <span style={{ fontWeight: 600 }}>{m.file}</span>
                {(m.added != null || m.removed != null) && (
                    <span style={{ color: 'var(--p-text-muted-color)' }}>
                        <span style={{ color: 'var(--p-green-600)' }}>+{m.added ?? 0}</span>{' '}
                        <span style={{ color: 'var(--p-red-600)' }}>−{m.removed ?? 0}</span>
                    </span>
                )}
                <Filler />
                {onOpenFile && <HGroup gap="0-5" style={{ color: 'var(--iso-primary-color)', fontFamily: 'var(--font-family)', fontSize: 11, fontWeight: 600 }}>
                    <Icon name="far fa-arrow-up-right-from-square" size={10} color="var(--iso-primary-color)" /> Open file
                </HGroup>}
            </HGroup>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: '19px', padding: '4px 0', background: 'var(--iso-surface-0)' }}>
                {m.hunks.map((h, i) => (
                    <div key={i} style={{ display: 'flex', background: bg[h.type], color: fg[h.type] }}>
                        <span style={{ width: 18, flex: '0 0 auto', textAlign: 'center', userSelect: 'none', opacity: .8 }}>{sign[h.type]}</span>
                        <span style={{ whiteSpace: 'pre' }}>{h.text || ' '}</span>
                    </div>
                ))}
            </div>
        </div>
    );
}

function CTACard({ m, onGoMode }) {
    return (
        <div style={{ display: 'flex', gap: 10 }}>
            <A3Avatar />
            <div style={{ flex: 1, minWidth: 0, fontSize: 14, lineHeight: 1.6, paddingTop: 3 }}>
                <RichText text={m.text} />
                <div style={{ marginTop: 6 }}>
                    <span onClick={() => onGoMode && onGoMode(m.to)}
                        style={{ color: 'var(--iso-primary-color)', fontWeight: 600, cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }}>
                        {m.link || m.title}
                    </span>
                </div>
            </div>
        </div>
    );
}

function EmptyState({ suggestion, onPick }) {
    if (!suggestion) return null;
    return (
        <div style={{ flex: 1, minHeight: 0, display: 'flex', flexFlow: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px', textAlign: 'center' }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--iso-primary-50)', border: '1px solid var(--iso-primary-200)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
                <svg width="24" height="24" viewBox="0 0 128 128" fill="none">
                    <path d="M 63.999985,63.999996 14.844273,35.653537 63.999989,7.3070782 113.15569,35.653537 V 92.346454 L 63.999989,120.69292 14.844273,92.346454 V 54.551177 l 49.155716,28.346457 16.38522,-9.448819 V 54.551177 L 47.61475,35.653537 63.999989,26.204718 96.770448,45.102357 V 82.897634 L 63.999989,101.79528 31.229511,82.897634" stroke="var(--iso-primary-color)" strokeWidth="7.2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
            </div>
            <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 6 }}>{suggestion.title}</div>
            <div style={{ fontSize: 13.5, color: 'var(--p-text-muted-color)', maxWidth: 420, marginBottom: 24, lineHeight: 1.5 }}>{suggestion.blurb}</div>
            <div style={{ display: 'flex', flexFlow: 'column', gap: 8, width: '100%', maxWidth: 440 }}>
                {suggestion.items.map((it, i) => (
                    <HGroup key={i} gap="1-5" onClick={() => onPick(it.prompt)}
                        style={{ padding: it.desc ? '14px 16px' : '12px 14px', border: '1px solid var(--iso-surface-200)', borderRadius: 10, cursor: 'pointer', background: 'var(--iso-surface-0)', textAlign: 'left', alignItems: it.desc ? 'flex-start' : 'center' }}
                        onMouseEnter={e => { e.currentTarget.style.background = 'var(--iso-surface-50)'; e.currentTarget.style.borderColor = 'var(--iso-primary-300)'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'var(--iso-surface-0)'; e.currentTarget.style.borderColor = 'var(--iso-surface-200)'; }}>
                        <Icon name={it.icon} size={15} color="var(--iso-primary-color)" style={{ width: 18, flex: '0 0 auto', marginTop: it.desc ? 2 : 0 }} />
                        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexFlow: 'column', gap: 4 }}>
                            <span style={{ fontSize: 13.5, fontWeight: it.desc ? 600 : 500 }}>{it.label}</span>
                            {it.desc && <span style={{ fontSize: 12.5, color: 'var(--p-text-muted-color)', lineHeight: 1.55 }}>{it.desc}</span>}
                        </div>
                        <Icon name="far fa-arrow-up" size={12} color="var(--p-text-muted-color)" style={{ transform: 'rotate(45deg)', marginTop: it.desc ? 2 : 0 }} />
                    </HGroup>
                ))}
            </div>
        </div>
    );
}

function Message({ m, onOpenFile, onGoMode }) {
    if (m.role === 'user') return <UserMsg text={m.text} />;
    if (m.role === 'agent') return <AgentMsg text={m.text} />;
    if (m.role === 'tool') return <ToolCard m={m} onOpenFile={onOpenFile} />;
    if (m.role === 'diff') return <DiffCard m={m} onOpenFile={onOpenFile} />;
    if (m.role === 'cta') return <CTACard m={m} onGoMode={onGoMode} />;
    return null;
}

const A3_MODELS = [
    { id: 'claude-opus-4.5', label: 'Claude Opus 4.5', vendor: 'Anthropic' },
    { id: 'claude-sonnet-4.5', label: 'Claude Sonnet 4.5', vendor: 'Anthropic' },
    { id: 'gpt-5.5', label: 'GPT-5.5', vendor: 'OpenAI' },
    { id: 'gpt-5.5-mini', label: 'GPT-5.5 mini', vendor: 'OpenAI' },
    { id: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash', vendor: 'Google' },
    { id: 'gemini-3.5-pro', label: 'Gemini 3.5 Pro', vendor: 'Google' },
];

function ModelSelector({ value, onChange }) {
    const [open, setOpen] = React.useState(false);
    const ref = React.useRef(null);
    const sel = A3_MODELS.find(m => m.id === value) || A3_MODELS[0];
    React.useEffect(() => {
        if (!open) return;
        const onDoc = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', onDoc);
        return () => document.removeEventListener('mousedown', onDoc);
    }, [open]);
    return (
        <div ref={ref} style={{ position: 'relative' }}>
            <HGroup gap="0-5" onClick={() => setOpen(o => !o)}
                style={{ height: 'var(--control-height-sm)', padding: '0 var(--sp1)', borderRadius: 'var(--radius-md)', background: open ? 'var(--iso-surface-200)' : 'var(--iso-surface-100)', cursor: 'pointer', fontSize: 12 }}>
                <Icon name="far fa-microchip" size={11} color="var(--p-text-muted-color)" />
                <span style={{ fontWeight: 600 }}>{sel.label}</span>
                <Icon name="far fa-chevron-down" size={9} color="var(--p-text-muted-color)" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .12s' }} />
            </HGroup>
            {open && (
                <div style={{ position: 'absolute', bottom: 'calc(100% + 5px)', left: 0, minWidth: 220, zIndex: 60, background: 'var(--iso-surface-0)', border: '1px solid var(--iso-surface-200)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-md)', padding: 'var(--sp0-5)' }}>
                    {A3_MODELS.map(m => {
                        const active = m.id === sel.id;
                        return (
                            <HGroup key={m.id} gap="1" onClick={() => { onChange && onChange(m.id); setOpen(false); }}
                                style={{ padding: '7px 10px', borderRadius: 'var(--radius-sm)', cursor: 'pointer', fontSize: 13, background: active ? 'var(--iso-primary-50)' : 'transparent', color: active ? 'var(--iso-primary-color)' : 'var(--p-text-color)', fontWeight: active ? 600 : 400 }}
                                onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--iso-surface-100)'; }}
                                onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
                                <VGroup gap="0" style={{ flex: 1, minWidth: 0 }}>
                                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.label}</span>
                                    <span style={{ fontSize: 11, fontWeight: 400, color: 'var(--p-text-muted-color)' }}>{m.vendor}</span>
                                </VGroup>
                                {active && <Icon name="fas fa-check" size={11} color="var(--iso-primary-color)" />}
                            </HGroup>
                        );
                    })}
                </div>
            )}
        </div>
    );
}

function Composer({ value, onChange, onSend, busy, mode = 'learn', model, onModel }) {
    const isRun = mode === 'run';
    const isConfig = mode === 'config';
    const isOrch = mode === 'orchestrate';
    return (
        <div style={{ padding: '0 24px 18px', flex: '0 0 auto' }}>
            <div style={{ maxWidth: 760, margin: '0 auto', border: '1px solid var(--iso-surface-300)', borderRadius: 14, background: 'var(--iso-surface-0)', boxShadow: 'var(--shadow-sm)', overflow: 'visible' }}>
                <textarea
                    value={value}
                    onChange={e => onChange(e.target.value)}
                    onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onSend(); }}
                    placeholder={isConfig ? 'Describe what your workflows should do…' : isRun ? 'Ask the workflow to do something…' : isOrch ? 'Ask A3 to learn or chain the workflows…' : 'Ask A3 to build, run, or fix a stage…'}
                    rows={2}
                    style={{ width: '100%', resize: 'none', border: 'none', outline: 'none', background: 'transparent', font: 'inherit', fontSize: 14, lineHeight: 1.5, color: 'var(--p-text-color)', padding: '12px 14px 4px' }}
                />
                <HGroup gap="1" style={{ padding: '6px 8px 8px 12px' }}>
                    <ModelSelector value={model} onChange={onModel} />
                    <Filler />
                    <HGroup gap="0-5" style={{ color: 'var(--p-text-muted-color)', fontSize: 12, marginRight: 4 }}>
                        <Icon name="far fa-robot" size={12} /> A3 agent
                    </HGroup>
                    <Button icon={busy ? 'fas fa-spinner-third' : 'fas fa-arrow-up'} iconOnly rounded severity="primary" size="small" onClick={onSend} disabled={busy} />
                </HGroup>
            </div>
            <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--p-text-muted-color)', marginTop: 8 }}>
                {isConfig ? 'The agent edits your project source files' : isRun ? 'Workflows run as tools against their sites' : isOrch ? 'A3 learns every workflow, chaining outputs forward' : 'A3 runs each step against the live site'} · ⌘↵ to send
            </div>
        </div>
    );
}

/* The per-demo landing screen: pick an existing project (→ learning
   orchestrator) or start a new one from scratch (→ project config). */
function EntryChooser({ project, onUseExisting, onStartNew }) {
    const card = ({ icon, title, body, cta, onClick, accent }) => (
        <div onClick={onClick}
            style={{ flex: 1, minWidth: 0, display: 'flex', flexFlow: 'column', gap: 14, padding: '28px 26px', border: '1px solid var(--iso-surface-200)', borderRadius: 16, background: 'var(--iso-surface-0)', cursor: 'pointer', textAlign: 'left', transition: 'border-color .15s, box-shadow .15s, transform .15s' }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--iso-primary-300)'; e.currentTarget.style.boxShadow = '0 12px 30px rgba(2,6,23,.08)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--iso-surface-200)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
            <div style={{ width: 46, height: 46, borderRadius: 12, background: accent ? 'var(--iso-primary-color)' : 'var(--iso-primary-50)', border: accent ? 'none' : '1px solid var(--iso-primary-200)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={icon} size={19} color={accent ? '#fff' : 'var(--iso-primary-color)'} />
            </div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>{title}</div>
            <div style={{ fontSize: 13.5, color: 'var(--p-text-muted-color)', lineHeight: 1.55, flex: 1 }}>{body}</div>
            <HGroup gap="0-5" style={{ color: 'var(--iso-primary-color)', fontWeight: 600, fontSize: 13.5 }}>
                {cta} <Icon name="far fa-arrow-right" size={12} color="var(--iso-primary-color)" />
            </HGroup>
        </div>
    );
    return (
        <div style={{ width: '100%', height: '100%', display: 'flex', flexFlow: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px' }}>
            <div style={{ width: '100%', maxWidth: 720 }}>
                <HGroup gap="1" style={{ marginBottom: 8 }}>
                    <svg width="26" height="26" viewBox="0 0 128 128" fill="none">
                        <path d="M 63.999985,63.999996 14.844273,35.653537 63.999989,7.3070782 113.15569,35.653537 V 92.346454 L 63.999989,120.69292 14.844273,92.346454 V 54.551177 l 49.155716,28.346457 16.38522,-9.448819 V 54.551177 L 47.61475,35.653537 63.999989,26.204718 96.770448,45.102357 V 82.897634 L 63.999989,101.79528 31.229511,82.897634" stroke="var(--iso-primary-color)" strokeWidth="7.2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    <span style={{ fontWeight: 800, fontSize: 18 }}>A3 Automation Studio</span>
                </HGroup>
                <div style={{ fontSize: 26, fontWeight: 800, marginBottom: 6 }}>How do you want to start?</div>
                <div style={{ fontSize: 14, color: 'var(--p-text-muted-color)', marginBottom: 28 }}>
                    Build and run browser automations with an A3 agent.
                </div>
                <div style={{ display: 'flex', gap: 16 }}>
                    {card({ icon: 'far fa-graduation-cap', title: 'Use existing project', body: 'Open the configured project and watch A3 learn every workflow end to end in the learning orchestrator.', cta: 'Open the orchestrator', onClick: onUseExisting })}
                    {card({ icon: 'far fa-wand-magic-sparkles', title: 'Start a new project', body: 'Describe your objective in one go and let A3 scaffold the missions, workflows and schemas from scratch.', cta: 'Configure a project', onClick: onStartNew, accent: true })}
                </div>
            </div>
        </div>
    );
}

window.A3Chat = Object.assign(window.A3Chat || {}, { Message, Composer, A3Avatar, EmptyState, EntryChooser });
