import React, { useState, useEffect } from 'react';
import { Marked } from 'marked';

const marked = new Marked({ breaks: true, gfm: true });

export default function DocsPage() {
    const [content, setContent] = useState('');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [search, setSearch] = useState('');
    const [toc, setToc] = useState([]);

    useEffect(() => {
        fetch('/DOKUMENTATION.md')
            .then(res => { if (!res.ok) throw new Error(); return res.text(); })
            .then(text => {
                setContent(text);
                // Extract headings for TOC
                const headings = [];
                const lines = text.split('\n');
                lines.forEach(line => {
                    const h2 = line.match(/^## (.+)/);
                    const h3 = line.match(/^### (.+)/);
                    if (h2) headings.push({ level: 2, text: h2[1], id: slugify(h2[1]) });
                    if (h3) headings.push({ level: 3, text: h3[1], id: slugify(h3[1]) });
                });
                setToc(headings);
            })
            .catch(() => setError('Dokumentation konnte nicht geladen werden.'))
            .finally(() => setLoading(false));
    }, []);

    const slugify = (text) =>
        text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-').trim();

    const getHtml = () => {
        let text = content;
        if (search.trim()) {
            // Highlight search terms
            const regex = new RegExp(`(${search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
            text = text.replace(regex, '**$1**');
        }
        // Add IDs to headings for anchor links
        const html = marked.parse(text);
        return html.replace(/<h([23])>(.*?)<\/h\1>/g, (_, level, heading) => {
            const id = slugify(heading.replace(/<[^>]+>/g, ''));
            return `<h${level} id="${id}">${heading}</h${level}>`;
        });
    };

    if (loading) return (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh', color: 'var(--text-muted)' }}>
            Dokumentation wird geladen...
        </div>
    );

    if (error) return (
        <div style={{ padding: '40px', color: 'var(--danger)', textAlign: 'center' }}>{error}</div>
    );

    return (
        <div style={{ display: 'flex', maxWidth: '1200px', margin: '0 auto', padding: '32px 24px', gap: '32px' }}>

            {/* Sidebar TOC */}
            <aside style={{
                width: '240px',
                flexShrink: 0,
                position: 'sticky',
                top: '24px',
                alignSelf: 'flex-start',
                maxHeight: 'calc(100vh - 80px)',
                overflowY: 'auto',
            }}>
                <div style={{
                    background: 'var(--bg-card)',
                    border: '1px solid var(--border-color)',
                    borderRadius: 'var(--radius-xl)',
                    padding: '16px',
                }}>
                    <div style={{ fontSize: '11px', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '12px' }}>
                        Inhalt
                    </div>
                    {toc.map((item, i) => (
                        <a
                            key={i}
                            href={`#${item.id}`}
                            style={{
                                display: 'block',
                                padding: item.level === 2 ? '5px 0' : '3px 0 3px 12px',
                                fontSize: item.level === 2 ? '13px' : '12px',
                                fontWeight: item.level === 2 ? 600 : 400,
                                color: item.level === 2 ? 'var(--text-primary)' : 'var(--text-muted)',
                                textDecoration: 'none',
                                borderLeft: item.level === 3 ? '2px solid var(--border-color)' : 'none',
                                lineHeight: '1.4',
                            }}
                            onMouseEnter={e => e.currentTarget.style.color = 'var(--cereda-primary)'}
                            onMouseLeave={e => e.currentTarget.style.color = item.level === 2 ? 'var(--text-primary)' : 'var(--text-muted)'}
                        >
                            {item.text}
                        </a>
                    ))}
                </div>
            </aside>

            {/* Main content */}
            <main style={{ flex: 1, minWidth: 0 }}>
                {/* Header */}
                <div style={{ marginBottom: '24px' }}>
                    <h1 style={{ fontSize: '22px', fontWeight: 700, color: 'var(--text-primary)', margin: '0 0 6px', display: 'flex', alignItems: 'center', gap: '10px' }}>
                        📄 Dokumentation
                    </h1>
                    <p style={{ color: 'var(--text-muted)', fontSize: '14px', margin: 0 }}>
                        IT Nexus – Vollständige Systemdokumentation
                    </p>
                </div>

                {/* Search */}
                <div style={{ marginBottom: '24px' }}>
                    <input
                        type="text"
                        className="form-input"
                        placeholder="In Dokumentation suchen..."
                        value={search}
                        onChange={e => setSearch(e.target.value)}
                        style={{ maxWidth: '360px' }}
                    />
                </div>

                {/* Markdown content */}
                <div
                    className="docs-content"
                    dangerouslySetInnerHTML={{ __html: getHtml() }}
                />
            </main>
        </div>
    );
}
