import {useEffect, useRef, useState} from 'react';
import { useLocation, useParams } from "react-router";

import './app.css';

import Sidebar from './components/sidebar/sidebar';
import Content from './components/content/content';

const files = [
	{
		id: '1',
		title: 'kaas',
		items: [
			{ type: 'plain', text: 'kaas 1' },
			{ type: 'plain', text: 'kaas 2' },
			{ type: 'plain', text: 'kaas 3' },
			{ type: 'plain', text: 'kaas 4' },
			{ type: 'plain', text: 'kaas 5' },
		],
	},
	{
		id: '2',
		title: 'ham',
		items: [
			{ type: 'plain', text: 'ham 1' },
			{ type: 'plain', text: 'ham 2' },
			{ type: 'plain', text: 'ham 3' },
			{ type: 'plain', text: 'ham 4' },
			{ type: 'plain', text: 'ham 5' },
		],
	},
	{
		id: '3',
		title: 'vis',
		items: [
			{ type: 'plain', text: 'vis 1' },
			{ type: 'plain', text: 'vis 2' },
			{ type: 'plain', text: 'vis 3' },
			{ type: 'plain', text: 'vis 4' },
			{ type: 'plain', text: 'vis 5' },
		],
	},
	{
		id: '4',
		title: 'empty',
		items: [
			{ type: 'plain', text: '' },
		],

		children: [{
			id: '4/5',
			title: 'empty 2',
			items: [
				{ type: 'plain', text: '' },
			],
		}],
	},
]

function splitOnce(str, sep) {
	const idx = str.indexOf(sep);
	if (idx === -1) return [str, ''];

	return [ str.slice(0, idx), str.slice(idx+1) ];
}

export default function App() {
	const e = useLocation();
	const fullPath = e.pathname.replace('/file/', '');
	let path = fullPath;

	let cur = { children: files };
	let builtKey = '';
	while (path != '') {
		let key;
		[key, path] = splitOnce(path, '/');
		builtKey += `/${key}`;

		console.log(key, path, cur);
		cur = (cur.children ?? []).find(p => p.id === builtKey.slice(1));
	}

	const file = cur;
	const [title, setTitle] = useState(() => file.title);
	const [items, setItems] = useState(() => file.items);

	useEffect(() => {
		setTitle(() => file.title);
		setItems(() => file.items);

		document.title = '🧀🥜 ' + file.title;
	}, [fullPath]);

	return <div className='app'>
		<Sidebar files={files} />
		<Content title={title} items={items} setTitle={setTitle} setItems={setItems} />
	</div>
}
