
const COLUMNS = [
    { title: "Em orçamento",         colorVar: "--text-secondary" },
    { title: "Aguardando aprovação", colorVar: "--blue" },
    { title: "Orçamento aprovado",   colorVar: "--accent" },
    { title: "Em execução",          colorVar: "--accent",  highlight: true },
    { title: "Aguardando peça",      colorVar: "--red" },
    { title: "Serviço concluído",    colorVar: "--green" },
];

function KanbanCard({ vehicle, mechanics, onChangeMechanic, onArchive, onClick }) {
    const statusColors = {
        "Em execução":        "--accent",
        "Orçamento aprovado": "--accent",
        "Aguardando peça":    "--red",
        "Serviço concluído":  "--green",
        "Aguardando aprovação": "--blue",
    };
    const borderColor = statusColors[vehicle.status] ? `var(${statusColors[vehicle.status]})` : 'var(--border-light)';

    return (
        <div onClick={() => onClick(vehicle.id)} style={{
            background: 'var(--bg)', border: '1px solid var(--border)',
            borderLeft: `3px solid ${borderColor}`,
            padding: '14px 16px', borderRadius: '6px', cursor: 'pointer',
            transition: 'transform 0.15s, box-shadow 0.15s',
            maxWidth: '100%', maxHeight: '260px', overflow: 'hidden',
            overflowWrap: 'anywhere', wordBreak: 'break-word',
        }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 16px rgba(0,0,0,0.5)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}
        >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '6px' }}>
                <h3 className="text-clamp-2" title={vehicle.vehicle_model} style={{
                    fontSize: '1rem', lineHeight: 1.3, margin: 0, fontFamily: 'var(--font-display)',
                    minWidth: 0, flex: '1 1 auto'
                }}>
                    {vehicle.vehicle_model}
                </h3>
                <span className="text-truncate" title={vehicle.license_plate} style={{
                    fontFamily: 'var(--font-mono)', background: 'var(--surface-2)',
                    border: '1px solid var(--border)', padding: '1px 7px', borderRadius: '3px',
                    fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.06em', flexShrink: 0,
                    marginLeft: '8px', maxWidth: '110px'
                }}>{vehicle.license_plate}</span>
            </div>

            <p className="text-clamp-2" title={vehicle.service_type} style={{
                color: 'var(--text-secondary)', fontSize: '0.8rem', marginBottom: '12px', lineHeight: 1.4
            }}>
                {vehicle.service_type}
            </p>

            <div style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                borderTop: '1px dashed var(--border)', paddingTop: '8px',
                fontFamily: 'var(--font-mono)', fontSize: '0.7rem', color: 'var(--text-muted)'
            }}>
                <select 
                    style={{
                        background: 'var(--surface-2)', border: '1px solid var(--border)', 
                        color: 'var(--text-primary)', borderRadius: '4px', fontSize: '0.7rem',
                        padding: '2px 4px', cursor: 'pointer', maxWidth: '120px'
                    }}
                    value={vehicle.mechanic?.id || ""} 
                    onClick={e => e.stopPropagation()}
                    onChange={e => onChangeMechanic(vehicle.id, e.target.value)}
                >
                    <option value="">NÃO ATRIBUÍDO</option>
                    {mechanics.map(m => (
                        <option key={m.id} value={m.id}>{m.name}</option>
                    ))}
                </select>

                <span style={{ color: 'var(--text-secondary)' }}>#{String(vehicle.id).padStart(4,'0')}</span>
            </div>
        </div>
    );
}

