/**
 * Diff Viewer — unified diff with syntax coloring
 * Ball Studios <https://git.balls.studio>
 */

import React, { useEffect, useState } from 'react';
import http from '@/api/http';

interface DiffLine {
    type: 'context' | 'added' | 'removed' | 'header';
    content: string;
    line_old?: number;
    line_new?: number;
}

interface Props {
    serverUuid: string;
    revision: { id: number; revision_number: number };
    onClose: () => void;
}

export default function DiffViewer({ serverUuid, revision, onClose }: Props) {
    const [lines, setLines]     = useState<DiffLine[]>([]);
    const [binary, setBinary]   = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        http.get(`/api/client/servers/${serverUuid}/addons/files/revisions/${revision.id}/diff`)
            .then(({ data }) => {
                setBinary(data.binary);
                setLines(data.lines ?? []);
            })
            .finally(() => setLoading(false));
    }, [serverUuid, revision.id]);

    return (
        <div className='addon-modal-overlay' onClick={onClose} role='dialog' aria-modal='true'>
            <div className='addon-modal addon-modal-wide' onClick={e => e.stopPropagation()}>
                <div className='addon-modal-header'>
                    <span>Diff — Revision #{revision.revision_number}</span>
                    <button className='addon-modal-close' onClick={onClose} aria-label='Close'>✕</button>
                </div>
                {loading && <div className='addon-loading'>Loading diff…</div>}
                {!loading && binary && <div className='addon-empty'>Binary file — diff not available.</div>}
                {!loading && !binary && (
                    <pre className='addon-diff'>
                        {lines.map((line, i) => (
                            <div
                                key={i}
                                className={`addon-diff-line addon-diff-${line.type}`}
                            >
                                <span className='addon-diff-lnum'>
                                    {line.line_old ?? ' '} {line.line_new ?? ' '}
                                </span>
                                <span className='addon-diff-sign'>
                                    {line.type === 'added' ? '+' : line.type === 'removed' ? '−' : ' '}
                                </span>
                                {line.content}
                            </div>
                        ))}
                    </pre>
                )}
            </div>
        </div>
    );
}
