const { useState, useRef, useEffect } = React;

const API_BASE = window.location.origin;

function ConfidenceBar({ label, score, evidence }) {
    const color = score >= 85 ? 'bg-green-500' : score >= 70 ? 'bg-yellow-500' : 'bg-red-500';
    return (
        <div className="mb-2">
            <div className="flex justify-between text-xs mb-1">
                <span className="text-gray-400">{label}</span>
                <span className="font-mono">{score}/100</span>
            </div>
            <div className="w-full bg-hydra-card rounded-full h-2">
                <div className={`confidence-bar ${color} h-2 rounded-full`} style={{ width: `${score}%` }} />
            </div>
            {evidence && <p className="text-xs text-gray-500 mt-0.5">{evidence}</p>}
        </div>
    );
}

function Spinner() {
    return (
        <div className="flex flex-col items-center justify-center py-12">
            <div className="spinner mb-4" />
            <style>{`
                .spinner {
                    width: 40px; height: 40px;
                    border: 3px solid rgba(99,102,241,0.2);
                    border-top-color: #6366f1;
                    border-radius: 50%;
                    animation: spin 0.8s linear infinite;
                }
                @keyframes spin { to { transform: rotate(360deg); } }
            `}</style>
        </div>
    );
}

function ModelBadge({ model, status, latency }) {
    const colors = {
        ok: 'bg-green-900/50 text-green-400 border-green-800',
        refused: 'bg-yellow-900/50 text-yellow-400 border-yellow-800',
        error: 'bg-red-900/50 text-red-400 border-red-800',
        timeout: 'bg-red-900/50 text-red-400 border-red-800',
    };
    return (
        <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-xs font-mono ${colors[status] || colors.ok}`}>
            {model}
            {latency > 0 && <span className="text-gray-500">{Math.round(latency)}ms</span>}
        </span>
    );
}

function App() {
    const [query, setQuery] = useState('');
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState(null);
    const [history, setHistory] = useState([]);
    const [showWork, setShowWork] = useState(false);
    const [forceSwarm, setForceSwarm] = useState(false);
    const [elapsed, setElapsed] = useState(0);
    const [error, setError] = useState(null);
    const inputRef = useRef(null);
    const timerRef = useRef(null);

    useEffect(() => { inputRef.current?.focus(); }, [loading]);

    useEffect(() => {
        if (loading) {
            setElapsed(0);
            timerRef.current = setInterval(() => setElapsed(prev => prev + 0.1), 100);
        } else {
            clearInterval(timerRef.current);
        }
        return () => clearInterval(timerRef.current);
    }, [loading]);

    async function handleSubmit(e) {
        e.preventDefault();
        if (!query.trim() || loading) return;

        setLoading(true);
        setResult(null);
        setError(null);

        try {
            const resp = await fetch(`${API_BASE}/query/sync`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    query: query.trim(),
                    force_swarm: forceSwarm,
                    max_rounds: 3,
                    show_work: showWork,
                }),
            });

            if (!resp.ok) {
                throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
            }

            const data = await resp.json();
            setResult(data);
            setHistory(prev => [{ query: query.trim(), result: data, time: new Date() }, ...prev]);
        } catch (err) {
            setError(err.message);
        }

        setLoading(false);
    }

    const conf = result?.confidence || {};

    return (
        <div className="max-w-4xl mx-auto px-4 py-8">
            {/* Header */}
            <div className="text-center mb-8">
                <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
                    HYDRA
                </h1>
                <p className="text-gray-500 text-sm mt-1">Multi-model AI orchestrator</p>
            </div>

            {/* Input */}
            <form onSubmit={handleSubmit} className="mb-6">
                <div className="flex gap-2">
                    <input
                        ref={inputRef}
                        type="text"
                        value={query}
                        onChange={e => setQuery(e.target.value)}
                        placeholder="Ask anything..."
                        disabled={loading}
                        className="flex-1 bg-hydra-card border border-hydra-border rounded-lg px-4 py-3 text-gray-200 placeholder-gray-600 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                    />
                    <button
                        type="submit"
                        disabled={loading || !query.trim()}
                        className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-800 disabled:text-gray-600 rounded-lg font-medium transition-colors"
                    >
                        {loading ? 'Thinking...' : 'Ask'}
                    </button>
                </div>
                <div className="flex gap-4 mt-2 text-xs text-gray-500">
                    <label className="flex items-center gap-1 cursor-pointer">
                        <input type="checkbox" checked={forceSwarm} onChange={e => setForceSwarm(e.target.checked)} className="rounded" />
                        Force swarm
                    </label>
                    <label className="flex items-center gap-1 cursor-pointer">
                        <input type="checkbox" checked={showWork} onChange={e => setShowWork(e.target.checked)} className="rounded" />
                        Show individual outputs
                    </label>
                </div>
            </form>

            {/* Loading spinner */}
            {loading && (
                <div className="bg-hydra-card border border-hydra-border rounded-lg p-4 mb-6">
                    <div className="flex justify-between items-center mb-2">
                        <span className="text-xs font-mono text-indigo-400">{elapsed.toFixed(1)}s elapsed</span>
                        <span className="text-xs font-mono text-gray-600">{Math.max(0, 90 - elapsed).toFixed(0)}s max</span>
                    </div>
                    <div className="w-full bg-hydra-border rounded-full h-1 mb-3">
                        <div className="bg-indigo-500 h-1 rounded-full transition-all" style={{ width: `${Math.min(100, (elapsed / 90) * 100)}%` }} />
                    </div>
                    <Spinner />
                    <p className="text-center text-sm text-gray-500">Querying models{forceSwarm ? ' in swarm mode' : ''}...</p>
                </div>
            )}

            {/* Error */}
            {error && !result && (
                <div className="bg-red-900/20 border border-red-800 rounded-lg p-4 mb-6">
                    <p className="text-red-400 text-sm">{error}</p>
                </div>
            )}

            {/* Result */}
            {result && (
                <div className="space-y-4">
                    {/* Answer */}
                    <div className="bg-hydra-card border border-hydra-border rounded-lg p-6 glow">
                        <pre className="text-gray-200 leading-relaxed whitespace-pre-wrap">{result.answer}</pre>
                    </div>

                    {/* Confidence */}
                    {conf.overall !== undefined && (
                        <div className="bg-hydra-card border border-hydra-border rounded-lg p-4">
                            <div className="flex items-center justify-between mb-3">
                                <h3 className="text-sm font-medium text-gray-400">Confidence</h3>
                                <span className={`text-2xl font-bold font-mono ${
                                    conf.overall >= 85 ? 'text-green-400' : conf.overall >= 70 ? 'text-yellow-400' : 'text-red-400'
                                }`}>{conf.overall}</span>
                            </div>
                            {conf.consensus && <ConfidenceBar label="Consensus" score={conf.consensus.score} evidence={conf.consensus.evidence} />}
                            {conf.coverage && <ConfidenceBar label="Coverage" score={conf.coverage.score} evidence={conf.coverage.evidence} />}
                            {conf.verification && <ConfidenceBar label="Verification" score={conf.verification.score} evidence={conf.verification.evidence} />}
                            {conf.coherence && <ConfidenceBar label="Coherence" score={conf.coherence.score} evidence={conf.coherence.evidence} />}
                            {conf.mechanical_overrides_applied && (
                                <p className="text-xs text-yellow-500 mt-2">Mechanical overrides applied</p>
                            )}
                        </div>
                    )}

                    {/* Outliers */}
                    {result.outliers?.length > 0 && (
                        <div className="bg-hydra-card border border-yellow-900/50 rounded-lg p-4">
                            <h3 className="text-sm font-medium text-yellow-400 mb-2">Outliers</h3>
                            {result.outliers.map((o, i) => <p key={i} className="text-sm text-gray-300 mb-1">{o}</p>)}
                        </div>
                    )}

                    {/* Contradictions */}
                    {result.contradictions?.length > 0 && (
                        <div className="bg-hydra-card border border-red-900/50 rounded-lg p-4">
                            <h3 className="text-sm font-medium text-red-400 mb-2">Contradictions</h3>
                            {result.contradictions.map((c, i) => <p key={i} className="text-sm text-gray-300 mb-1">{c}</p>)}
                        </div>
                    )}

                    {/* Meta */}
                    <div className="flex flex-wrap gap-4 text-xs text-gray-500">
                        <span>Rounds: {result.rounds}</span>
                        <span>Time: {result.wall_time_seconds}s</span>
                        <span>Cost: ${result.estimated_cost_usd?.toFixed(4)}</span>
                        <span>Budget: ${result.budget_remaining_usd?.toFixed(2)} ({result.budget_status})</span>
                        <span>Swarm: {result.was_swarm ? 'yes' : 'no'}</span>
                        {result.terminated_early && <span className="text-yellow-500">Terminated early</span>}
                    </div>

                    {/* Models used */}
                    {result.models_used?.length > 0 && (
                        <div className="flex flex-wrap gap-2">
                            {result.models_used.map((m, i) => <ModelBadge key={i} model={m} status="ok" latency={0} />)}
                            {result.models_refused?.map((m, i) => <ModelBadge key={`r${i}`} model={m} status="refused" latency={0} />)}
                            {result.models_failed?.map((m, i) => <ModelBadge key={`f${i}`} model={m.model} status="error" latency={0} />)}
                        </div>
                    )}

                    {/* Individual outputs */}
                    {showWork && result.individual_outputs?.length > 0 && (
                        <details className="bg-hydra-card border border-hydra-border rounded-lg">
                            <summary className="p-4 cursor-pointer text-sm text-gray-400 hover:text-gray-200">
                                Individual model outputs ({result.individual_outputs.length})
                            </summary>
                            <div className="px-4 pb-4 space-y-3">
                                {result.individual_outputs.map((o, i) => (
                                    <div key={i} className="border border-hydra-border rounded p-3">
                                        <div className="flex justify-between mb-2">
                                            <ModelBadge model={o.model} status={o.status} latency={o.latency_ms} />
                                        </div>
                                        <pre className="text-xs text-gray-400 max-h-48 overflow-y-auto">{o.output || `[${o.status}]`}</pre>
                                    </div>
                                ))}
                            </div>
                        </details>
                    )}

                    {/* Remaining gaps */}
                    {result.remaining_gaps?.length > 0 && (
                        <div className="bg-hydra-card border border-hydra-border rounded-lg p-4">
                            <h3 className="text-sm font-medium text-gray-400 mb-2">Remaining Gaps</h3>
                            {result.remaining_gaps.map((g, i) => <p key={i} className="text-sm text-gray-500 mb-1">{g}</p>)}
                        </div>
                    )}
                </div>
            )}

            {/* History */}
            {history.length > 1 && (
                <div className="mt-8 border-t border-hydra-border pt-4">
                    <h3 className="text-sm text-gray-500 mb-3">Previous queries</h3>
                    {history.slice(1).map((h, i) => (
                        <div key={i} className="text-sm text-gray-600 py-1 cursor-pointer hover:text-gray-400"
                             onClick={() => setQuery(h.query)}>
                            <span className="text-gray-500">{h.time.toLocaleTimeString()}</span>
                            {' '}{h.query.slice(0, 80)}
                            <span className="ml-2 text-xs">({h.result?.confidence?.overall || '?'}/100)</span>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('app')).render(React.createElement(App));