function TvMode() {
    const { useState, useEffect, useCallback } = React;
    const [vehicles, setVehicles] = useState([]);
    const [mechanics, setMechanics] = useState([]);
    const [currentTime, setCurrentTime] = useState(
        new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
    );
    const [selectedVehicle, setSelectedVehicle] = useState(null);

    const loadData = useCallback(() => {
        window.api.getVehicles().then(setVehicles).catch(() => {});
    }, []);

    useEffect(() => {
        loadData();
        window.api.getMechanics().then(setMechanics).catch(() => {});
        const dataInterval = setInterval(loadData, 5000);
        const clockInterval = setInterval(() => {
            setCurrentTime(new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }));
        }, 1000);
        return () => { clearInterval(dataInterval); clearInterval(clockInterval); };
    }, [loadData]);

    const handleMechanicChange = async (vehicleId, mechanicId) => {
        const val = mechanicId ? parseInt(mechanicId) : null;
        await window.api.updateVehicle(vehicleId, { mechanic_id: val });
        loadData();
    };

    const handleArchive = async (vehicleId) => {
        await window.api.updateVehicle(vehicleId, { status: "Entregue" });
        loadData();
    };

    const totalActive = vehicles.filter(v => v.status !== 'Serviço concluído').length;

    return (
        <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--bg)', overflow: 'hidden' }}>
            {/* Header */}
            <header style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '10px 28px', borderBottom: '1px solid var(--border)',
                background: 'var(--bg-secondary)', flexShrink: 0
            }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: '2px', cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}
                     onClick={() => window.location.href = '/'}>
                    <span style={{ fontFamily: 'var(--font-display)', color: 'var(--accent)', fontSize: '1.25rem', fontWeight: 800 }}>MAC</span>
                    <span style={{ color: 'var(--text-muted)', fontSize: '1.1rem', fontWeight: 700 }}>//</span>
                    <span style={{ fontFamily: 'var(--font-display)', color: 'var(--text-primary)', fontSize: '1.25rem', fontWeight: 800 }}>SHOP FLOOR</span>
                </div>

                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <span style={{
                        padding: '4px 12px', background: 'var(--surface)', border: '1px solid var(--border)',
                        borderRadius: '20px', fontSize: '0.75rem', color: 'var(--text-secondary)',
                        whiteSpace: 'nowrap', flexShrink: 0
                    }}>
                        {totalActive} ativos · auto-refresh 5s
                    </span>
                </div>

                <div style={{
                    fontFamily: 'var(--font-display)', fontSize: '2rem', fontWeight: 800,
                    color: 'var(--accent)', letterSpacing: '0.05em',
                    fontVariantNumeric: 'tabular-nums'
                }}>{currentTime}</div>
            </header>

            {/* Kanban */}
            <div style={{
                display: 'flex', flex: 1, padding: '14px', gap: '12px',
                overflowX: 'auto', overflowY: 'hidden'
            }}>
                {COLUMNS.map(col => {
                    const colVehicles = vehicles.filter(v => v.status === col.title);
                    const count = colVehicles.length;
                    return (
                        <div key={col.title} style={{
                            flex: 1, minWidth: '240px', display: 'flex', flexDirection: 'column',
                            background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '8px',
                            borderTop: col.highlight ? `3px solid var(--accent)` : `3px solid ${col.colorVar.startsWith('--') ? `var(${col.colorVar})` : col.colorVar}`
                        }}>
                            {/* Col header */}
                            <div style={{
                                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                                padding: '12px 14px', borderBottom: '1px solid var(--border)',
                                background: col.highlight ? 'var(--accent-glow)' : 'var(--surface-2)',
                            }}>
                                <h2 style={{
                                    fontSize: '0.8rem', fontWeight: 700, textTransform: 'uppercase',
                                    letterSpacing: '0.06em', margin: 0,
                                    color: col.highlight ? 'var(--accent)' : `var(${col.colorVar})`
                                }}>{col.title}</h2>
                                <span style={{
                                    background: count > 0 ? `var(${col.colorVar})` : 'var(--surface)',
                                    color: count > 0 ? '#000' : 'var(--text-muted)',
                                    width: '22px', height: '22px', borderRadius: '50%',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    fontSize: '0.7rem', fontWeight: 800
                                }}>{count}</span>
                            </div>

                            {/* Col content */}
                            <div style={{
                                flex: 1, padding: '12px', overflowY: 'auto',
                                display: 'flex', flexDirection: 'column', gap: '10px'
                            }}>
                                {colVehicles.map(v => (
                                    <KanbanCard 
                                        key={v.id} 
                                        vehicle={v} 
                                        onClick={setSelectedVehicle} 
                                        mechanics={mechanics}
                                        onChangeMechanic={handleMechanicChange}
                                        onArchive={handleArchive}
                                    />
                                ))}
                                {count === 0 && (
                                    <div style={{
                                        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        color: 'var(--text-muted)', fontSize: '0.75rem', fontStyle: 'italic'
                                    }}>vazio</div>
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>

            <window.VehicleModal
                vehicleId={selectedVehicle}
                isOpen={!!selectedVehicle}
                onClose={() => setSelectedVehicle(null)}
                onUpdated={loadData}
                onDeleted={(id) => setVehicles(prev => prev.filter(v => v.id !== id))}
            />
        </div>
    );
}

window.TvMode = TvMode;
